#define INCL_KBD
#define INCL_DOS
#include <os2.h>

#include <stdio.h>
#include <string.h>
#include <process.h>

#include "osdep/keycodes.h"

HPIPE   hpipe;

void pipeOpen( int pid )
{
    CHAR    szPipeName[ 100 ];
    ULONG   rc;

    sprintf( szPipeName, "\\PIPE\\MPLAYER\\%x", pid );

    DosCreateNPipe( szPipeName, &hpipe, NP_ACCESS_DUPLEX, 1, 1024, 1024, 0 );
}

void pipeClose( void )
{
    DosClose( hpipe );
}

void pipeWrite( const char *s )
{
    ULONG cbActual;

    DosConnectNPipe( hpipe );

    DosWrite( hpipe, s, strlen( s ), &cbActual );

    // Wait for ACK
    DosRead( hpipe, &cbActual, sizeof( ULONG ), &cbActual );

    DosDisConnectNPipe( hpipe );
}

int main( int argc, char *argv[])
{
    KBDKEYINFO  kki;
    int     pid;
    char    command[ 100 ];

    pid = spawnl( P_NOWAIT, "mplayer.exe", "mplayer.exe", "-slave", "-quiet", argv[ 1 ], NULL );

    pipeOpen( pid );

    do
    {
        if( KbdCharIn( &kki, IO_WAIT, 0 ))
            break;

        printf("Pressed char = '%c'\n", kki.chChar );

        switch( kki.chChar )
        {
            case 'l' :
            case 'r' :
            {
                sprintf( command, "key_down_event %d\n",
                         kki.chChar == 'l' ? KEY_LEFT : KEY_RIGHT );
                pipeWrite( command );
                break;
            }

            case 'q' :
                pipeWrite("quit\n");
                break;
        }
    } while( kki.chChar != 'e' );

    pipeClose();

    return 0;
}

