#include "minios7.h"
#include <stdlib.h>
#include <stdio.h>
#include "MFS.h"

#define  printf printCom1
#define  Print printCom1


#define _DISK_A     0
#define _DISK_B     1
#define _Test_Length 32767
#define _Test_Loop   1

char far sFileData[32767],sStandardData[32767];

#define BUFSIZE 1024       /* read/write buffer size */
#define SERVICE 10000      /* define the service port for Server */
#define SOCKETS 32         /* define the maximum number of sockets */
#define QLEN    SOCKETS-1  /* maximum connection queue length */

int es;       /* flag to run ES (service loop) */
fd_set rfds;  /* set of socket file descriptors for reading */
int c3Toc2=1,c2Toc3=0, iLength,er;
unsigned char item2,item3,item4;
int c3Head=0,c4Head=0,c2Head=0;
int RS_232 =0,RS_485=0;
long c3Index=0,c4Index=0,c2Index=0;
uchar Rdata[2048],C2Buf[1024],C3Buf[1024],C4Buf[1024],CBuf[1024];
#define BUFFER_SIZE (500)

char *keyname[]=
{
"UP:","LEFT:","DOWN:","CR:","RIGHT:","BS:","3:","6:","9:","0:","SHIFT:","DOT(.):","1:",
"4:","7:","8:","5:","2:","F1:","F2:","F3:","F6:","F5:","F4:"
};

int inc_flag[]=
{
18,19,20,23,22,21,12,13,14,17,16,15,6,7,8,11,10,9,0,1,2,5,4,3
};

typedef struct socket_state {
  int                active;  /* socket is active */
  int                init;    /* socket just initiated */
  struct sockaddr_in sin;     /* client address */
} socket_state;
socket_state sst[SOCKETS];    /* sockets state table */

unsigned char cIP_Net[4];     
unsigned char cGateway_Net[4];     
unsigned char cMask_Net[4];     
int needConfigIP=1;

