////////////////////////////////////////////////////////////////////////////////
// Debug.cpp
//
//  Debugging and error handling code.

#include "stdhdr.h"

#include "Debug.h"

////////////////////////////////////////////////////////////////////////////////
// Error handling

static  TCHAR   szErrorBuf[512], szMessage[256];

// Display an error in a message box, and dump it to the debugger (if appropriate).
void DisplayError(LPCTSTR szFile, int nLine, LPCTSTR lpMessage)
{
    // Create the string.
    wsprintf(szErrorBuf, _T("%s (%d): %s"), 
        szFile, nLine, lpMessage);

#ifdef _DEBUG
    // Dump the error to the debugger, if present.
    OutputDebugString(szErrorBuf);
#endif

    // Display the error using MessageBox.
    MessageBox(NULL, szErrorBuf, _T("Error"), MB_OK);
}

// Display a customised error with a description of the error code.
void DisplayError(LPCTSTR szFile, int nLine, HRESULT hResult, LPCTSTR lpMessage)
{
    // Get an error description using FormatMessage.
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | 
            FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, hResult, 0, szMessage, 
        sizeof(szMessage) / sizeof(TCHAR), NULL);

    // Create the string.
    wsprintf(szErrorBuf, _T("%s (%d): %s\nError code 0x%08X: %s"), 
        szFile, nLine, lpMessage, hResult, szMessage);

#ifdef _DEBUG
    // Dump the error to the debugger, if present.
    OutputDebugString(szErrorBuf);
#endif

    // Display the error using MessageBox.
    MessageBox(NULL, szErrorBuf, _T("Error"), MB_OK);
}

void Trace(LPCTSTR lpFormat, ...)
{
    va_list ap;

    va_start(ap, lpFormat);
    wvsprintf(szErrorBuf, lpFormat, ap);
    va_end(ap);

    OutputDebugString(szErrorBuf);
}