// Processes the files

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bpp.h"
#include "scanner.h"
#include "error.h"
#include "process.h"

///////////////////
// Process's a file
void ProcessFile(FILE *file)
{
	char Command[81];
	char FileName[128];
	YY_BUFFER_STATE OldFileBuffer;
	int NeedToken= TRUE;
	int c;

	while(curToken->type != TK_EOF)
	{
		if(NeedToken)
			GetToken();
		NeedToken = TRUE;
		
		if(curToken->type == TK_COMMENT && LookToken->type != TK_METACOMMAND)
		{
			// Get rid of tha comments
			while(curToken->type != TK_NEWLINE)
				GetToken();
		}
		if(curToken->type == TK_COMMENT && LookToken->type == TK_METACOMMAND)
		{
			GetToken();
			strcpy(Command,curToken->text);
			if(stricmp(Command,"$include") == 0)
			{
				Match(":");
				while(curToken->type == TK_SPACE || curToken->type == TK_TAB)
					GetToken();

				GetToken();
				GetToken();
				GetToken();		// single quote				

				// Get the filename
				strcpy(FileName,"");				
				while(curToken->type != TK_COMMENT)
				{
					strcat(FileName,curToken->text);
					GetToken();
				}
				
				// Save old file information
				OldFileBuffer = GetCurrentBuffer();

				fprintf(outfile,"\n'--- Included File '%s' ---\n",FileName);
				IncludeFile(FileName);
				fprintf(outfile,"\n'--------------------------\n");
				
				// Restore old file info
				yy_switch_to_buffer(OldFileBuffer);
				yyin = file;
				FileStart = TRUE;
				GetToken();
				NeedToken = FALSE;
			}
			
			continue;
		}
				
		fprintf(outfile,"%s",curToken->text);
		
	}
}

///////////////////
// Open a new file to process
void IncludeFile(char *name)
{	
	char buf[128];
	YY_BUFFER_STATE NewFileBuffer;
	
	yyin = fopen(name,"rt");
	if(yyin == NULL)
	{
		sprintf(buf,"Could not open file '%s'",name);
		SysError("IncludeFile",buf);
	}

	// Create a new flex file buffer
	fseek(yyin,0,SEEK_SET);
	NewFileBuffer = yy_create_buffer(yyin,YY_BUF_SIZE);
	yy_switch_to_buffer(NewFileBuffer);
	FileStart = TRUE;
			
	// Process the file
	ProcessFile(yyin);
	

	// Delete this buffer
	yy_delete_buffer(NewFileBuffer);

	if(yyin)
		fclose(yyin);
}