int NetInit()
{
  struct sockaddr_in ssin; /* client Internet endpoing address */
  int sin_len;             /* length of sockaddr_in */
  int s;                   /* master socket for listenning */
  int ss;                  /* slave socket got from accept */
  int type, protocol, err=0;

  int rc;                  /* return code of selectsocket */
  int i,ret,ver,SlotType;
  char str[2048];
//  unsigned long far *IntVectMain=(unsigned long far *)0x00000000L;

  struct timeval   seltime;
  
  	
	if(needConfigIP==1)
	{
		cIP_Net[0]=192;
		cIP_Net[1]=168;
		cIP_Net[2]=255;
		cIP_Net[3]=1;
		SetIp(cIP_Net);		
		
		
		cMask_Net[0]=255;
		cMask_Net[1]=255;
		cMask_Net[2]=0;
		cMask_Net[3]=0;
		SetMask(cMask_Net);
		
		cGateway_Net[0]=192;
		cGateway_Net[1]=168;
		cGateway_Net[2]=0;
		cGateway_Net[3]=1;
		SetGateway(cGateway_Net);
	}						
		
			
	GetIp(cIP_Net);
	sprintf(str,"I:%d.%d.%d.%d",cIP_Net[0],cIP_Net[1],cIP_Net[2],cIP_Net[3]);
	LCD_PutsAt(0,0,str,0);
	GetMask(cMask_Net);
	sprintf(str,"M:%d.%d.%d.%d",cMask_Net[0],cMask_Net[1],cMask_Net[2],cMask_Net[3]);
	LCD_PutsAt(0,1,str,0);
	GetGateway(cGateway_Net);
	sprintf(str,"G:%d.%d.%d.%d",cGateway_Net[0],cGateway_Net[1],cGateway_Net[2],cGateway_Net[3]);
	LCD_PutsAt(0,2,str,0);
	//printf("\n\n**********************\n\n");
	
	
	
	  type = SOCK_STREAM;  /* TCP/IP */
	  protocol = 0;        /* always 0 */
	  err = s = socket( PF_INET, type, protocol );
	  if (s < 0)
	  {
		printf( "can't create socket! error %d\n\r", err );
		Nterm();
		return err;
	  }
	//	printf( "create socket seccessful!\n\r");
	  /********************************
	   * addressing for master socket *
	   ********************************/
	  memset( &sst[s].sin, 0, sizeof(sst[s].sin) ); /* bzero is a unix system call */
	  sst[s].sin.sin_family = AF_INET;
	  sst[s].sin.sin_addr.s_addr = 0; /* INADDR_ANY is a 32bits zero value */
	  sst[s].sin.sin_port = htons( SERVICE );
	
	  /*******************
	   * bind the socket *
	   *******************/
	  err = bind( s, (struct sockaddr *)&sst[s].sin, sizeof(sst[s].sin) );
	  if (err < 0)
	  {
		printf( "can't bind to port %d, error %d\n\r", SERVICE, err );
		closesocket( s );
		Nterm();
		return err;
	  }
		printf( "bind to port %d seccessful!\n\r",SERVICE);
	
	  /******************
	   * make listening *
	   ******************/
	  err = listen( s, QLEN );
	  if (type == SOCK_STREAM && err < 0)
	  {
		closesocket( s );
		Nterm();
		return err;
	  }
	//	printf( "Now Listening!\n\r");
	
	  /**********
	   * select *
	   **********/
	  FD_ZERO( &rfds );
	  es = 1;
	  for (i = 0; i < SOCKETS; i++)
	  {
		sst[i].active = 0;
		sst[i].init   = 0;
	  }
	  sst[s].active = 1;  /* master socket is active */
	  sin_len = sizeof( ssin );
	  seltime.tv_sec=0;
	  seltime.tv_usec=0;
	 	
	

	  
	  return 0;
}
  struct sockaddr_in ssin; /* client Internet endpoing address */
  int sin_len;             /* length of sockaddr_in */
  int s;                   /* master socket for listenning */
  int ss;                  /* slave socket got from accept */
  int type, protocol, err=0;
char Message1[]="connected successful.\r\n";

