#include <mt_aes.h>
#include <osbind.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
 
#include "debug.h"

EXTERN BOOLEAN	debug;	/* global.c */
 
LOCAL FILE			*debug_handle = NULL;
LOCAL DEVICETYP	device;
LOCAL time_t		start_ticks;
				
VOID	DebugInit(DEVICETYP dev, UBYTE *file)
{
	UBYTE	devicename[20] = "";

	if (!debug)
		return;
		
	device = dev;
	switch (dev)
	{
		case Con :
			debug_handle = stdout;
			break;
		case TCON :
			if (appl_find("T-CON   ") > 0)
				debug_handle = stdout;
			break;
		case Datei:
			strcpy(devicename, file);
			break;
		case Terminal :
			strcpy(devicename, "u:\\dev\\modem1");
			break;
		case Modem1:
			strcpy(devicename, "u:\\dev\\modem1");
			break;
		case Modem2:
			strcpy(devicename, "u:\\dev\\modem2");
			break;
		case Seriell1:
			strcpy(devicename, "u:\\dev\\serial1");
			break;
		case Seriell2:
			strcpy(devicename, "u:\\dev\\serial2");
			break;
		case Prn:
			strcpy(devicename, "u:\\dev\\prn");
			break;
		default:
			device = null;
			break;
	}
	if (device != null && device != Con && device != TCON)
	{
		if (device == Datei)
			debug_handle = fopen(devicename, "a");
		else
			debug_handle = fopen(devicename, "w");
		if (debug_handle != NULL)
			setvbuf(debug_handle, NULL, _IONBF, 0);
	}
	if (device == Terminal)
		Debug("\33[2J\33[0;0H");			/* VT100-Terminal an Modem 1 */
}


VOID	DebugExit(VOID)
{
	if (!debug)
		return;

	if (debug_handle != NULL && debug_handle != stdout)
	{
		fclose(debug_handle);
		debug_handle = NULL;
	}
}


VOID	Debug(UBYTE *FormatString, ...)
{
	va_list	arg_ptr;

	if (!debug)
		return;

	if (debug_handle != NULL)
	{
		va_start(arg_ptr, FormatString);
		vfprintf(debug_handle, FormatString, arg_ptr);
		va_end(arg_ptr);
	}
}

VOID	StopIt(BOOLEAN start)
{
	if (debug)
	{
		if (start)
		{
			if (start_ticks != 0)	/* Messung l„uft schon */
				Debug("\aStopIt: l„uft schon!\n");
			else
				start_ticks = clock();
		}
		else
		{
			Debug(" %ld ticks.\n", clock() - start_ticks);
			start_ticks = 0;
		}
	}
}
