#include "def21262.h"
#include "Cdef21262.h"
#include "sru21262.h"
#include "21262_SSL_Parallel_FLASH.h"
#include "stdio.h"

int app_offset=0x0;

void firmware_upgrade()
{
	
	
	int offset;
	
	int temp,i=0,j=0;
	
	int temp1;
	
	int length_ldr;
	
	int baud;
	
	int write_pointer=0;
	
	int sector_mask = 0x0000FFFF;
	
		
	//Signal the host that the slave is ready to communicate 				
	Write_UART(START_LOADING);
	
	/*----Receive 'length' of the .ldr file ---*/

		
	//Read the first least significant byte of 'length' 
	length_ldr=Read_UART();
	//Send acknowledgement to the host
	Write_UART(LENGTH_ACK);
	
	//Read the second least signnificant byte of 'length'
	temp=Read_UART();
	temp=temp<<8;
	length_ldr|=temp;
	//Send acknowledgement to the host
	Write_UART(LENGTH_ACK);
	
	//Read the third least signnificant byte of 'length'
	temp=Read_UART();
	temp=temp<<16;
	length_ldr|=temp;
	//Send acknowledgement to the host
	Write_UART(LENGTH_ACK);
	
	//Read the  most signnificant byte of 'length'
	temp=Read_UART();
	temp=temp<<24;
	length_ldr|=temp;
	//Send acknowledgement to the host
	Write_UART(LENGTH_ACK);
	
	
	/*----Receive 'FLASH Offset' ---*/
	
	//Read the first least  signnificant byte of 'offset'
	offset=Read_UART();
	//Send acknowledgement to the host
	Write_UART(OFFSET_ACK);

	//Read the second least  signnificant byte of 'offset'
	temp=Read_UART();
	temp=temp<<8;
	offset|=temp;
	//Send acknowledgement to the host
	Write_UART(OFFSET_ACK);
	
	
	//Read the third least  signnificant byte of 'offset'
	temp=Read_UART();
	temp=temp<<16;
	offset|=temp;
	//Send acknowledgement to the host
	Write_UART(OFFSET_ACK);
	
	//Read the most signnificant byte of 'offset'
	temp=Read_UART();
	temp=temp<<24;
	offset|=temp;
	Write_UART(OFFSET_ACK);
	
	app_offset=offset+0x600;
	
						
 	//Program the FLASH with the upgraded application
	while(i<length_ldr)
	{
		
		if((i%0x10000)==0)
			erase_sector(offset+i);
				
			//Read next byte sent by the PC		
			temp=Read_UART();
			
			//Program the byte received into the FLASH
			Write_FLASH(offset+i,temp);
			
						
			for(j=0;j<10000;j++);
		
			while((*pSPCTL1&(BIT_31))==0)
			{
					
					//Keep sendig the ackowledgement till a new byte is received 
					Write_UART(BYTE_RECEIVED);
					if(i==length_ldr-1)
						break;
			}
					
				i++;	
	}
	
	int ii=0;
	
	
}



	
void Init_SRU()
{
	
	SRU(HIGH,PBEN02_I);
	SRU(SPORT0_DA_O,DAI_PB02_I);
	
	SRU(LOW,PBEN04_I);
	SRU(DAI_PB04_O,SPORT1_DA_I);
	SRU(DAI_PB04_O,SPORT1_FS_I);
	
	SRU(SPORT0_CLK_O,SPORT0_CLK_I);
	SRU(SPORT1_CLK_O,SPORT1_CLK_I);
}

	
void Init_PLL()
{
	int temp,i;
	
	temp=PLLM16|DIVEN;
	
	*pPMCTL=temp;
	
	temp=*pPMCTL;
	
	temp|=PLLBP;
	
	temp^=DIVEN;
	
	*pPMCTL=temp;
	
	for(i=0;i<5000;i++);
	
	*pPMCTL^=PLLBP;
	
}