void RecCOM23(void)
{
	//c3Toc2 =0 com3 will receive data
    if(IsCom(3))                                                  
    { 
    	if(c3Toc2==1)  // 會從 COM3 送資料, COM2 會收到資料
    		printf("[%d] COM 3 can not receive any data here\n",c3Toc2);
    	                                                         
        item3=ReadCom(3); 
        //printf("%c\n",item3);
        if( c3Index==0)// check head
        {
        	c3Head=1;
        	if(item3!='#')
        	{
        		printf("\nCOM3 Head  %c [%d] Error\n",item3,c3Index);
        		exit(0);
        	}
        	else
        	{
        		//printf("COM3 Head %c [%d]\n",item3,c3Index);
        	}
        	C3Buf[c3Index]=item3;
        	//printf("%c\n",C3Buf[c3Index]);
        	c3Index++; 
        	
        }
        else // check end
        {
        	if(c3Head==1)
        	{
            	if(item3=='~')
            	{
            		C3Buf[c3Index]=item3;
            		//printf("%c\n",C3Buf[c3Index]);
            		c3Index++;
            		if(c3Index!=BUFFER_SIZE)
            		{
            			printf("\nCOM3 End %c [%d] Error\r\n",item3,c3Index); 
            			exit(0);
            		}
            		else
            		{
            			printf("COM2 --> COM3 Test OK [%d]B \r\n\n",c3Index);
            			
            			//printf("COM3 End %c [%d] \r\n\n",item3,c3Index); 
            		}
            		printf("=====================================\n\n");
            		ClearCom2();
            		ClearCom3();
            		//ClearCom4();
            		//RS_232=1;
            		RS_485=0;
            		c3Index=0;
            		c3Head=0;
            		c3Toc2=1;
            	}
            	else
            	{
            		if(item3!=':')
            		{
            			printf("\nCOM3 Body Error %c\n",item3);
            			exit(0);
            		}
            		else
            		{
            			//printf("COM3 Body %c [%d]\n",item3,c3Index);
            		}
            		C3Buf[c3Index]=item3;
            		//printf("%c\n",C3Buf[c3Index]);
            		c3Index++;
            	}
            }
        } 
        
                              
    }
    if(IsCom(2))                                                  
    {     
    	if(c3Toc2==0)
    	{
    		printf("[%d] COM 2 can not receive any data here\n",c3Toc2);	
    		exit(0);
    	}        	                                                       
        item2=ReadCom(2); 
        if( c2Index==0)// check head
        {
        	c2Head=1;
        	if(item2!='$')
        	{
        		printf("\nCOM2 Head  %c [%d] Error\n",item2,c2Index);
        		exit(0);
        	}
        	else
        	{
        		//printf("COM2 Head %c [%d]\n",item2,c2Index);
        	}
        	C2Buf[c2Index]=item2;
        	//printf("%c\n",C4Buf[c4Index]);
        	c2Index++; 
        	
        }
        else // check end
        {
        	if(c2Head==1)
        	{
            	if(item2=='@')
            	{
            		C2Buf[c2Index]=item2;
            		//printf("%c\n",C4Buf[c4Index]);
            		c2Index++;
            		if(c2Index!=BUFFER_SIZE)
            		{
            			printf("\nCOM2 End %c [%d] Error\r\n\n",item2,c2Index); 
            			exit(0);
            		}
            		else
            		{
            			printf("COM3 --> COM2 Test OK [%d]B \r\n\n",c2Index);
            			//printf("COM2 End %c [%d] \r\n\n",item2,c2Index); 
            		}
            		//printf("=====================================\n\n");
            		//RS_232=1;
            		RS_485=0;
            		c2Index=0;
            		c2Head=0;
            		ClearCom2();
            		ClearCom3();		            				            		
            		//ClearCom4();
            		c3Toc2=0;	            		
            	}
            	else
            	{
            		if(item2!='*')
            		{
            			printf("\nCOM2 Body Error %c\n",item2);
            			exit(0);
            		}
            		else
            		{
            			//printf("COM2 Body %c [%d]\n",item2,c2Index);
            		}
            		C2Buf[c2Index]=item2;
            		//printf("%c\n",C4Buf[c4Index]);
            		c2Index++;
            	}
            }
        } 
    }	    	
}	

int Test_WritingSpeed(int EnableWriteVerify)
{
    /*
    Test item: Writing speed (calls WriteFile)
    Description:  
        Create a file "Speed.txt". 
    */
    
    int iFileHandle,i;
    int iRet,iFaile=0;
    long lLastTimeTicks,lTimeDiff;
    
    Print (" before  mfs_EnableWriteVerify");

    if(EnableWriteVerify) mfs_EnableWriteVerify();
    else                  mfs_DisableWriteVerify();
    
    Print (" after  mfs_EnableWriteVerify");
    if((iFileHandle=mfs_OpenFile(_DISK_A, "Speed.txt", "w"))>0)
    {
        Print("OpenFile() : A:Speed.txt ok, File handle=%d.....\r\n", iFileHandle);

        //Prepare data: 0,1,2,...,8,9,0,1,....
        for(i=0;i<_Test_Length;i++)
            sFileData[i]='0'+i%10;
        
        lLastTimeTicks=GetTimeTicks();
        for(i=0;i<_Test_Loop;i++)
        {
            iRet=mfs_WriteFile(iFileHandle,sFileData,_Test_Length);
            if(iRet<=0)
            {
                //
                Print("Loop%d Write data failed! Error code=%d\r\n",i, iRet);
                Print(" _Test_Length= %d\r\n",_Test_Length);
                
                 //for(i=0;i<_Test_Length;i++)
            		//Print (" %c" ,sFileData[i]
                
                iFaile=1;
                return  iRet;
                //break;
            }
            Print(".");
        }
        lTimeDiff=GetTimeTicks()-lLastTimeTicks;
        
        iRet=mfs_CloseFile(iFileHandle);
        if(iRet==NoError)
        {
            Print("\n\rCloseFile(): A:Speed.txt ok.\n\r");
            if(iFaile==0)
            {
                Print("\n\rTest result=ok. WriteFile %ld Bytes takes %ldms(%5.1fKB/Sec)\n\r",
                      (long)_Test_Loop*(long)_Test_Length,
                      lTimeDiff,
                      (float)_Test_Loop*(float)_Test_Length/lTimeDiff); 
            }
            else Print("\n\rTest result=failed!\n\r");
        }
        else
        {
            Print("\n\rCloseFile(): A:Speed.txt failed! Error code=%d\r\n", iRet);
            Print("\n\rTest result=failed!\n\r");
            return  iRet;
        } 
    }
    else
    {
        Print("OpenFile(): A:Speed.txt failed! Error:%d\r\n", iFileHandle);
        Print("\n\rTest result=failed!\n\r");
    }
    return  0;
}


