/* ParseFile.c - part of !GameID
 *  Musus Umbra 1997
 */

#include "gameid.h"
#include "core.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

#include "query.h"


static char buffer[320];	/* we have at least 2fns that need a buffer */


/* Parse a (desklib style) 'messages' file and create a gamelist from it */
gamelist readfile(char *filename)
{
	gamelist	gl = NULL;
	FILE		*istream;

	istream = fopen(filename,"r");
	if ( !istream )
	{
		sprintf(buffer,"Can't open file '%s'",filename);
		query_box2("Internal Error",buffer,NULL,"Continue");
		return NULL;
	}

	while ( fgets(buffer,320,istream) )
	{
		int l = strlen(buffer)-1;
		while ( isspace(buffer[l]) && l>=0 ) { l--; }
		buffer[l+1] = 0;
		if ( *buffer=='s' )		/* ie. probably 'serial.xx:' */
		{
			char *mtag, *sname,*lname,*slist;
			mtag = strtok(buffer,":");
			if ( strncmp(mtag,"serial.",6) )
				continue;	/* start next iteration of the enclosing while() */
			sname = strtok(NULL,":");	/* short name */
			slist = strtok(NULL,":");	/* ID list */
			lname = strtok(NULL,"");	/* long name */
			gl = add_game(gl,sname,lname,slist);
		}
	}
	fclose(istream);
	return gl;
}



/* Write a (desklib style) 'messages' file from the gamelist 'gl' */
void writefile( FILE *ostream, gamelist gl )
{
	int		g_num;
	time_t	now = time(NULL);

	for ( g_num = 0 ; gl ; gl=gl->next, g_num++ )
	{
		char *id_list = ids_to_text( gl->ids, buffer );
		fprintf( ostream, "serial.%d:%s:%s:%s\n", g_num,gl->s,id_list,gl->l );
	}
	fprintf( ostream,"\n# generated %s", ctime(&now) );
	fprintf( ostream,"# by %s (%s)\n\n", task_name, task_version );
}



/* Copy the comments at the head of 'old_file' to 'ostream' */
void copy_comments( FILE *ostream, char *old_file )
{
	FILE *istream = fopen( old_file, "r" );
	if ( !istream ) { return; }
	while ( fgets(buffer,320,istream) )
	{
		if ( *buffer != '#' ) { break; }
		fprintf(ostream,"%s",buffer);
	}
	fprintf(ostream,"\n");
	fclose(istream);
}
