/*  cgidbg.c   */
/*  Copyright 1989 Mountain Math Software  */
/*  All Rights Reserved                    */
#include <time.h>
#include <sys/types.h>
#include <sys/types.h>
#include <unistd.h>

#include <stream.h>
#include <strstream.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include "mkstr.h"
/* #include <new.h> */
typedef void (*new_handler_t)();
extern new_handler_t __new_handler;
extern "C" void default_new_handler();
extern "C" new_handler_t set_new_handler(new_handler_t);


#include <stdlib.h>

#include "baseio.h"

#include "cgidbg.h"


#define DebugOut LogOut 


// obsolete should be deleted
void LogMsg(const char * p1, const char * p2,const char * p3,
const char *p4)
{
	long Time = time(0) &0xffff;
	char Buf[32];
	sprintf(Buf,"0x%0x",Time);
	DebugOut << "Log: 0x" << Buf << " " << p1 ;
	if (p2) DebugOut << p2 ;
	if (p3) DebugOut << p3 ;
	if (p4) DebugOut << p4 ;
	DebugOut <<"\n" ;
}


// obsolete should be deleted
// void LogForm(const char * format,int32 a, int32 b,int32 c, int32 d)
// {
//	LogOut.form(format,a,b,c,d);
// }

static int AttemptState = 1 ;

void ExitOneWayOrAnother()
{
	if (AttemptState==1) {
		AttemptState=0 ;
		ExitAndCleanUp();
		exit(1);
	}
	if (!AttemptState) {
		AttemptState = -1 ;
		ExitMinimalCleanUp() ;
		exit(1);
	}
	if (AttemptState == -1) {
		AttemptState = -2 ;
		exit(2);
	}
	if (AttemptState == -2) {
		AttemptState = -3 ;
		abort();
	}
#ifdef __NT_VC__
	exit(1);
#else
	kill(getpid(),SIGKILL);
#endif
}


void DbgError(const char * Routine,const char *ErrorType, const char* Class)
{
	DebugOut << "Error " << ErrorType << "  from `" ;
	if (Class)  DebugOut << Class <<  "::" ;
	DebugOut <<	Routine  << "'.\n" ;
	// LogOut << "Before flush\n" ;
	// kill(getpid(),SIGQUIT);
	ExitOneWayOrAnother() ;
}

void SystemErrorMessage(int LastLineFeed, char ** ret)
{
	const char * message_is = "The system error message is:\n" ;
	const char * err_number = "error number: " ;
	const char * not_in = " which is not in the system error table" ; 
	if (ret) {
		char * to_delete = 0 ;
		const char * sys_msg = 0 ;
		if (errno < sys_nerr) {
			const buf_size = 32 ;
			char buf[buf_size] ;
			ostrstream num(buf,buf_size);
			num << errno ;
			sys_msg = to_delete = Concatenate(err_number,buf,not_in);
		} sys_msg = sys_errlist[errno] ;
		*ret  = Concatenate(message_is,sys_msg,".");
		delete to_delete ;
		return ;	
	}
	OutputCurrentChannel << message_is ;
	if (errno < sys_nerr) OutputCurrentChannel << sys_errlist[errno] ;
	else OutputCurrentChannel << err_number << errno << not_in ;
	OutputCurrentChannel << "." ;
	if (LastLineFeed) OutputCurrentChannel << "\n" ;

}

static void OutOfMemory()
{
	cerr << "JOB TERMINATED: no more memory\n" ;
	// LogOut << "JOB TERMINATED: no more memory\n" ;
	_exit(1);
	// DbgError("No more memory","JOB TERMINATED");
}
	
void SetNewHandler()
{
	set_new_handler(OutOfMemory);
}