int Test_ReadingSpeed(void)
{
    /*
    Test item: Reading speed (calls ReadFile)
    Description:  
        Read data from A:Speed.txt and check its correction.
        "Speed.txt" should be created advanced by TestWritingSpeed().
    */
    int iFileHandle,i,j;
    int iRet,iFaile=0;
    long lLastTimeTicks,lTimeDiff;
    
    //Prepare standard data: 0,1,2,...,8,9,0,1,.... 
    for(i=0;i<_Test_Length;i++)
        sStandardData[i]='0'+i%10;
       
    if((iFileHandle=mfs_OpenFile(_DISK_A, "Speed.txt", "r"))>0)
    {
        Print("OpenFile() : A:Speed.txt ok, File handle=%d.....\r\n", iFileHandle);
        
        lLastTimeTicks=GetTimeTicks();
        for(i=0;i<_Test_Loop;i++)
        {
            memset(sFileData,0,_Test_Length);
            
            iRet=mfs_ReadFile(iFileHandle,sFileData,_Test_Length);
            if(iRet<=0)
            {
                Print("Loop%d Read data failed! Error code=%u\r\n",i, iRet);
                iFaile=1;
                return  iRet;
                //break;
            }
            else if(memcmp(sFileData,sStandardData,_Test_Length)!=NoError)
            {
                Print("Loop%d, Compare data failed! Error code=%u\r\n",i, iRet);
                Print("Standard :File\n\r");                
                for(j=0;j<_Test_Length;j++)
                {
                    if(sStandardData[j]!=sFileData[j])
                    Print("{Data[%d] %c:%c [%02d]:[%02d]} \n\r",j,sStandardData[j],sFileData[j],sStandardData[j],sFileData[j]);
                }
                Print("\n\r");
                iFaile=1;
                return  iRet;
                break;
            }
            else Print(".");
        }
        
        if(i==_Test_Loop)
        {
            lTimeDiff=GetTimeTicks()-lLastTimeTicks;
            iRet=mfs_CloseFile(iFileHandle);
            if(iRet==NoError)
            {
                Print("\n\rCloseFile(): A:Speed.txt ok.\n\r");
                if(iFaile==0)
                {
                    Print("\n\rTest result=ok. ReadFile %ld Bytes takes %ldms(%5.1fKB/Sec)\n\r",
                          (long)_Test_Loop*(long)_Test_Length,
                          lTimeDiff,
                          (float)_Test_Loop*(float)_Test_Length/lTimeDiff); 
                }
                else Print("\n\rTest result=failed!\n\r");
            }
            else
            {
                Print("\n\rCloseFile(): A:Speed.txt failed! Error code=%d\r\n", iRet);
                Print("\n\rTest result=failed!\n\r");
                return  -1;
            }
        }
        else
        {
            Print("\n\rTest result=failed!\n\r");
            return  -2;
        }
    }
    else
    {
        Print("OpenFile(): A:Speed.txt failed! Error:%d\r\n", iFileHandle);
        Print("\n\rTest result=failed!\n\r");
        return  -3;
    }
    return  0;
}

