#include "config.h"

void main()

{
	
	 		Init_PLL();
			Init_ASYNC_Memory();
			Init_GPIO();
			Enable_Interrupt();
		
	
			// For HOST_WRITE operation, fill the buffer so that Slave reads this data
		
			#ifndef HOST_READ		
		
			Fill_Master_Buffer();	
		
			#endif
	
			// Read HOST_STATUS to check if ALLOW_CONFIG is set.
	
			while (!(*pCONFIG_READ_WRITE_ADDR & 0x0080));
			HDMA_Config();
			asm("nop;");
			while(1)
			{
			}
		
}
		 
	
void Init_PLL(void)

{
			*pSIC_IWR = 1;
			*pPLL_CTL = MSELECT;
			ssync();
			idle();
			*pPLL_DIV = CSELECT | SSELECT;
			ssync();
	
}

void Init_ASYNC_Memory(void)
{
			*pEBIU_AMBCTL0 = 0xFFC2FFC2;
			*pEBIU_AMBCTL1 = 0xFFC3FFC2;
			*pEBIU_AMGCTL = 0x00FE;	//enable all banks
			ssync();
}


void Init_GPIO(void)

{
	
			*pPORTGIO_DIR 	= 0;
			*pPORTGIO_INEN 	= PG13;
			*pPORTGIO_EDGE 	= PG13;
			*pPORTGIO_POLAR	= PG13;		//Falling edge sensitive
			*pPORTGIO_MASKA = PG13;
	
}


void Enable_Interrupt(void)
{
	
			register_handler(ik_ivg12, PG13_ISR);	

			// enable FLAG A Interrupt on Port G
			*pSIC_IMASK = 0x08000000;
			ssync();
	
}

void Fill_Master_Buffer(void)
{
	
			//Fill the buffer, so that slave reads this data
		
			for(i=0; i<Transfer_Size; i++)
			{
			
				Master_Buffer[i] = i;
			
			
			}
		
}

void HDMA_Config(void)
{
	
			for(i=0; i<7; i++)
		
			{		
				data = HDMA_Config_Words[i];
		
				*pCONFIG_READ_WRITE_ADDR = data;	
				ssync();
				
				//Write the MSB
				data >>= 8;
				*pCONFIG_READ_WRITE_ADDR = data;	
				ssync();
			
			
			}
			
			//Read HOST_STATUS to check if HDMA Port is ready
			while (!(*pCONFIG_READ_WRITE_ADDR & 0x0001));
		
		
}

		
EX_INTERRUPT_HANDLER(PG13_ISR)
{
	
			ISR_Count++;
	
			*pPORTGIO_CLEAR = PG13;		// acknowledge the interrupt
			ssync();
		
			for(i=0; i<Transfer_Size; i++)
			{
		
			Data_Transfer();
		
			}
		
		
}


void Data_Transfer(void)
{
	

			#ifdef HOST_READ
			
			
			Master_Buffer[i] = *pDATA_READ_WRITE_ADDR;
			
			#else
			
					
			*pDATA_READ_WRITE_ADDR = Master_Buffer[i]; 
			
			#endif
				
}
