/*
 * modem - simple terminal server
 *       - allows one to TELNET in and connect to COM1
 */

#include <dos.h>
#include <stdio.h>
#include <rtos.h>
#include <sio.h>
#include <telnetd.h>
#include <process.h>

void modem_server( DWORD comport )
{
#define CBUFSIZ 128
    BYTE ch;
    BYTE buffer[ CBUFSIZ ];
    teld_str *t;
    int i;

    do {
        cputs("Listenning... ");
        t = teld_listen( 0 );
        cputs("connection arrived\r\n");
        sock_mode( t, TCP_MODE_NONAGLE );
        do {
            /* way to break out */
            if ( kbhit() ) exit( 0 );

            /* look for TELNET arriving chars */
            ch = teld_getc( t );
            if ( ch == 255 ) break;
            if ( ch != 0 )
                sio_writebyte( comport, ch );

            /* look for serial chars coming in, group them for speed */
            for ( i = 0 ; i < BUFSIZ ; ++i ) {
                if ( sio_recv_waiting( comport ) ) {
                    ch = sio_readbyte( comport );
                    buffer[ i ] = ch;
                } else break;
            }
            if ( i == CBUFSIZ ) i--;
            if ( i != 0 )
                teld_write( t, buffer, i );

            rt_yield();
        } while ( 1 );
        teld_close( t );
        cputs("Connection closed\r\n");
    } while ( 1 );
}

main()
{
    int comport = 1;        /* com port */
    WORD port = 0x3f8;      /* its i/o port base */
    int baud = 9600;

    int temp;
    DWORD dummy;

    rt_init( 100 );
    sock_init();
    kdebug = 0;

    sio_init( comport, port, 4, 4096, 4096 , NULL, 0 );
    sio_setup( comport, baud, 8, 0, 1 , 1);
    cputs("Press any key to exit\r\n");

    rt_newthread( &modem_server, comport, 4096, 0, "modem thread");

    while ( 1 ) {
        if ( kbhit() ) break;
        rt_sleep( 1000 );
    }

    sio_close( comport );
}