int Test_Dir(void)
{
    int i,iRet,iFileno,iDisk;
    char FileName[20];
    FILE_DATA fdata;
    
    for(iDisk=_DISK_A;iDisk<=_DISK_B;iDisk++)
    {
        if(iDisk==_DISK_A) Print("DiskA file list:\n\r");
        if(iDisk==_DISK_B) Print("DiskB file list:\n\r");
        
        if((iFileno=mfs_GetFileNo(iDisk))>=0)
        {
            for(i=0;i<iFileno;i++)
            {
                iRet=mfs_GetFileInfoByNo(iDisk,i,(FILE_DATA *) &fdata);
                if(iRet==NoError)
                {
                    memset(FileName, 0x0, 14);
                    memcpy(FileName,fdata.fname, 12);
                    
                    Print("%d)%12s    %4ld bytes\r\n",i,FileName, fdata.size);
                }
            }  
            
            Print("\r\nThere are %d File(s)\r\n", iFileno);
            
            Print("%12lu bytes used\r\n", mfs_GetUsedSize(iDisk));
            Print("%12lu bytes free\r\n", mfs_GetFreeSize(iDisk));
            Print("%12lu bytes bad\r\n", mfs_GetBadSzie(iDisk));              
             if (iFileno!=0)
             {
             	return iFileno;
             	Print(" iFileno= %d \r\n",iFileno);
              }
             	
            	
        }
        else 
        {
            Print("GetFileNo() failed! Error code= %d\r\n", iFileno);            
             	
            Print(" iFileno= %d \r\n",iFileno);
            return -5;
        }
        return 0;
    }
}

int test_MFS(void)
{
	int i, iRet;
	
	
            
		        	
	Print (" test 4 ");
	iRet=mfs_Init();	//	
	if (iRet!=64)
	{
		Print (" test 3 ");
		iRet=mfs_ResetFlash();
		//LCD_PutsAt(0,0,"MFS Init fail",0);
		Print (" test 2 ");
		//Print("MFS Init fail, iRet=%d\r\n", iRet);
		//return iRet;
		
	}
	else
	{
		Print (" tes11 ");
		
	}
		iRet=-1;
		iRet=Test_WritingSpeed(1);
		Print (" test ");
		Delay(100);
		if (iRet!=0)
		{
			LCD_PutsAt(0,0,"MFS Write fail",0);		
			Print("MFS write fail, iRet=%d\r\n", iRet);
			return iRet;
		}
		else
		{
			iRet=-1;
			iRet=Test_ReadingSpeed();
			Delay(100);
			if (iRet!=0)
			{
				LCD_PutsAt(0,0,"MFS Read fail",0);		
				Print("MFS read fail, iRet=%d\r\n", iRet);
				return iRet;
			}
			else
			{
				Print("After Test_ReadingSpeed OK, iRet=%d\r\n", iRet);
				mfs_DeleteAllFiles(_DISK_A);
            			mfs_DeleteAllFiles(_DISK_B);
            			Delay(100);
            			iRet=-1;
            			iRet=Test_Dir();
            			if (iRet!=0)
				{
					LCD_PutsAt(0,0,"MFS Del fail",0);		
					Print("MFS clear/Dir fail, iRet=%d\r\n", iRet);
					return iRet;
				}
				else
				{
					return 0;
				}
            			
				
			}
		}
		
	//}
	
}



