#include <rtos.h>
#include <mem.h>

#define KBD_DELAY 80

int kgetch(void)
{
    int x;
    while ( 1 ) {
        dos_enter();
        x = kbhit();
        dos_exit();
        if ( x != 0 ) break;

        rt_sleep( KBD_DELAY );
    }
    dos_enter();
    x = getch();
    dos_exit();

    return( x );
}

int kgetche( void )
{
    int x;

    while ( 1 ) {
        dos_enter();
        x = kbhit();
        dos_exit();
        if ( x != 0 ) break;
        rt_sleep( KBD_DELAY );
    }

    dos_enter();
    x = getche();
    dos_exit();
    return( x );
}

char *kgets( char *str )
{
    int maxlen = *(BYTE *)str;
    int len;
    char ch;

    memset( str, 0, maxlen );

    for ( len = 0 ; len < maxlen ; ) {
        putch( 220 );
        ch = kgetch();
        putch( 8 );
        putch( ' ' );
        putch( 8 );
        switch ( ch ) {
            case 27 : *str = 0; return( str );
            case 13 : return( str );
            case  8 :
            case 127 : if ( len > 0 ) {
                         putch( 8 );
                         str[ --len ] = ' ';
                       }
                       break;
            default  : str[ len++ ] = ch;
                       putch( ch );
                       break;
        }
    }
    return( str );
}
