#include "config.h"

void main()

{
	
		Init_PLL();
		Init_ASYNC_Memory();
		Init_GPIO();
		Enable_Interrupt();
		
			
		#ifndef HOST_READ
		
		Fill_Master_Buffer();
	
		#endif
		
		Config_MemDMA();
			
	
		// 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)

{
		*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 Fill_Master_Buffer(void)
{
	
		//Fill the buffer, so that slave reads this data
		short fill_data = 0x1111;
		for(i=0; i<Transfer_Size; i++)
		{
			
			Master_Buffer[i] = fill_data;
			fill_data += 0x1111;
			
			
		}
		
}


void Config_MemDMA(void)
{
	
		#ifdef HOST_READ
	
		// From ASYNC Memory to Buffer
	
		*pMDMA_S0_START_ADDR = 0x20300000;
		*pMDMA_D0_START_ADDR = Master_Buffer;
	
		#else
	
		//From Buffer to ASYNC Memory
	
		*pMDMA_S0_START_ADDR = Master_Buffer;
		*pMDMA_D0_START_ADDR = 0x20300000;
	
		#endif
	
		*pMDMA_S0_CONFIG = WDSIZE_16;
		*pMDMA_S0_X_COUNT = Transfer_Size;
		*pMDMA_S0_X_MODIFY = 2;
		*pMDMA_S0_Y_COUNT = 0;
		*pMDMA_S0_Y_MODIFY = 0;
	
		*pMDMA_D0_CONFIG = WDSIZE_16 | WNR;
		*pMDMA_D0_X_COUNT = Transfer_Size;
		*pMDMA_D0_X_MODIFY = 2;
		*pMDMA_D0_Y_COUNT = 0;
		*pMDMA_D0_Y_MODIFY = 0;
	

}


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


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();
	
}


	
EX_INTERRUPT_HANDLER(PG13_ISR)
{
	
		ISR_Count++;
		*pPORTGIO_CLEAR = PG13;		// acknowledge the interrupt
		ssync();
	
		// For Auto Buffer DMA, disable the DMA Channel and then re-enable it.
		
		*pMDMA_S0_CONFIG &= 0xFFFE;
		*pMDMA_D0_CONFIG &= 0xFFFE;
	
		
		// Enable the DMA to perform the data transfer here
		
		*pMDMA_S0_CONFIG |= 1;
		*pMDMA_D0_CONFIG |= 1;
}

	