void do_KeyPAD(void)
{
  int y=1,i,idx=0,sts;
  int j=0,z=0;
  int status[24]={0},temp;
  
  
  LCD_Clear();
  LCD_PutsAt(0,0,"Press KEY test",0);
	LCD_Hline(0,127,14,1);
	LCD_Hline(0,127,15,1);
	LCD_UpdateGraphic();
  while(1)
  {
    //for(i=0 ;i <24 ;i++)
    for(j=0 ;j <24 ;j++)
    {
      LCD_PutsAt(0,y,"                ",0);
      LCD_Gotoxy(0,y);
      i=inc_flag[j];
      //idx=i;
      LCD_Puts(keyname[i],0);
      //*i=inc_flag[j];
      //LCD_Puts(keyname[i],0);
      while(1)
      {
         z=inc_flag[idx];
        if((sts=ReadKeyStatus(z)) != status[z])
        {
     			status[z]=sts;
    			if(sts)
		    	{
		    	  //if(idx == inc_flag[j]) break;
               if(idx == inc_flag[i]) break;
            }
        }
        idx++;
        if(idx > 23) idx =0;
        temp = ReadKey();
      }
      LCD_Puts(" OK",0);
      y++;
      if(y > 3) y =1;
    }
    LCD_Clear();
    LCD_PutsAt(0,0,"KEY test OK",0);
    break;
    /*
    for(i=0 ;i <26 ;i++)
    {
      LCD_PutsAt(0,y,"                ",0);
      LCD_Gotoxy(0,y);
      LCD_Puts(keyCH[i],0);
      while(1)
      {
        if(IsKey())
        {
          temp = ReadKey();
          if(temp == 65+i)
          {
            LCD_Putch(65+i,0);
            break;
          }
        }
      }
      LCD_Puts(" OK",0);
      y++;
      if(y > 3) y =1;
    }
    break;
    */
  }
}

/*
{
	int status[24]={0},sts;
	while(1)
  	{
  		while(1)
      	{
	  		for(i=0 ;i <24 ;i++)
			{
				if((sts=ReadKeyStatus(idx)) != status[idx])
				
				
				
			}
		}
	}
	
}
*/


void doServer(void)
{
  


  int rc;                  /* return code of selectsocket */
  int i,ret,ver,SlotType;

//  unsigned long far *IntVectMain=(unsigned long far *)0x00000000L;

  struct timeval   seltime;
  seltime.tv_sec=0;
  seltime.tv_usec=0;  
   // printf( "11111\n\r" );
	for (i = 0; i < SOCKETS; i++)
	{
		if (sst[i].active)
		{  /* re-join active sockets */
			FD_SET( i, &rfds );
		}
	}
	rc = selectsocket( SOCKETS, &rfds, NULL, NULL, &seltime  );//check the socket come in
	if (rc < 0)
	{
	   printf( "selectsocket error %d\n\r", rc );
	   return;
	}
	//if( !rc )//no socket come in , continue waitting
	//   continue;
	//some sockets come in
	//printf( "222222\n\r" );
	for (i = 0; i < SOCKETS; i++)
	{  /* scan all possible sockets */
		if (FD_ISSET(i, &rfds))
		{
			if (i == s)
			{  /* master socket */
				memset( &ssin, 0, sizeof(ssin) );
				err = ss = accept( s, (struct sockaddr *)&ssin, &sin_len );
				if (err < 0)
				{
					printf( "accept error %d\n\r", err );
					return;
				}
				else
				{
					LCD_Clear();
					LCD_Gotoxy(0,0);
				//	printf( "accept ok %d\n\r", err );
				}
				//err=send( ss, Message1, strlen(Message1), 0 );//send connection message to client
				FD_SET( ss, &rfds );//set the setting
				sst[ss].active = 1;//active
				sst[ss].init   = 1;
				memcpy( &sst[ss].sin, &ssin, sin_len );
			}
			else
			{       /* slave socket */
				do_echo( i );//The client connection is accept and distribution to socket i
							//So the user can read the message(may be command string or other)
							//from the socket i.
							//remember each clinet connection If it is accept by this server
							//will cause one socket. So the maximun socket (connection) is 31.
							//In the other word, This server can be connected by 31 client maximun.
							//for the detail to read string,please refer to function "do_echo()".
			}
		}
	}
	//printf( "33333333\n\r" );
  /* service loop */
  //killsockets();//will end the program
 // Nterm();//close ethernet
}	

