/*                      QBCC Project

This source file is licensed under the GNU Lesser Public Licence which should be 
included with the distribution of this source.

*/
// File Input Function

#include "../include/stdlibh.h"
#include "../include/stringh.h"
#include "../include/file.h"


/* Standard FILE INPUT function */
void FINPUT(char *fmt,...)
{
	int UseNewline = FALSE;
	int UsePrompt = FALSE;
	va_list p;
	string *Str;
	int *Integer;
	float *Single;
	char InputStr[1024];
	char *format;
	char *token;
	int FirstEntry = TRUE;
	int FileNumber = -1;	
	
	va_start(p, fmt);

	format = fmt;

	// Need to get the filenumber first
	do {
		// File Number
		if(*fmt == 'i' && FirstEntry)
		{
			FirstEntry = FALSE;
			Integer = (int *)va_arg(p,int *);
			FileNumber = *Integer;
		}
	} while (*(++fmt) != '\0');

	
	if(FileNumber < 0 || FileNumber >= MAX_FILES)
		return;
	if(!Files[FileNumber].ptr)
		return;
	if(!Files[FileNumber].used)
		return;

	fscanf(Files[FileNumber].ptr,"%[^\n]\n",InputStr);	
	token = strtok(InputStr,",");
	FirstEntry = TRUE;

	while(token != NULL)
	{
		if(*format == 'i')
		{
			if(FirstEntry)			
			{
				FirstEntry = FALSE;			// Ignore the filenumber
				format++;
			}
			else
			{
				Integer = (int *)va_arg(p,int *);
				*Integer = atoi(token);
			}
		}
		if(*format == 's')
		{
			Str = (string *)va_arg(p,string *);
			Str->ptr = realloc(Str->ptr, strlen(token) + 1);
			strcpy(Str->ptr, token);
			Str->length = strlen(token);
		}		
		if(*format == 'f')
		{
			Single = (float *)va_arg(p,double *);
			*Single = (float)atof(token);
		}

		token = strtok(NULL,",");		
		if(*format == '\0')
			break;
		format++;
	}
}