#include <stdio.h>
#include <conio.h>
#include<stdlib.h>
#include "..\..\..\lib\vp2k.h"

#define BUFFER_SIZE (2048+256)
uchar Wdata[BUFFER_SIZE];
uchar Rdata[2048];
int MaxBlock=0;
void TestS256(int size)
{ int i,key,block,offset;
  uchar *p1,*p2;
  unsigned long addr=0,error=0,MaxRamSize;

	MaxRamSize=size*1024UL;
	srand(*TimeTicks);
	for(i=0;i<BUFFER_SIZE;i++){
		Wdata[i]=random(256);
	}

	Print("Write data to SRAM.\n\r");
	for(i=0,addr=0;i<MaxBlock;i++,addr+=2048){
		Print("\rBlock %d",i);
		S256_WriteFn(addr,2048,Wdata+i);
	}
	Print("\n\rRead & Check data.\n\r");
	for(i=0,addr=0;i<MaxBlock;i++,addr+=2048){
		Print("\rBlock %d",i);
		S256_ReadFn(addr,2048,Rdata);
		for(offset=0,p1=Rdata,p2=Wdata+i;offset<2048;offset++){
			if(*p1 != *p2) {
				error++;
				Print("[%d(%02X):%02x-->%02x]",offset,offset,*p2,*p1);
				if(Kbhit()){
					Getch();
					goto End;
				}
			}
			p1++;
			p2++;
		}
	}
End:
  Print("\n\r--------->%lu errors\n\r",error);
}

void main(int argc,char *argv[])
{
	int ii;
	int status,mr;
	int size;	
	unsigned block=0;
    InitLib();
    
    status=GetBatteryStatus();
	if(status & BATTERY_LOW_1){
		Print("power of battery 1 is LOW\n\r");
		//power of battery 1 is LOW
	}
	else 
		Print("power of battery 1 is OK\n\r");
	if(status & BATTERY_LOW_2){
		Print("power of battery 2 is LOW\n\r");
		//power of battery 2 is LOW
	}
	else 
		Print("power of battery 2 is OK\n\r");
	
	switch(S256_Init())
	{
		case -256://low battery and 256K
			Print("low battery and 256K\n\r");
			size=256;
			MaxBlock=2048;
			break;
		case 256://battery OK and 256K
			Print("battery OK and 256K\n\r");
			size=256;
			MaxBlock=2048;
			break;
		case -512://low battery and 512K
			Print("low battery and 512K\n\r");
			size=512;
			MaxBlock=4096;
			break;
		case 512://battery OK and 512K
			Print("battery OK and 512K\n\r");
			size=512;
			MaxBlock=256;
			break;
		case 0:
			Print("Can not find S256/S512!");
			exit(1);
	}
	Print("Press any key to stop test.\n\r");
	while(!Kbhit()) TestS256(size);
	Getch();
}
