#include <dos.h>
#include <stdio.h>
#include <stdlib.h>
#include <rtos.h>
#include <telnetd.h>
#include <string.h>
#include <parse.h>

void hightext( char *s )
{
    highvideo();
    cputs( s );
    lowvideo();
}

void telnet_thread( DWORD dummy )
{
    teld_str *t;
    BYTE ch;
    char buf[ 128 ];
    char buf2[ 256 ];
    char *substring;
    int i;

    do {

        hightext( "listenning for a connection\r\n");

        t = teld_listen( 0 );

        hightext("connection established\r\n");
        hightext("keys you type will be sent to client, Esc to exit\r\n");

        teld_puts( t, "Welcome\r\nPress keys to send to server\r\nESC moves to next section\r\n");

        do {
            ch = teld_getc( t );

            if ( ch == 255 ) break;
            if ( ch == 27 ) break;  /* ESC */
            if ( ch != 0 ) putch( ch );

            if ( kbhit() ) {
                ch = getch();

                /* break on ESC */
                if ( ch == 27 ) exit( 0 );

                teld_write( t, &ch, 1 );
            }
        } while ( 1 );

        teld_puts(t, "Enter any old password: ");
        if ( teld_getpassword( t, buf, sizeof( buf ), 0 )) {
            teld_puts( t, "You enterred: ");
            teld_puts( t, buf );
            teld_puts( t, "\r\n");
        }

        do {
            teld_puts(t,"Now enter a text string or 'quit': ");

            if ( teld_gets(t, buf, sizeof( buf ), 0 )) {
                teld_puts( t, "\r\n Got: ");
                teld_puts( t, buf );
                teld_puts( t, "\r\n");

                /* show how to parse the string */
                for ( i = 1 ; i < 20 ; ++i ) {
                    if ( ( substring = parse_arg( buf, i )) != NULL ) {
                        sprintf( buf2, " arg %u : %s\r\n", i, substring );
                        teld_puts( t, buf2 );
                        kfree( substring );
                    }
                }
            } else break;
        } while ( stricmp( buf, "quit"));

        teld_close( t );

        hightext("\r\nclosed connection\r\n");

    } while ( 1 );
}



main()
{
    kdebug = 1;
    rt_init(100);

    sock_init();            /* initialize network */

    cputs("starting...\r\n");

    rt_newthread( telnet_thread, 0, 4096, 0, "worker" );
    do {
        /* nothing */
        rt_yield();
    } while ( 1 );
}


