// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "WS2InterceptDLL.h"
#include "Trace.h"
#include "dllmain.tmh"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
    BOOL    bRet;
    int     nRet;
    hModule; lpReserved;
    switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
        TraceEvents(
            TRACE_LEVEL_INFORMATION,
            TRACE_DLLMAIN,
            "%!FUNC! line:%!LINE! %!LEVEL! Enter (DLL_PROCESS_ATTACH)"
            );
        bRet = AfxWinInit(hModule, NULL, _T(""), 0);
        if (!bRet)
        {
            AfxWinTerm();
            return FALSE;
        }
        bRet = theApp.InitInstance();
        if (!bRet)
        {
            nRet = theApp.ExitInstance();
            AfxWinTerm();
            return FALSE;
        }
        AfxInitLocalData(hModule);
        TraceEvents(
            TRACE_LEVEL_INFORMATION,
            TRACE_DLLMAIN,
            "%!FUNC! line:%!LINE! %!LEVEL! Exit (DLL_PROCESS_ATTACH)"
            );
        break;
    case DLL_THREAD_ATTACH:
        //TraceEvents(
        //    TRACE_LEVEL_INFORMATION,
        //    TRACE_DLLMAIN,
        //    "%!FUNC! line:%!LINE! %!LEVEL! Exit (DLL_THREAD_ATTACH)"
        //    );
        break;
    case DLL_THREAD_DETACH:
        //TraceEvents(
        //    TRACE_LEVEL_INFORMATION,
        //    TRACE_DLLMAIN,
        //    "%!FUNC! line:%!LINE! %!LEVEL! Exit (DLL_THREAD_DETACH)"
        //    );
        break;
    case DLL_PROCESS_DETACH:
        TraceEvents(
            TRACE_LEVEL_INFORMATION,
            TRACE_DLLMAIN,
            "%!FUNC! line:%!LINE! %!LEVEL! Enter (DLL_PROCESS_DETACH)"
            );
        nRet = theApp.ExitInstance();
#ifdef _DEBUG
        // check for missing AfxLockTempMap calls
        if (AfxGetModuleThreadState()->m_nTempMapLock != 0)
        {
            TraceEvents(
                TRACE_LEVEL_WARNING,
                TRACE_DLLMAIN,
                "%!FUNC! line:%!LINE! %!LEVEL! Temp map lock count non-zero (%ld)",
                AfxGetModuleThreadState()->m_nTempMapLock
                );
        }
#endif
        AfxLockTempMaps();
        AfxUnlockTempMaps(-1);
        // terminate the library before destructors are called
        AfxWinTerm();
        TraceEvents(
            TRACE_LEVEL_INFORMATION,
            TRACE_DLLMAIN,
            "%!FUNC! line:%!LINE! %!LEVEL! Exit (DLL_PROCESS_DETACH)"
            );
        break;
	}
	return TRUE;
}

