#include "Parallel_FLASH.h"
#include "def21469.h"
#include "Cdef21469.h"

void Setup_for_flash()
{
	*pEPCTL = (((*pEPCTL) & (~B1SD)) | EPBRCORE);

	*pAMICTL1 = ( PKDIS | WS31 | HC1 | HC2 | RHC1 | RHC2 | IC7 | AMIEN | AMIFLSH);
	
}


void erase_sector(int address)

{
	int temp=0;
	
	int* start_add; 
	int* add;
	
	
	start_add=(int*)(FLASH_START_ADDRESS);
	
	
	add=start_add+0xAAA;
	
	*add = 0x000000aa;
	
	add=start_add+0x555;
			
	*add = 0x00000055;
	
	add=start_add+0xAAA;
	
	*add = 0x00000080;
	
	add=start_add+0xAAA;
	
	*add = 0x000000aa;
	
	add=start_add+0x555;
	
	*add = 0x00000055;
	
	add=start_add+address;
	
	*add=0x30;
	
	while(temp!=0xFF)
		temp=*add;
}


void Write_FLASH(int byte_address, int data)
{
	
	
	int temp,temp1,temp2;
	
	int done=0;
	
	int* start_add;
	int* add;
	
	
	start_add=(int*)(FLASH_START_ADDRESS);
	
	add=start_add+0xAAA;
	
	*add = 0x000000aa;
	
	add=start_add+0x555;

	*add = 0x00000055;
	
	add=start_add+0xAAA;
	
	*add = 0x000000a0;

	add=start_add+byte_address;
	
	*add =	data;
	
	while(1)
	{
		temp = Read_FLASH(byte_address);
		
		temp1=temp&0x00000080;
		
		temp2=data&0x00000080;
		
		if(temp1==temp2)
		{
			done=1;
			break;
		}
		
		temp1=temp&0x00000020;
		
		if(temp1==0x00000020)
			break;
	}
	
	if(done!=1)
	{
		temp=Read_FLASH(byte_address);
		
		temp1=temp&0x00000080;
		
		
		temp2=data&0x00000080;
		
		if(temp1==temp2)
		
			done=1;
	}
	
	if(done!=1)
	{
		int error=1;
	}
	
	
}

int Read_FLASH(int byte_address)
{
	
	int temp;
	
	int *add = (int*)(FLASH_START_ADDRESS+byte_address);
	
	temp = *add;
	
	return temp;
}
