/*
    ####             #    #     # #
    #   #            #    #       #          The FreeWare C library for
    #   #  ##   ###  #  # #     # ###             RISC OS machines
    #   # #  # #     # #  #     # #  #   ___________________________________
    #   # ####  ###  ##   #     # #  #
    #   # #        # # #  #     # #  #    Please refer to the accompanying
    ####   ### ####  #  # ##### # ###    documentation for conditions of use
    ________________________________________________________________________

    File:    Debug.c.uniquefile
    Author:  Julian Smith
    Version: 0.00 (04 Jun 1995)
    Purpose: Provides a set of Debug_ function which send stuff to a unique
             file found using tmpnam().
*/


#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>

#include "Desk.Error2.h"
#include "Desk.Str.h"
#include "Desk.Debug.h"
#include "Desk.Sound.h"

#include "Defs.h"


static char		debug__filename[ 256] = "";
static FILE*		debug__file = NULL;
static Desk_bool	Desk_debug__initialised = Desk_bool_FALSE;



#define Desk_Debug__EnsureInitialised()	if ( !Desk_debug__initialised)	Desk_Debug_Initialise()



void	Desk_Debug_Initialise( void)
{
static Desk_bool	threaded = Desk_bool_FALSE;

if ( Desk_debug__initialised)	return;

if ( threaded)	{
	/* We have failed to initialise - eg Desk_Error2 trying to print diagnostics about not able to open Debug output file	*/
	Desk_Sound_SysBeep();
	fprintf( stderr, "Error occurred while initialising Desk Debug system\n");
	abort();
	}

threaded = Desk_bool_TRUE;

Desk_debug__initialised = Desk_bool_TRUE;
tmpnam( debug__filename);
debug__file = fopen( debug__filename, "w");

if ( !debug__file)
	Desk_Error2_HandleTextf( "Debug_Initialise can't open output file '%s'\n", debug__filename);

if (setvbuf( debug__file, NULL, _IONBF, 0))		/* Turn off buffering	*/
	Desk_Debug_Printf( Desk_error_PLACE "Couldn't turn buffering off for output debug file");

threaded = Desk_bool_FALSE;
}


void	Desk_Debug_Finalise( void)
	{
	Desk_Debug_Printf( Desk_error_PLACE "Desk_Debug_Finalise called\n");
	if ( debug__file)	fclose( debug__file);
	}


int	Desk_Debug_VPrintf( const char *format, va_list va)
	{
	Desk_Debug__EnsureInitialised();
	Desk_Debug__LineNestingPrefix( debug__file);
	return vfprintf( debug__file, format, va);
	}


int	Desk_Debug_Printf( const char *format, ...)
{
va_list	va;
int	i;

va_start( va, format);
i = Desk_Debug_VPrintf( format, va);
va_end( va);

return i;
}



void	Desk_Debug_Print( const char *text)
{
Desk_Debug__EnsureInitialised();
Desk_Debug__LineNestingPrefix( debug__file);
fputs( text, debug__file);
}


