/* This subroutine saves the current location in the current file and
 * begins reading from a new file.
 *
 * $Log: include.c,v $
 * Revision 1.2  1997/06/04 01:11:14  david
 * ANSI-fied the program.
 *
 */

#include <stdio.h>
#include <string.h>
#include "xasm.h"

static char *RcsId = "$Id: include.c,v 1.2 1997/06/04 01:11:14 david Exp $";

struct file
   {
   char *filename;    /* Name of saved file */
   unsigned long pos; /* Position in saved file */
   int line;          /* Line # in saved file */
   struct file *next; /* Pointer to next one in list */
   };

static struct file *fileroot = NULL;

void ainclude( char *label, char *opcode, char *operand, char *lptr )
{
struct file *temp;
int len, c;
	
labproc( label );

if ( (temp = (struct file *) malloc( sizeof(struct file) ) ) == NULL )
   {
   fprintf( stderr, "ainclude: Out of Memory\n" );
   exit( 1 );
   }
   
temp->next = NULL;
temp->filename = filename; /* Save old file name */
temp->pos = ftell( infd ); /* Save old position */
temp->line = line; /* Save old line # */

c = *operand++;
len = strlen( operand ) - 1;
if ( c != '"' && c != '\'' && operand[len] == c )
   {
   xerror( "ainclude: Invalid Operand." );
   free( temp );
   return;
   }

operand[len] = '\0'; /* Strip off last character ' or " */
filename = strdup( operand );
line = 0;

/* Everthing OK. Link old file onto stack */
temp->next = fileroot;
fileroot = temp;

/* Now close previous file and open new file */
if ( fclose( infd ) == -1 )
   {
   fprintf( stderr, "ainclude: Error on closing previous file.\n" );
   exit( 1 );
   }
   
#ifdef MSDOS
infd = fopen( filename, "rb" ); /* Open in BINARY mode for MSDOS */
#else
infd = fopen( filename, "r" );
#endif
if ( infd == NULL )
   {
   fprintf( stderr, "ainclude: Can't open INCLUDE file %s.\n", filename );
   exit( 1 );
   }

printl( (long) -1, NULL, -1, lptr );
}

/* Re-instate the previous file on the file stack */
int deinclude(void)
{
struct file *temp;
	
if ( (temp = fileroot) == NULL )
   return 0; /* Error - Nothing on file stack */
	

fileroot = fileroot->next; /* Pop entry off stack */
free( filename ); /* Free up unused memory */
filename = temp->filename; /* Get previous file name */
line = temp->line; /* Get previous line # */

if ( fclose( infd ) == -1 )
   {
   fprintf( stderr, "deinclude: Error on close of include file.\n" );
   exit( 1 );
   }
   
#ifdef MSDOS
infd = fopen( filename, "rb" ); /* Open in BINARY mode for MSDOS */
#else
infd = fopen( filename, "r" );
#endif
if ( infd == NULL )
   {
   fprintf(stderr, "deinclude: Error on re-open of file %s.\n", filename);
   exit( 1 );
   }
   
if ( fseek( infd, temp->pos, 0 ) == -1 )
   {
   fprintf( stderr, "deinclude: Error on fseek in file %s.\n", filename );
   exit( 1 );
   }
   
free( temp ); /* De-Allocate memory */
return 1; /* Everything AOK */
}
