/* read_kbd.c (rsxnt) -- Copyright (c) 1996-1997 Rainer Schnitker */

#include "rsxnt.h"

static int __read_kbd_console(HANDLE hInput, int wait)
{
    static unsigned char next_key = 0;
    unsigned char ascii;
    INPUT_RECORD ir;
    DWORD n;

    if (next_key) {
        int retv = next_key;
        next_key = 0;
        return retv;
    }

    for (;;) {

        if (!wait) // test, if there is input event
            if (GetNumberOfConsoleInputEvents(hInput, &n) == FALSE || n == 0)
                return -1;

        if (ReadConsoleInput(hInput, &ir, 1, &n) == FALSE)
            return -1;

        if (ir.EventType != KEY_EVENT)  /* not a key */
            continue;

        if (ir.Event.KeyEvent.bKeyDown != 1) /* not key down */
            continue;

        if (ir.Event.KeyEvent.uChar.AsciiChar) {
            /***
            if (ir.Event.KeyEvent.dwControlKeyState & 1)
                ReadConsole(hInput, &ascii, 1, &n, NULL);
            else
            ***/
            ascii = ir.Event.KeyEvent.uChar.AsciiChar;
        }
        else { /* enhanced key */
            if (ir.Event.KeyEvent.wVirtualKeyCode == 16)
                continue;   /* enhanced key released */
            if (ir.Event.KeyEvent.dwControlKeyState & 0xf)
                continue;   /* control,shift,alt */
            ascii = 0;
            next_key = ir.Event.KeyEvent.wVirtualScanCode;
        }
        break;
    }

    return ascii;
}

int __read_kbd(int echo, int wait, int signal)
{
    DWORD mode;
    HANDLE hInput;
    int ascii;

    /* check Console Input Handle */
    hInput = GetStdHandle(STD_INPUT_HANDLE);
    if (hInput == INVALID_HANDLE_VALUE)
        return -1;
    else if (GetConsoleMode(hInput, &mode) == FALSE)
        return -1;

    /* disable control-c */
    SetConsoleMode(hInput, 0);

    ascii = __read_kbd_console(hInput, wait);

    SetConsoleMode(hInput, mode);

    if (echo)
        if (ascii >= 32)
            __write(1, &ascii, 1);

    if (signal && ascii == 3) {
        EMXPROCESS *proc = _rsxnt_get_process_ptr();
        _rsxnt_send_signal(proc, SIGINT);
#ifdef EMX_SYS_LIB
        _rsxnt_check_signals();
#endif
    }
    return ascii;
}
