#!/usr/bin/ruby
# $Id: PAR.rb,v 1.1 2006/08/24 03:45:43 nishi Exp $
#
# Parallel command handling module for Galatea
# by Takuya NISHIMOTO (nishi@hil.t.u-tokyo.ac.jp)
#
# set Init = 1 [Queue ID : only 1 is supporede now]
# set Cmd = sleep 3
# set Cmd = to @FSM set FaceExp = HAPPY 1 100 1000
#
# set SSMSpeak.stat = SPEAKING (from DM-MCL)
# or 
# set Run = NOW
#
# TODO:
#   multi-thread (non-blocking command handling)
#   multiple-queue (needed?)
#   better synchronization mechanism
#

$debug = false
$queue1 = Array.new

# -------------
def debug_puts(str)
  if $debug then 
    STDERR.puts str
  end
end

# -------------
def exec_queue()
  while $queue1.length > 0 do
    debug_puts("queue1.length=" + $queue1.length.to_s)
    
    cmd = $queue1.delete_at(0)
    debug_puts("cmd=" + cmd)
    
    cmd =~ /(.*)\s+(.*)$/
    if $1 == "sleep" then
      debug_puts("sleeping " +$2)
      sleep $2.to_f
    else
      debug_puts(cmd)
      puts cmd; STDOUT.flush
    end
  end
  debug_puts("queue1 done.")
end

# -------------
while gets do

  # set Init = 1
  if /^set\s+Init\s*=\s*1$/ =~ $_ then
    id = 1
    $queue1 = []
  end 
  
  # set Cmd = sleep 5
  # set Cmd = to @FSM set FaceExp = HAPPY 1 100 0
  if /^set\s+Cmd\s*=\s*(.*)$/ then
    cmd = $1
    $queue1.push(cmd)
  end

  # set SSMSpeak.stat = SPEAKING
  if /^set\s+SSMSpeak\.stat\s*=\s*SPEAKING$/ then
    exec_queue()
  end

  # set Run = NOW
  if /^set\s+Run\s*=\s*NOW$/ then
    exec_queue()
  end
end

# end of file
