/* Present a choice to the user, and return the user's choice
 *
 * Arguments
 *   arg(1)    - the dialog name. This will be the title line for VIO and the
 *               name of the tab on the Display Monitor.
 *   arg(2)    - a string containing the query to the user. This string has
 *               a maximum length of 900 characters.
 *   arg(3)    - the default value. If the user simply presses OK or Enter,
 *               this is the value returned.
 *   arg(4..8) - up to 5 choices. arg(3) must match one of these choices exactly.
 *
 * Copyright (C) 2001 Blonde Guy
 * All Rights Reserved
 */

pipeName = '\pipe\suntan'
dialogName = 'Choice Test'

if arg() = 0 then do
   response = choice(dialogName, "Select one of the following items.", "item 1", "item 1", "item 2", "item 3", "item 4", "item 5 is a really long, long item that is pretty long, too.")
   say response
   exit
end

pipestate = stream(pipeName, 'c', 'open')
if left(pipestate, 8) = 'NOTREADY' then do
   call SysSleep 1
   /* call beep 223, 100 uncomment to diagnose pipe failures */
end
call stream pipeName, 'c', 'close'
call SysSleep 1

pipestate = stream(pipeName, 'c', 'open')
if left(pipestate, 8) = 'NOTREADY' then do
   dialogName = arg(1)
   instructions = translate(arg(2), d2c(13), '~')
   response = ''
   do while response = ''
      say ""
      call sayWords instructions
      say ""
      say "Select one item from this list and press Enter."
      do i = 4 to arg()
         say i - 3 || ".  " arg(i)
      end
      say ""
      say "Enter item number, or just press Enter for" arg(3)
      parse pull iNum
      if iNum = '' then do
         response = arg(3)
      end
      else do
         if datatype(iNum) = 'NUM' then do i = 4 to arg()
            if iNum = i - 3 then do
               response = arg(i)
            end
         end
      end
      if response = '' then do
         say "you must enter a number from 1 to" arg() - 3
      end
   end
   response = 'dc=' || response
end
else do
   x = translate(arg(1), d2c(13), '~') || d2c(10) || arg(2) || d2c(13) || "Make your selection and press OK."
   do i = 3 to arg()
      x = x || d2c(10) || arg(i)
   end

   call lineout pipeName, "!choice" x
   
   call SysSleep 1
   
   response = ''
   do until response \= ''
      pipeState = stream(pipeName, 'c', 'open')
      if left(pipestate, 8) = 'NOTREADY' then do
         call stream pipeName, 'c', 'close'
         return arg(3)
      end
      call lineout pipeName, "!dialogwait"
      response = linein(pipeName)
      call SysSleep 1
   end
end

call stream pipeName, 'c', 'close'

return substr(response, 4)
