#ifndef FM_DUMP_H
#define FM_DUMP_H

#include <windows.h>
#include <DbgHelp.h>
#include <schannel.h>

void CreateMiniDump(char *file, EXCEPTION_POINTERS* pep)
{
    // Open the file
    HANDLE hFile = CreateFileA(file, GENERIC_READ | GENERIC_WRITE,
        0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );

    if( ( hFile != NULL ) && ( hFile != INVALID_HANDLE_VALUE ) )
    {
        // Create the minidump
        BOOL rv = 0;
        MINIDUMP_EXCEPTION_INFORMATION mdei;
        MINIDUMP_TYPE mdt;
        mdei.ThreadId           = GetCurrentThreadId();
        mdei.ExceptionPointers  = pep;
        mdei.ClientPointers     = TRUE;

        mdt = MiniDumpWithFullMemory;

        rv = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),
            hFile, mdt, (pep != 0) ? &mdei : 0, 0, 0 );

        // Close the file
        CloseHandle( hFile );
    }
}

long __stdcall FMExcpHandler(PEXCEPTION_POINTERS excp)
{
    char mod[MAX_PATH] = { 0 };
    FILE* ferr = NULL;
    GetModuleFileNameA(NULL, mod, MAX_PATH);
    strcat(mod, ".err");
    ferr = fopen(mod, "w");

    fprintf(ferr, "Error address %x\n",excp->ExceptionRecord->ExceptionAddress);
    fprintf(ferr, "CPU register:\n");
    fprintf(ferr, "eax   %x   ebx   %x   ecx   %x   edx   %x\n",excp->ContextRecord->Eax,
        excp->ContextRecord->Ebx,excp->ContextRecord->Ecx,
        excp->ContextRecord->Edx);
    fclose(ferr);

    strcat(mod, ".dmp");

    CreateMiniDump(mod, excp);
    return   EXCEPTION_EXECUTE_HANDLER;
}

#endif // DUMP