/*************************************************************************
 * killsockets
 * clear, shutdown, and close all sockets
 *************************************************************************/
void killsockets()
{
  int i;
  FD_ZERO( &rfds );  /* clear FD set */

  for (i = 0; i < SOCKETS; i++) {
	if (sst[i].active) {       /* if socket lives, kill it */
	  shutdown( i, 0 );
	  closesocket( i );
	}
  }
}
/*************************************************************************
 * do_echo
 *
 * when client is connected, do echo here  or process message
 * Add the user process program here.
 *************************************************************************/
static int lineIndex=0;
int do_echo( int skt )

{
  int i, cc, err=0;
  char buf[BUFSIZE],str[BUFSIZE];

  if (sst[skt].init)
  {
	sst[skt].init = 0;/* socket is just initiated */
	return err;
  }

   //err = cc = readsocket( skt, buf, strlen(buf)/*sizeof(buf)*/ );
  err = cc = recv( skt, buf, sizeof(buf),0 );// Read Socket data
  for(i=0;i<cc;i++)
  	str[i]=buf[i];
  //sprintf(str,"%s",buf);
  buf[cc] = '\0';
  
 if (err == 0)/* disconnected */
  {
	 shutdown( skt, 0 );//shutdown socket
	 closesocket( skt );//close socket
	 FD_CLR( skt, &rfds );//clear setting
	 sst[skt].active = 0;
	 return err;
  }

  if (err < 0)/* read error */
  {
	shutdown( skt, 0 );//shutdown socket
	closesocket( skt );//close socket
	FD_CLR( skt, &rfds );//clear setting
	sst[skt].active = 0;
	return err;
  }
//This send back is not necessary for every one
//_____________________________________________________
 err= send(skt,buf,cc,0);//echo string
 str[cc] = 0;
 if(lineIndex==0)
 {
	LCD_Clear();
	LCD_Gotoxy(0,0); 	
 } 	
 LCD_PutsAt(0,lineIndex,str,0);
 lineIndex++;
 if(lineIndex>=4)
 {

 	lineIndex=0;
 }
 if(strcmp(str,"EXIT")==0)
 {
	
	RestoreCom1();
	*LCD_BackLight=0;
	shutdown( skt, 0 );
	closesocket( skt );
	FD_CLR( skt, &rfds );
	sst[skt].active = 0;		
	exit(0);
 } 	
 //LCD_Puts(buf,0);
 if(err < 0)
 {               /* write error */
 	
	printf( "echo write error %d\n\r", err );
	shutdown( skt, 0 );
	closesocket( skt );
	FD_CLR( skt, &rfds );
	sst[skt].active = 0;
	return err;
 }
//_____________________________________________________
//force to terminal this program
 if (!strcmp("down", buf))
 {  /* shutdown echo server */
	es = 0;
	printf( "Server is Terminal\n\r");
	return err;
 }
// *************************************************************************/
 //err = User_Program(skt,buf,cc);
// *************************************************************************/
 return err;
}


void ClearEEP(int block)
{
	int aa,i;
	int err=0;
	unsigned char v0;
	
	unsigned char buf[256],str[256];
	for(i=0;i<256;i++)
		buf[i]=0xff;
	EE_WriteEnable();
	//for(aa=0;aa<256;aa++)
	//{
		EE_MultiWrite_A(block,0,256,buf);
	//}
	EE_WriteProtect();
	for(aa=0;aa<256;aa++)
	{
		EE_MultiRead(block,aa,1,&v0);
		if(v0!=0xff)
			err=1;
		//printf("[%d][%02X][%02X]\n",block,aa,v0);
	}
	if(err==1)
	{
		sprintf(str,"EEPROM Error %d",block);
		LCD_PutsAt(0,3,str,0);
		Delay(100);
		RestoreCom1();
		exit(0);
	}
	else
	{
		sprintf(str,"EEPROM %d/64 OK",block+1);
		LCD_PutsAt(0,3,str,0);		
	}
	
}
