#include<cdefBF537.h>
#include<ccblkfn.h>
#include<sys/exception.h>

#define SystemCLK	 100000		//Value in KHz
#define VCO_CoreCLK  1			//Value of VCO/CCLK - value can be 1, 2, 4, 8
#define VCO			 500000		//Value in KHz
#define CLKin		 27000

#define HostWrite

void ConfigurePLL(void);
void ConfigureAsyncMem(void);
short StatusRead(void);



void ConfigureHDMA(void);
void DataTransfer(void);
void SetUpWriteData(void);

EX_INTERRUPT_HANDLER (MemDMA);


int Status;
short ConfigurationWord[7] = {0x00A9, 0x060, 0xFF90, 0x10, 0x2, 0x0, 0x0};
char DataIn[32];
char DataOut[32];
/*
HOST_CONFIG - 0x00A9 = Host Read Operation, 1D DMA, Stop Mode; 0x00AB for writes
START_ADDR.L - 0x0060
START_ADDR.H - 0xFF90
XCOUNT - 0x10 - for 8 bit, count is 1/2 of total transfers (total is 32). 
XMODIFY - 0x2
YCOUNT - 0x0
YMODIFY - 0x0
*/

section("hdma_command") short Command;
section("hdma_data") char Data;

void main()
{
	int j;
	
	ConfigurePLL();
	ConfigureAsyncMem(); 
	#ifdef HostWrite
		SetUpWriteData();
		ConfigurationWord[0] = 0x00AB;
	#endif
	
	do		//Poll on the ALLOW_CONFIG bit. Do configuration only if this bit is set.
	{
		Status = StatusRead();	
	}while((Status & 0x80)!=0x80);
	
	ConfigureHDMA();
	ssync();
	
	do
	{
		Status = StatusRead();	
	} while((Status & 0x1)!=0x1);
		
	DataTransfer();
	
	while(1);
}

void ConfigurePLL()
{
	*pSIC_IWR = 0x1;
	*pPLL_CTL = SET_MSEL(VCO / CLKin);
	ssync();
	idle();
	*pPLL_DIV = SET_SSEL(VCO / SystemCLK) | ((VCO_CoreCLK)&0x30);
	asm("ssync;");
}


void ConfigureAsyncMem()
{
	*pEBIU_AMBCTL1 = 0xFFC355C0;
	*pEBIU_AMGCTL = 0xFF;
}

short StatusRead(void)
{
	short temp;
	temp = Command;
	return temp;
}

void SetUpWriteData()
{
	int i;
	for(i=0;i<32; i++)
	{
		DataOut[i] = i+10;
	}
}

void ConfigureHDMA()
{
	int i;
	short temp;
	for(i=0; i<7; i++)
	{
		
		temp = ConfigurationWord[i];
		Command = temp;
		ssync();
		
		// Write the MSB
		temp >>= 8;
		Command = temp;
		ssync();
		
	}
}

void DataTransfer()
{
	int i;
	for(i=0; i<32; i++)
	{
		#ifdef HostWrite
		Data = DataOut[i];
		#else
		DataIn[i] = Data;
		#endif
	}

}


