///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Winnov L.P., 1996.  All rights reserved
// debug.c: 
///////////////////////////////////////////////////////////////////////////////

#include <windows.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "debug.h"

#ifdef WNV_DBG
///////////////////////////////////////////////////////////////////////////////

BOOL bDisplayTrace = TRUE;
BOOL fFileExisted = FALSE;
DWORD dwCheckCount = 999;

void TraceWrite (PVOID pStr, int nLen)
{
	int nFile;
	HANDLE hFile;

	if (!bDisplayTrace) return;

	if (!fFileExisted)
	{
	    dwCheckCount++;
	    if (dwCheckCount > 100)
	    {	// check for file exists
			hFile = CreateFile(
				L"c:\\traceirq.txt",	// pointer to name of the file 
				GENERIC_WRITE,	// access (read-write) mode 
				0,			// share mode 
				NULL,		// pointer to security descriptor 
				OPEN_EXISTING,	// how to create 
				FILE_ATTRIBUTE_NORMAL, // file attributes 
				NULL);		// handle to file with attributes to copy  
			if (hFile)
			{
				fFileExisted = TRUE;
				CloseHandle (hFile);
			}
			else
			{
				dwCheckCount = 0;
				fFileExisted = FALSE;
			}
	    }
	}

	if (fFileExisted)
	{
		HANDLE hMutex = NULL;
		hMutex = CreateMutex (NULL, FALSE, L"TRACEIRQ");
		if (hMutex)
			WaitForSingleObject (hMutex, INFINITE);
	    nFile = _open ("c:\\traceirq.txt",_O_WRONLY | _O_APPEND);
	    _write (nFile, pStr, nLen);
	    _close (nFile);
		ReleaseMutex (hMutex);
		if (hMutex)
			CloseHandle (hMutex);
	}
}

void TraceString (PCHAR pStr)
{
    TraceWrite (pStr, strlen (pStr));
}

void TraceWString (PWCHAR pWStr)
{
    TraceWrite (pWStr, wcslen (pWStr));
}

char sz[32];
void TraceInt (int n)
{
    _itoa (n, sz, 10);
    TraceString (sz);
}

void TraceLong (DWORD dw)
{
    _itoa ((int)dw, sz, 16);
    TraceString (sz);
}

void TraceBegin (void)
{
}

#else	// ndef WNV_DBG
///////////////////////////////////////////////////////////////////////////////

// void TraceString (char *pStr) {}
// void TraceWString (PWCHAR pWStr) {}
void TraceInt (int n) {}
void TraceLong (DWORD dw) {}
void TraceBegin (void) {}
#endif	// ndef WNV_DBG
