#include <process.h>
#include <windows.h>

char* emulator_arm = "../EmulatorArm/debug/EmulatorArm.exe";

enum kSpawnType
{
    SPAWNTYPE_EXECV,
    SPAWNTYPE_CREATEPROCESS
};

int main(int argc, char *argv[])
{
    kSpawnType st = SPAWNTYPE_EXECV;
    if (argc > 1 && strstr(argv[1],"spawntype=") == argv[1]) {
        if (strstr(argv[1],"createprocess"))
            st = SPAWNTYPE_CREATEPROCESS;
    }

    if (st == SPAWNTYPE_CREATEPROCESS) {
        bool dont_allow_inherit = false;
        if (argc > 2 && !strcmp(argv[2],"-noinherit"))
            dont_allow_inherit = true;

        STARTUPINFOA         startup;
        memset(&startup, 0, sizeof(startup));
        startup.cb = sizeof(startup);
        startup.hStdInput  = GetStdHandle(STD_INPUT_HANDLE);
        startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
        startup.hStdError  = GetStdHandle(STD_ERROR_HANDLE);
        startup.dwFlags    = STARTF_USESTDHANDLES;

        if (dont_allow_inherit) {
            HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
            HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE);
            if (stdout_handle != INVALID_HANDLE_VALUE) {
                SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
            }
            if (stderr_handle != INVALID_HANDLE_VALUE) {
                SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
            }
        }
        PROCESS_INFORMATION pinfo;
        memset(&pinfo, 0, sizeof(pinfo));
        CreateProcessA(NULL,
                      emulator_arm,
                      NULL,
                      NULL,
                      TRUE,
                      DETACHED_PROCESS,
                      NULL,
                      NULL,
                      &startup,
                      &pinfo);
    }
    else {
        execv(emulator_arm, 0);
    }
    return 0;
}
