/*																				*/
/*																				*/
/*				File:		  	txtget.c										*/
/*				Returns:	  	char											*/
/*				Parameters:													*/
/*																				*/
/*																				*/

#include <stdio.h>
#include <process.h>
#include <ctype.h>

#include "advm.h"
#include "huff.h"
#include "ptrt.h"
#include "values.h"
#include "words.h"

#include "hufget.h"


char txtget()

	{
	static int spaces = 0;
	static int eflag = FALSE;
	static int count;
	int tptr;
	static unsigned char hufc;
	static int irec = 0;
	static unsigned char buff [128];
	unsigned char a;
	static int spflag;
	static int eptr;

	trace3("Txtget: spaces = %d, eflag = %s, eptr = %d\n",
				spaces, eflag ? "True" : "False", eptr);
	if (spaces)
		{
		spaces--;
		return (' ');
		}
	if (eflag)
		{
		if (count <= 0)
			{
			eflag = FALSE;
			return (' ');
			}
		count--;
		if (!count && !spflag) eflag = FALSE;
		array (chars, eptr);
		return (chars[eptr++]);
		}
	tptr = 0;
	trace("TXTGET: tptr = top\n");
	for (;;)
		{
		if (hptr <= 0)
			{
			hptr = 1;
			hufc = hufget (&irec, &rpt, dbt, buff, &bpt, rec1, rec2, bp);
			}
		if (hufc & (1 << (hptr++ -1))) tptr++;
		trace2("TXTGET: bit test - hptr = %d, tptr = %d\n",hptr-1, tptr);
		if (hptr > 8) hptr=0;
		array (tree, tptr);
		if (!(tree[tptr] & 0x80))
			{
			tptr += tree[tptr];
			trace1("TXTGET: non-term - tptr = %d\n", tptr);
			if (tptr >= 750) 
				{
				printf("Error while expanding text in record %d.%03d after loc %d,\nTPTR out of range = %d",
							rec2,rec1,bp,tptr);
				exit(1);
				}
			}
		else
			{
			a = tree[tptr += tree[tptr] & 0x7f];
			trace3("TXTGET: term - char = %02.2X '%c', tptr = %d\n",a,a,tptr);
			array (tree, tptr);
			if (a > 0 && a < 32)
				{
				trace1("TXTGET: %d spaces\n",a);
				spaces = a-1;
				return (' ');
				}
			if (!(a & 0x80)) return (a);
			eflag = TRUE;
			spflag = ((a & 0x20) == 0x20);
			trace1("TXTGET: eflag set, spflag = %s\n",spflag ? "YES" : "NO");
			eptr = a & 0x1f;
			array (len, eptr);
			array (index, eptr);
			count = len[eptr];
			eptr = index[eptr]-1;
			array (chars, eptr);
			a = (a & 0x40) ? toupper(chars[eptr]) : chars[eptr];
			trace3("        count = %d, eptr = %d, char = %c\n",count,eptr,a);
			eptr++;
			count--;
			if (!count && !spflag)
				eflag = FALSE;
			return (a);
			}
		}
	}
