/*
 *	File:					ASCII.h
 *	Description:	Read and write a Recall project in ASCII format.
 *
 *	(C) 1993-1994, Ketil Hunn
 *
 */

short num;

int GetText(BPTR fp, char s[])
{
	int c, i=0, lim=FNSIZE, inquote=0;
	BOOL done=FALSE;

	while((c=FGetC(fp))!=EOF && c!='\n' && --lim>0 && done==FALSE)
	{
		if(c==',' && inquote==0)
			done=TRUE;
		else
		{
			if(c=='"')
				inquote^=1;
			else if(inquote)
				s[i++]=c;
		}
	}

	s[i]='\0';
	return c;
}

LONG GetNumber(BPTR fp)
{
	int c, i=0, lim=FNSIZE;
	char s[10], *dummy;

	while((c=FGetC(fp))!=EOF && c!='\n' && c!='.' && c!=':' && --lim>0 && c!=',')
	{
		if(c!='"')
			s[i++]=c;
	}

	s[i]='\0';
	num=(short)strtol(s, &dummy,10);
	return c;
}

BOOL ReadASCII(struct List *list, char *destination)
{
	BPTR	fp;
	struct EventNode *globalnode;
	BOOL success;
	char text[FNSIZE];

	if(fp=Open(destination, MODE_OLDFILE))
	{
		while(GetText(fp, text)!=EOF)
		{
			globalnode=AddEvent(list, text);
			GetNumber(fp); globalnode->day	=num;
			GetNumber(fp); globalnode->month=num;
			GetNumber(fp); globalnode->year	=num;
			GetNumber(fp); globalnode->hour	=num;
			if(GetNumber(fp)!='\n')
			{
				globalnode->minutes=num;
				while(GetText(fp, text)!='\n')
					AddText(globalnode->textlist, text);
				AddText(globalnode->textlist, text);
			}
			success=TRUE;
		}
		Close(fp);
	}
	return success;
}

void WriteASCIITexts(BPTR fp, struct List *list)
{
	struct Node *node;

	for(every_node)
	{
		Write(fp, ",\"", 2);
		Write(fp, node->ln_Name, strlen(node->ln_Name));
		Write(fp, "\"", 1);
	}
	Write(fp, "\n", 1);
}

BOOL WriteASCII(struct List *list, char *destination)
{
	BPTR fp;
	struct Node *node;
	struct EventNode *globalnode;
	BOOL success;
	char string[256];

	if(fp=Open(destination, MODE_NEWFILE))
	{
		for(every_node)
		{
			globalnode=(struct EventNode *)node;
			sprintf(string, "\"%s\",\"%ld.%ld.%ld\",\"%ld:%ld\"",
											globalnode->eventname,
											globalnode->day,
											globalnode->month,
											globalnode->year,
											globalnode->hour,
											globalnode->minutes);
			Write(fp, string, strlen(string));
			WriteASCIITexts(fp, globalnode->textlist);
		}
		Close(fp);
		success=TRUE;
	}
	return success;
}
