#include <stdlib.h>
#include <stream.h>
#include <string.h>
#include "lexmac.h"
#include "linlist.h"
#include "totex.h"
#include "mkstr.h"

static void ** TheStack ;
static int StackPtr = 0 ;
static int MaxStackSize = 0 ;

void PushLexState(void * yybgin)
{
	Dbg cerr << "Pushing " << (int) yybgin << "\n" ;
	if (StackPtr < MaxStackSize) {
		TheStack[StackPtr++] = yybgin ;
		return ;
	}
	if (StackPtr++ != MaxStackSize++) {
		cerr << "PushLexState:Messed up stack.\n" ;
		exit(1) ;
	}
	TheStack = AddToList(yybgin,TheStack);
}

void * PopLexState()
{
	if (!StackPtr) {
		cerr << "PopLexState: nothing to pop.\n" ;
		exit(1);
	}
	void * Return = TheStack[--StackPtr] ;
	Dbg cerr << "Popping " << (int) Return << "\n" ;
	return Return ;
}

const char * make_verbatim_line(const char * Text)
{
	char * prefix = "\\\".LINE " ;
	const char * start = strlen(prefix) + Text ;
	for (const char * pt = start; *pt && *pt != '\n'; pt++);
	int NewLength = pt - start ;
	if (!NewLength) return Concatenate(" ");
	char * Result = new char[NewLength+2];
    strncpy(Result,start,NewLength);
	// Result[NewLength] = '\n' ;
	Result[NewLength] = '\0' ;
	return Result ;
}

const char * MakeLitNlString(const char * Text)
{
	Dbg cerr << "MakeLitNlString called\n" ;
	int Length = strlen(Text) ;
	for (const char * Skp = Text + strlen(Text) -1 ;
		Skp >= Text ; Skp--) if (*Skp != '\n') break ;
	int NewLength = Skp - Text + 1;
	if (!NewLength) return Concatenate(" ");
	char * Result = new char[NewLength+1];
	strncpy(Result,Text,NewLength);
	Result[NewLength] = '\0' ;
	return Result ;
}

