// tTrace.cpp

#include <windows.h>
#define TAPI_CURRENT_VERSION 0x00010004
#include "ztapi.h"

HINSTANCE g_hinst = 0;
HINSTANCE g_hinstThat = 0;

BOOL WINAPI DllMain(HINSTANCE hinst, DWORD nReason, void*)
{
    switch( nReason )
    {
    case DLL_PROCESS_ATTACH:
        g_hinst = hinst;
        g_hinstThat = LoadLibrary("zTapi32.dll");
    break;

    case DLL_PROCESS_DETACH:
        FreeLibrary(g_hinstThat);
    break;
    }

    return TRUE;
}

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

    HANDLE  hFile = CreateFile("c:\\tapi32.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);

    va_end(ap);
}


template<typename RET, typename PFN>
struct FunctionPointer
{
    FunctionPointer(HINSTANCE hinst, const char* pszFunction)
    {
        m_psz = pszFunction;
        m_pfn = (PFN)GetProcAddress(hinst, pszFunction);
    }

    PFN operator()()
    {
        return m_pfn;
    }

    RET Trace(RET n)
    {
        char    szModule[MAX_PATH+1]; GetModuleFileName(0, szModule, MAX_PATH);
        ::Trace("%s()= 0x%x: Called from %s\n", m_psz, n, szModule);
        return n;
    }

private:
    const char* m_psz;
    PFN         m_pfn;
};

#pragma warning(disable:4786)
#include "tFunctions.cpp"
