#include "plateau.h"
 
extern char MAILBOX[50];
extern char MYADDR[50];
 
void initialize();
void parse_header();
void recmoves();
struct gameinfo *read_gameinfo();
 
/*  void parsemail();
    int sort_message();
    void parse_message();
    6-25-92 JK 
*/
 
void initialize()
{   FILE *fptr;
    char buffer[80];
 
    intro();
    fgets(buffer,80,stdin);
}
 
void parse_header(tempgame,buffer)
struct gameinfo *tempgame;
char buffer[80];
{   char *cptr;
    
        if ((cptr=strstr(buffer,"PLATEAU!")) != NULL)
	{   if ((cptr = strtok(cptr+8,":")) == NULL)
	    {   printf("Unparsable message! #1\n");
	        return;
	    }
	    else
		strcpy(tempgame->name,cptr);
 
	    if ((cptr = strtok(NULL,":")) == NULL)
	    {	printf("Unparsable message! #2\n");
		return;
	    }
	    else
	    {	tempgame->moveno = atoi(cptr);
		if (!isdigit(*cptr))
		{   printf("Unparsable message! #3\n");
		    return;
		}
	    }
	
	    if ((cptr = strtok(NULL,":")) == NULL)
	    {   printf("Unparsable message! #4\n");
		return;
	    }
	    else
		tempgame->status = *cptr;
 
	    if ((cptr = strtok(NULL,"\n")) == NULL)
	    {   printf("Unparsable message! #5\n");
		return;
	    }
	    else
		tempgame->comments = *cptr;
	}
}
 
void recmoves()
{   FILE *fptr,*gptr;
    struct gameinfo game;
    char filename[20];
    char command[50];
    char buffer[80];
 
    if ((fptr = fopen("board.cfg","r")) == NULL)
    {	/*printf("I can't find your \'board.cfg\' file!\n");*/
	return;
    }
 
    while (read_gameinfo(&game,fptr) != NULL)
    {   if (game.status == 'o' || game.status == 'p')
	{   sprintf(filename,"%s.in",game.name);
	    if ((gptr = fopen(filename,"r")) != NULL)
	    {   while (fgets(buffer,80,gptr) != NULL &&
		    strstr(buffer,"PLATEAU!") == NULL);
 
	 	if (strstr(buffer,"PLATEAU!") != NULL)
		{   parse_header(&game,buffer);
		    fclose(gptr);
		   sprintf(command,"cat %s >> %s",filename,game.name);
		 /*   sprintf(command,"type %s >> %s",filename,game.name);*/
		    system(command);
		    sprintf(command,"rm %s",filename);
		 /*   sprintf(command,"del %s",filename);*/
		    system(command);
		    update_gameinfo(&game,0);
		    
		}
		else
		{   printf("File %s possibly corrupt, please check...\n",
				filename);
		    fclose(gptr);
		}
	    }
	}
    }
    fclose(fptr);
}
