#include "Parallel_FLASH.h"
#include "def21364.h"
#include "Cdef21364.h"

void Write_Parallel_Port(int address,int data)
{
	int i=0;
	
	*pEIPP=address;
	
	*pEMPP=1;
	
	*pPPCTL=0;
	
	*pPPCTL=PPDUR32|PPEN| PPTRAN|PPFLMD;
	
	*pTXPP=data;
	
	for(i=0;i<6;i++);
	
	while((*pPPCTL&BIT_17)!=0);
	
}

void Setup_for_flash()
{
	*pPPCTL=PPDUR32;
	
}


void erase_sector(int address)

{
	int temp=0,temp1,temp2,temp3, temp4;
	
	int done=0;
	
	Write_Parallel_Port(address,0x55aa0000);
			
	Write_Parallel_Port(address,0x3055aa80);
	
	while(1)
	{
		temp = Read_FLASH_MASK(address,0xFFFFFFFF);
		
		temp1=temp&0x000000FF;
		
		temp2=(temp&0x0000FF00)>>8;
	
		if(temp1==temp2)
		{
			
			done=1;
			break;
		}
		
		if(temp1&0x20!=0)
				break;
		
		temp1=(temp&0x00FF0000)>>16;
		
		temp2=(temp&0xFF000000)>>24;
		
		if(temp1==temp2)
		{
			
			done=1;
			break;
		}
		
		if(temp1&0x20!=0)
				break;
		
		
	}
	
	if(done!=1)
	{
		
		temp = Read_FLASH_MASK(address,0xFFFFFFFF);
		
		temp1=temp&0x000000FF;
		
		temp2=(temp&0x0000FF00)>>8;
	
		if(temp1==temp2)
			done=1;
	
	}
	
	if(done!=1)
	{
		int error=1;
	}
}


void Write_FLASH(int byte_address, int data)
{
	
	
	int temp,temp1,temp2,temp3,temp4;
	
	int done=0;
	
	temp=0xa055aa00;
	
	Write_Parallel_Port(byte_address,temp);
	
	temp=data&0x000000FF;
	
	Write_Parallel_Port(byte_address,temp);
			
	while(1)
	{
		temp = Read_FLASH_MASK(byte_address,0x000000FF);
		
		if(temp==data)
		{
			done=1;
			break;
		}
		
		else
		
		if((temp&0x20)!=0)
				break;
		
	}
	
	if(done!=1)
	{
		
		temp = Read_FLASH_MASK(byte_address,0x00000000);
		
		if(temp==data)
			done=1;
	
	}
	
	if(done!=1)
	{
		int error=1;
	}
	
}

int Read_FLASH(int byte_address)
{
	return Read_FLASH_MASK(byte_address, 0x000000FF);
}


int Read_FLASH_MASK(int byte_address,int mask)
{
	
	int temp;
	
	while((*pPPCTL&PPS0)==1||(*pPPCTL&PPS1)==1);
		
	//Read
	*pEIPP=byte_address;
	
	*pEMPP=1;
	
	*pPPCTL=PPDUR32|PPEN|PPFLMD;
	
	while((*pPPCTL&(PPS0|PPS1))==0);
	
	temp=*pRXPP;
	
	*pPPCTL=0;
	
	temp&=mask;
	
	return temp;
}
