/* REXX inside */
/*    based on PMDownloader's script */

call rxFuncAdd "SysLoadFuncs" , "RexxUtil" , "SysLoadFuncs"
call SysLoadFuncs

/* pipe name */
pname = "\PIPE\COOLFMCONTROL"



Parse arg ccommand

/* If no ccommand is given, exit with errorlevel 1 */
if ccommand="" then do
    say "coolfm/pipe pusher, version 2.0 beta 11  (November 16, 2003)"
    say "Product of eCo Software (http://ecomstation.ru/ecosoft, coolfm@ecomstation.ru)"
    say ""
    say "Usage:" 
    say "coolfm-pipe.cmd command"
    say ""
    say "Commands:"
    say "100.5             -- set frequency 100.5 MHz"
    say "Maximum           -- set Maximum station (i.e. .frq file with 'name=Maximum')"
    say "HamburgFM.frq     -- set station defined in hamburgfm.frq file"
    say "$Mute/$Unmute     -- mute/unmute fm-tuner"
    say "$switchmute       -- turn over mute"
    say "$Prev/$Next       -- switch to previous/next station"
    say "$switchrecord     -- turn over record"
    say "$1                -- switch to the first station, $2 - second, .. $9"
    say "$Beep             -- beep"
    say "$Quit             -- close coolfm"
    say ""
    say "Examples:"
    say "1) Switch to 'Love radio' station:"
    say '    coolfm-pipe.cmd Love radio'
    say "2) Set new frequency: 100.9 MHz"
    say "    coolfm-pipe.cmd 100.9"
    
    exit 1
end

os2rc=0

/* Loop */
do forever
    /* Try open control pipe for writing */
    opret = stream(pname,"C","open write")
    if opret == "READY:" then do
        /* Pipe opened, write ccommand to pipe */
        call lineout pname,ccommand
        /* Close pipe */
        call lineout pname
        /* All done, exit with errorlevel 0 */
        say "pouring command ["||ccommand||"]"
        exit 0
    end
    
    /* Pipe not opened, opret contains something like "NOTREADY:errorcode"
       Parse opret to get errorcode */
    parse value opret with pstate ":" os2rc
    
    /* OS/2 errorcode 231 indicates pipe busy, and we call SysWaitNamedPipe
       to wait when pipe become available */
    if os2rc=231 then do
        os2rc = SysWaitNamedPipe( pname , -1 )

        /* Non-zero return value indicates error, pipe not available */
        if os2rc\=0 then leave
    end
    else leave  /* Another error, pipe not available */

    /* retry loop after calling SysWaitNamedPipe */
end

/* Loop is ended, which indicates error */
/* Print error message and errorcode and exit with errorlevel 1 */
/* To get more info on specific errorcode, type in command window
   "help <errorcode>", where <errorcode> is OS/2 error number */
say "Can't open pipe '"||pname||"', rc: "||os2rc||"."
exit 1

