/*  lexnum.c   */
/*  Copyright 1989 Mountain Math Software  */
/*  All Rights Reserved                    */
#include <stream.h>
#include <strstream.h>
#include <stdio.h>
#include <string.h>
#include "debug.h"


#include "lexnum.h"

char * MakeLitString(const char * Text)
{
	if (!Text) DbgError("MakeLitString","NULL string pointer");
	int lng = strlen(Text) ;
	if (!lng) DbgError("Make:otString","NULL string");
	char * Result = new char[lng+1];
	strcpy(Result,Text);
	return Result ;
}

char * MakeString(const char * Text)
{
	int lng = strlen(Text) ;
	if (!lng) DbgError("MakeString","NULL string");
	if (*Text != '"' || Text[lng-1] != '"') DbgError("MakeString",
		"quote marks bad");
	char * Result = new char[lng-1];
	char * Temp = Result ;
	for (const char * Src = Text+1; *Src != '"'; *Temp++ = *Src++) ;
	*Temp++ = '\0' ;
	return Result ;
}

static int CStringLength(const char * Str)
{
	int Return = 0;
	if (*Str != '"') DbgError("MakeCString","missing initial `\"'");
	else Str++;
	for (const char * Ptr = Str ; *Ptr; Ptr++) {
		if (*Ptr == '\\') Ptr++ ;
		if (*Ptr) Return++ ;
		else {
			DbgError("CStringLength","bad string");
			return Return+1 ;
		}
	}
	if (Str[Return-1] == '"' ) return Return-1;
	DbgError("CStringLength","missing final `\"'");
	return Return ;
}
	


char * MakeCString(const char * String)
{
	int Length = CStringLength(String);
	if (*String == '"') String++ ;
	char * NewString = new char[Length+1];
	char * Pt = NewString ;
	while (*String) {
		if (*String == '\\') {
			String++;
			if (!*String) break ;
		}
		*Pt++ = *String++ ;
	}
	if (Pt > NewString) if (*(Pt-1) == '"') Pt--;
	*Pt = '\0' ;
 	if (Pt - NewString != Length) {
/*
 *		LogForm("Length = %d, Diff = %d", Length,
 *			(long) (Pt - NewString));
 */
 		DbgError("MakeCString - internal length error:",NewString);
	}
	return NewString ;
}


static void CheckLength(const char * String)
{
	if (strlen(String) > 1023) DbgError("LocGet(Int | Float)Value",
		"string too long");
}



static int32 LocGetIntValue(const char * format,const char * String)
{
	int32 ReturnValue ;
	CheckLength(String);
	char Temp[1024] ;
	strcpy (Temp,String);
	if (sscanf(Temp,format,&ReturnValue) != 1) {
		// cout << "Error string:" << String << ".\n" ;
		DbgError("GetIntValue","Cannot read number");
	}
	return ReturnValue ;
}
		
int32 OctConvert(const char * Text)
{
	return LocGetIntValue("%o",Text);
}

int32 IntConvert(const char * Text)
{
	return LocGetIntValue("%d",Text);
}

int32 HexConvert(const char * Text)
{
	return LocGetIntValue("%x",Text);
}

double FloatConvert(const char * Text)
{
	const BufSize = 1024 ;
	double ReturnValue = 0.0;
	CheckLength(Text);
	char Temp[BufSize] ;
	strcpy(Temp,Text);
	istrstream Read (Temp,BufSize-1);
	Read>>ReturnValue;
	return ReturnValue ;
}

