/*
 * advanced TTY terminal example demonstrating SIO serial i/o library
 *
 * Gets settings from term.ini, or creates one if none exists
 *
 * We create a thread for the keyboard input/serial output, and a
 * second thread for serial input/console output.  Both threads
 * block while waiting for their input.
 *
 */

#include <dos.h>
#include <stdio.h>
#include <rtos.h>
#include <sio.h>
#include <kconio.h>
#include <inifile.h>

/*********************************************************************/
void kbd_thread( DWORD port )
{
    BYTE ch;

    do {
        ch = kgetch();      /* blocks thread until keystrokes available */
        /* exit on ~ character */
        if ( ch == '~' ) break;
        sio_writebyte( port, ch );

    } while ( 1 );

    kwritemessage( kmainthread, 0, 0 );
}

/*********************************************************************/
void serial_thread( DWORD port )
{
    BYTE ch;
    do {
        ch = sio_readbyte( port );     /* busy waits */
        putch( ch );
    } while ( 1 );
}
/*********************************************************************/
void extra_thread( DWORD port )
{
    do {
        rt_sleep(0);
    } while ( 1 );
}
/*********************************************************************/
main()
{
    int comport = 1;        /* com port */
    WORD port = 0x3f8;      /* its i/o port base */
    int baud = 9600;
    int irq = 4;

    int temp;
    DWORD dummy;


    rt_init( 100 );
    kpreemptive = 1;

    if (( comport = GetIniDWORD( "term.ini", "com", "port", 0 )) == 0 ){
        comport = 1;
        SetIniDWORD("term.ini","com","port", comport );
    }
    if ( comport == 2 ) {
        port = 0x2f8;
        irq = 3;
    }
    if (( baud = GetIniDWORD( "term.ini", "com", "baud", 0 )) == 0 ){
        baud = 9600;
        SetIniDWORD("term.ini","com","baud", baud );
    }


    sio_init( comport, port, irq, 4096, 4096, NULL, 0 );

    sio_setup( comport, baud, 8, 0, 1 , 1);
    cprintf("Press ~ to exit\r\n");

    rt_newthread( kbd_thread, comport, 4096, 0, "keyboard thread" );
    rt_newthread( serial_thread, comport, 4096, 0, "serial input thread");
    rt_newthread( extra_thread, comport, 4096, 0, "dummy thread");


    /* wait until we're done */
    kreadmessage( &temp, &dummy );

    sio_close( comport );
}

