/*  texspec.C   */
/*  Copyright 1991 Mountain Math Software  */
/*  All Rights Reserved                    */
#include <stream.h>
#include <string.h>
#include <ctype.h>
#include <ctype.h>
#include "texspec.h"
#include "texrep.h"
#include "mkstr.h"
#include "textrans.h"

static TeXWordTranslate  TeXTable[] = {
	{"\\times", "*", 1},
	{"\\leq", "<=", 1},
	{"\\geq", ">=", 1},
	{"\\Dpp", "ObjectProDSP",0},
	{"\\dpp", "DSP++",0},
	{"\\Cpp", "C++",0},
	{0}
};

DoTeXWordTranslate TheTeXWordTranslator(TeXTable);

DoTeXWordTranslate::DoTeXWordTranslate(TeXWordTranslate * translations):
	TheTranslations(translations),
	RecursiveCall(0)
{
}


char * DoTeXWordTranslate::Translate(const char * Input)
{
	RecursiveCall++ ;
	for (const char * Pt = Input; *Pt; Pt++) if(FindMacroWord(Pt))  {
		const char * Translation = CheckTranslate(Pt);
		if (Translation) {
			char * Return = Translate(DoTranslate(Input,
				Pt, Translation));
			RecursiveCall-- ;
			return Return ;
		}
	}
	RecursiveCall-- ;
	if (RecursiveCall) return (char *) Input ;
	return 0 ;
}

const char * DoTeXWordTranslate::IsTeXMacro(const char * Word)
{
	return CheckTranslate(Word,1) ;
}

int DoTeXWordTranslate::FindMacroWord(const char * Ptr)
{
	if (*Ptr != '\\') return 0;
	word[0] = '\\' ;
	char C ;
	for (Count = 1; Count < MaxWordSize && (C=Ptr[Count]); Count++)
		if (!isalnum(C)) break ; else word[Count] = C ;
	word[Count] = '\0' ;
	return Count > 1 ;
}

int DoTeXWordTranslate::IsMathTeXMacro(const char * Word)
{
	if (!FindMacroWord(Word)) return 0;
	for (const TeXWordTranslate * Check = TheTranslations; Check->TeXName;
		Check++) if (!strcmp(word,Check->TeXName))
		return Check->IsMath ;
	return 0 ;
}

const char * DoTeXWordTranslate::CheckTranslate(const char * Word, int Flag)
{
	if (!FindMacroWord(Word)) return 0;
	for (const TeXWordTranslate * Check = TheTranslations; Check->TeXName;
		Check++) if (!strcmp(word,Check->TeXName))
		if (Flag) return Check->TeXName ;
		else return Check->TranslateTo ;
	return 0 ;
}

const char * DoTeXWordTranslate::DoTranslate(const char * Input,
	const char * Start, const char * Translation)
{
	int NewLength = strlen(Input) + strlen(Translation) - Count + 1;
	char * Temp = new char[NewLength] ;
	int Index = 0 ;
	for (const char * Pt = Input ; Pt < Start ; Pt++) Temp[Index++] = *Pt ;
	strcpy(Temp + Index, Translation);
	strcat(Temp + Index, Start + Count);
	if (RecursiveCall > 1) delete (char *) Input ;
	return Temp ;
}

char * TeXString(const char * String)
{
	// cerr << "TeXString(" << String << ")\n" ;
	char * DeleteTemp = Concatenate(String);
	const char * Temp = TranslateToTeX.DoTeXTranslate(DeleteTemp);
	char * Return = TeX(Temp);
	delete DeleteTemp ;
	return Return ;
}
