//***********************************************************************************************************
//**
//**	hp21asm - File Line Stream Utility Module
//**
//**	Provides for a list of files to be processed as a stream of lines, and a stack to insert files into the stream.
//**
//**	2014 Nov: init / bh
//**
//***********************************************************************************************************
#include <stdio.h>
#include <string.h>
#include "util.h"


//* END Refs
//***********************************************************************************************************
//* Internals

static char			*Fls__list[100];			// the list of file names to read from
static int			Fls__cnt;				// number of files in the list
static int			Fls__idx;				// index through list

static FILE			*Fls__stk[10];				// stack of open files
static int			Fls__top;				// current file in the stack


//* END Internals
//***********************************************************************************************************
//* Interface

//----------------------------------------------------
// Initialise, list & stack are initially empty.

void
Fls_init()
 {
	Fls__cnt = 0;
	Fls__idx = 0;
	Fls__top = -1;
 }


//----------------------------------------------------
// Append the specified file to the list of files to be processed.

void
Fls_append( fname )
	char			*fname;
 {
	Fls__list[Fls__cnt++] = fname;
 }


//----------------------------------------------------
// Go back to the beginning of the existing list and start over.
// !!! Should check that stack is empty / all closed !!!

void
Fls_restart()
 {
	Fls__idx = 0;
 }


//----------------------------------------------------
// Open the specified file and push it on the stack.
// The file becomes the current source of lines.

void
Fls_push( fname )
	char			*fname;
 {
	FILE			*file;

	file = fopen( fname, "r" );
	if( !file )
	 {	printf( "File '%s' not found!\n\n", fname );
		return;
	 }

	Fls__stk[++Fls__top] = file;
 }


//----------------------------------------------------
// Get the next line from the sequence of files.

int
Fls_getLn( lnStr, max )
	char			lnStr[];
	int			max;
 {
	int			i;

	repeat
	 {	while( Fls__top < 0 )					// loop through list if stack is empty, until we have an open file
		 {	if( Fls__idx >= Fls__cnt )			// if list exhausted we're done
				return( FALSE );
			Fls_push( Fls__list[Fls__idx++] );		// try to open and stack the next file
		 }

		if( fgets(lnStr,max,Fls__stk[Fls__top]) )		// if we get a line, good, get out
			break;

		fclose( Fls__stk[Fls__top--] );				// EOF on current stack file, close it and pop stack
	 }

	i = strlen( lnStr );						// strip newline
	if( i-->0 && lnStr[i]=='\n' ) lnStr[i] = 0;

	return( TRUE );
 }


//* EOF
//***********************************************************************************************************
