/*
   Example: Playlist REXX program for OS/2.

   This script will be called from ICES when playlist type is "program"
   and playlist module is "playlist-program.cmd".
*/

/* Uncomment the following line if you want to set the time limit (in seconds)
   for any song. */
/* songTimeLimit = 180 */


/* Environment variable ICES_PLAYLIST - configured playlist file. */
ices.__platlist = value( "ICES_PLAYLIST", , "OS2ENVIRONMENT" )

/* Environment variable ICES_RANDOMIZE - configured "randomize" flag. */
ices.__ramdomize = value( "ICES_RANDOMIZE", , "OS2ENVIRONMENT" )

/* Query script file name for log */
parse source v1 v2 script
script = filespec( "name", script )
drop v1 v2

/* Load playlist */

idx = 0
do while lines( ices.__platlist ) \= 0
  line = strip( linein( ices.__platlist ), "B" )
  if line = "" | left( line, 1 ) = "#" then iterate
  
  idx = idx + 1
  list.idx = line
end
list.0 = idx
call stream ices.__platlist, "c", "close"

if list.0 = 0 then
do
  say "Log: [" || script || "] Playlist " || ices.__platlist " is empty."
  exit
end

say "Log: [" || script || "] " || list.0 || " playlist records."

/* Shuffle list */

if ices.__ramdomize \= 0 then
do
  say "Log: [" || script || "] Randomize playlist."

  do idx = 1 to list.0
    shuffle.idx = idx
  end

  do idx = 1 to list.0
    idxRand = random( 1, list.0 )
    if idxRand = idx then iterate

    swap = shuffle.idx
    shuffle.idx = shuffle.idxRand
    shuffle.idxRand = swap
  end
end

/* Processing ices requests. */

/* All previous lines "Log: ..." are read by ices only after the first
   request. */
idx = 1
do forever
  /* Read request (NEXT or SHUTDOWN) from STDIN: */
  cmd = linein()
  if cmd \= "NEXT" then
    /* Not NEXT... SHUTDOWN ?
       We must finish script immediately on SHUTDOWN. */
    leave

  /* Command NEXT received. Write reply to STDOUT: */

  /* Get index for playlist. */
  if ices.__ramdomize \= 0 then
    /* Use the shuffled indexes. */
    idxPlay = shuffle.idx
  else
    idxPlay = idx

  /* Reply field "File-name" - media file full name. */
  say "File-name: " || list.idxPlay

  /* Optional reply field "Line-no" - playlist line number. It's used for CUE. */
  say "Line-no: " || idxPlay

  /* Optional reply field "Time-limit" - go to next song after N seconds. */
  if symbol( "songTimeLimit" ) = "VAR" then
    say "Time-limit: " || songTimeLimit

  /* Empty line - end of reply */
  say

  /* Next index. */
  if idx = list.0 then
  do
    idx = 1
    /* ICES will receive this message after next request, as first line of
       reply. */
    say "Log: [" || script || "] Playlist completely passed."
  end
  else
    idx = idx + 1
end

exit
