/*******************************************************************
*  include files
*******************************************************************/
#include <stdio.h>
#include <sys\exception.h>	// Interrupt Handling Header
#include <ccblkfn.h>
#include <sysreg.h>
#include <signal.h>
#include "m24c02.h"


/*******************************************************************
*  global variables and defines
*******************************************************************/
#define BUFFER_SIZE	128
#define MAX_WRITE_SIZE 16

/*******************************************************************
*   Function:    TEST_LCD_CONFIGFLASH
*   Description: Main test routine will get launched from the POST
*				 framework.
*******************************************************************/
int TEST_LCD_CONFIGFLASH(void)
{
	int bPassed = 1;
	int i = 0;
	int j = 0;
	unsigned char dataIn[BUFFER_SIZE];
	unsigned char SavedData[BUFFER_SIZE];
	unsigned char dataOut[BUFFER_SIZE];
	unsigned int uiAddress = 0;

	/* reset the TWI interface */
	m24c02_Reset_TWI();

	/* read the configuration flash contents so we can put them back */
	ReadM24C02(uiAddress, SavedData, BUFFER_SIZE);
	
	/* initialize our buffer */
	for( i = 0; i < BUFFER_SIZE; i++ )
		dataIn[i] = (unsigned char)(i & 0xFF);

	/* write our buffer to the configuration flash */
	for( i = 0; i < BUFFER_SIZE / MAX_WRITE_SIZE; i++ )
	{
		WriteM24C02(uiAddress, &dataIn[uiAddress], MAX_WRITE_SIZE);
		uiAddress += 16;

		for( j = 0; j < 0x7FFFF; j++ )
		{
			asm("nop;");
		}
	}
	
	/* reset the address for the read */
	uiAddress = 0;

	/* read the configuration flash back so we can verify */
	ReadM24C02(uiAddress, dataOut, BUFFER_SIZE);

	/* write our saved contents back */
	for( i = 0; i < BUFFER_SIZE / MAX_WRITE_SIZE; i++ )
	{
		WriteM24C02(uiAddress, &SavedData[uiAddress], MAX_WRITE_SIZE);
		uiAddress += 16;

		for( j = 0; j < 0x7FFFF; j++ )
		{
			asm("nop;");
		}
	}
	
	/* check to see if the buffers match */
	for( i = 0; i < BUFFER_SIZE; i++)
	{
		if( dataIn[i] != dataOut[i] )
		{
			bPassed = 0;
			break;
		}
	}

	return bPassed;
}

#ifdef _STANDALONE_

#include <bfrom.h>

int main(void)
{
	int bPassed = 1;
	int count = 0;

	/* use Blackfin ROM SysControl() to change the PLL */
    ADI_SYSCTRL_VALUES sys_cntrl_struct;

	sys_cntrl_struct.uwPllCtl = 0x2000;		/* (25MHz CLKIN x (MSEL=16))::CCLK = 400MHz */
	sys_cntrl_struct.uwPllDiv = 0x0005;		/* (400MHz/(SSEL=5))::SCLK = 80MHz */

	bfrom_SysControl( SYSCTRL_WRITE | SYSCTRL_PLLCTL | SYSCTRL_PLLDIV,
					  &sys_cntrl_struct, NULL);

	bPassed = TEST_CONFIGFLASH();

	return bPassed;
}
#endif /* #ifdef _STANDALONE_ */
