/*
 * TEST12 - show multithread console i/o fundamentals
 *
 *          The big newswire services transmit stories to many newspapers
 *          and radio stations, traditionally at relatively slow speeds.
 *
 *          But when there is nothing else to transmit, they
 *          simply display a sentance repeatedly, a sentance which practices
 *          every letter of the alphabet - thereby testing the equipment
 *          and communications lines.
 *
 *          The output is paced to appear roughly at 300 baud, or 30 chars
 *          per second.
 */

#include <stdio.h>
#include <rtos.h>
#include <process.h>
#include <conio.h>
#include <kconio.h>
#include <string.h>

bq_str *bq = NULL;          /* byte queue to hold input */

void write_string( bq_str *bq, char *s )
{
    while ( *s )
        bq_writebyte( bq, *s++);
}

void user_input_thread( DWORD dummy )
{
    char buffer[ 128 ];
    kwindow( 1, 1, 80, 15);

    cputs("Type quit to exit\r\n");

    do {
        buffer[ 0 ] = sizeof( buffer ) - 2;
        kgets( buffer );
        if ( !stricmp( buffer, "quit" ))
            exit( 0 );
        strcat( buffer, "\r\n");

        /* now queue that data */
        write_string( bq, buffer );
        cputs("\r\n");
    } while ( 1 );
}

void teletype_thread( DWORD dummy )
{
    BYTE ch;
    kwindow( 1, 15, 80, 25 );
    do {
        if ( bq_getbyte( bq, &ch ) == 0 ) {
            /* nothing there, send alphabet soup */
            write_string( bq, "The quick brown fox jumped over the lazy dog.\r\n");
        } else {
            putch( ch );
            rt_sleep( 1000 / 30 );
        }
    } while ( 1 );
}


main()
{
    rt_init(100);
    bq = bq_alloc( 100 );

    rt_newthread( user_input_thread, 2,4096, 0, "keyboard thread" );
    rt_newthread( teletype_thread, 2,4096, 0, "teletype thread" );

    while ( 1 )
        rt_yield();
}

