#include <stdio.h>
#include <rtos.h>
#include <mem.h>
#include <dos.h>
#include <ctype.h>

#include "morse.h"

bq_str *bq = NULL;  /* byte queue */

/*-----------------------------------------------------------------*/
void play_char( char ch )
{
    morse_type *m;
    BYTE *p;
    int i;

    ch = toupper( ch );
    m = ascii_to_morse( ch );
    if ( m != NULL ) {
        p = m->m_code;
        for ( i = 0 ; p[i] != 9 ; ++i ) {
            if ( p[i] == 1 ) sound( 400 );
            else nosound();
            rt_sleep( DELAY );
        }
        nosound();
    }
}

/*-----------------------------------------------------------------*/

void kbd_thread( DWORD dummy )
{
    BYTE ch;

    kwindow( 1,11, 80, 25 );

    cputs("Type text here and it gets translated into Morse code\r\n");
    cputs("Type as fast as you want.  We buffer between the two threads\r\n");
    cputs("Press Esc to exit\r\n");

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

            /* exit on ~ character */
            if ( ch == 27 ) break;
            putch( ch );
            bq_writebyte( bq, ch );
        }
        rt_yield();
    } while ( 1 );
    kwritemessage( kmainthread, 0, 0 );
}

/*-----------------------------------------------------------------*/

void sound_thread( DWORD dummy )
{
    char ch;
    kwindow( 1, 1, 80, 10 );
    do {
        bq_readbyte( bq , &ch );
        putch( ch );
        play_char( ch );
    } while ( 1 );
}

/*-----------------------------------------------------------------*/

main()
{
    int temp;
    DWORD dummy;

    rt_init( 100 );

    bq = bq_alloc( 4096 );
    rt_newthread( kbd_thread, 0, 2048, 0, "keyboard thread" );
    rt_newthread( sound_thread, 0, 2048, 0, "sound thread");

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



