#/* #include <windows.h> */
#define SW_SHOWDEFAULT      10
#define WINAPI __attribute__((stdcall))
typedef unsigned int UINT;
typedef unsigned int HWND;
typedef int BOOL;
typedef char *LPSTR;
typedef void *HANDLE;
typedef void *HINSTANCE;
typedef void WINAPI (*FARPROC)(void);
int WINAPI SetWindowTextA(HWND, char *);
int WINAPI DestroyWindow(HWND);
HANDLE WINAPI GetModuleHandleA(char *);

#include <sys/emx.h>
#include <stdlib.h>
#include <fcntl.h>
#include <setjmp.h>
#include <sys/ioctl.h>
#include <rsxioapp.h>
#include "rsxio.h"

static jmp_buf  JmpBuf;
static HWND     hWnd;
static BOOL     window_closed = FALSE;

int __read(int handle, void *buf, size_t nbyte)
{
    extern int __read_old(int handle, void *buf, size_t nbyte);

    if ((_files[handle] & F_DEV) && ((_files[handle] & O_ACCMODE) == O_RDONLY))
        return RSXIO_Read(hWnd, buf, nbyte);
    else
        return __read_old(handle, buf, nbyte);
}

int __write(int handle, __const__ void *buf, size_t nbyte)
{
    extern int __write_old(int handle, __const__ void *buf, size_t nbyte);

    if ((_files[handle] & F_DEV) && ((_files[handle] & O_ACCMODE) == O_WRONLY))
        return RSXIO_Write(hWnd, (char *) buf, nbyte);
    else
        return __write_old(handle, buf, nbyte);
}

int __ioctl2(int handle, int request, int arg)
{
    extern int __ioctl2_old (int handle, int request, int arg);

    if (handle >= 0 && handle <= 2) {
        * (int *) arg = HT_DEV_CON;
        return 0;
    }
    else
        return __ioctl2_old (handle, request, arg);
}

int __read_kbd (int echo, int wait, int sig)
{
    return RSXIO_ReadKbd(hWnd, echo, wait, sig);
}

static void exit_func()
{
    if (window_closed == FALSE) {           // if exit called
        if (!rsxio_window_close) {
            SetWindowTextA(hWnd, "terminated!");
            RSXIO_WaitClose(hWnd);          // inactiv window
        }
        else
            DestroyWindow(hWnd);            // close window
    }
}

static void CloseFunc(void)
{
    window_closed = TRUE;
    longjmp(JmpBuf, 1);
}

int WINAPI WinMain(void) /* we need GUI */
{
    return 1;
}

int main(int argc, char **argv, char **env)
{
    hWnd = RSXIO_Register(GetModuleHandleA(NULL), rsxio_window_title, SW_SHOWDEFAULT, CloseFunc);

    if (hWnd == 0)
        exit(1);

    atexit(exit_func);
    if (setjmp(JmpBuf) != 0)
        return 0;

    return rsxio_main(argc, argv, env);
}
