// Utilities.cpp

#include "pch.h"
#include "wavetsp.h"

#if defined(_DEBUG) && defined(DEBUGTSP)

static
void DumpParams(FUNC_INFO* pInfo, ParamDirection dir)
{
    TSPTRACE("  %s parameters:\n", (dir == dirIn ? "in" : "out"));

    FUNC_PARAM* begin = &pInfo->rgParams[0];
    FUNC_PARAM* end = &pInfo->rgParams[pInfo->dwNumParams];

    for( FUNC_PARAM* pParam = begin; pParam != end; ++pParam )
    {
        if( pParam->dir == dir )
        {
            switch( pParam->pt )
            {
            case ptString:
            {
                char    sz[MAX_PATH+1] = "<NULL>";
                if( pParam->dwVal )
                {
                    wcstombs(sz, (const wchar_t*)pParam->dwVal, MAX_PATH);
                    sz[MAX_PATH] = 0;
                }

                TSPTRACE("    %s= 0x%lx '%s'\n", pParam->pszVal, pParam->dwVal, sz);
            }
            break;

            case ptDword:
            default:
                if( dir == dirIn )
                {
                    TSPTRACE("    %s= 0x%lx\n", pParam->pszVal, pParam->dwVal);
                }
                else
                {
                    TSPTRACE("    %s= 0x%lx '0x%lx'\n", pParam->pszVal, pParam->dwVal, (pParam->dwVal ? *(DWORD*)pParam->dwVal : 0));
                }
            break;
            }
        }
    }
}

void Prolog(FUNC_INFO* pInfo)
{
    char    sz[MAX_PATH+1];
    GetModuleFileName(0, sz, MAX_PATH);

    TSPTRACE("%s() from %s\n", pInfo->pszFuncName, sz);
    DumpParams(pInfo, dirIn);
}

LONG Epilog(FUNC_INFO* pInfo, LONG tr)
{
    DumpParams(pInfo, dirOut);
    TSPTRACE("%s() returning 0x%x\n\n", pInfo->pszFuncName, tr);
    return tr;
}

void TspTrace(LPCSTR pszFormat, ...)
{
    char    buf[128];
    va_list ap;
    
    va_start(ap, pszFormat);
    wvsprintf(buf, pszFormat, ap);
    OutputDebugString(buf);

#define _DEBUGTOFILE
#ifdef _DEBUGTOFILE
    HANDLE  hFile = CreateFile("c:\\wavetsp.out", GENERIC_WRITE,
                               0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
    SetFilePointer(hFile, 0, 0, FILE_END);
    DWORD   err = GetLastError();
    DWORD   nBytes;
    WriteFile(hFile, buf, strlen(buf), &nBytes, 0);
    CloseHandle(hFile);
#endif

    va_end(ap);
}

#endif  // _DEBUG
