@TCL_STARTUP@

# fac.remote.tcl
#
# This agent asks the user for an integer and then computes the factorial
# of that integer on a DIFFERENT machine.
 
proc factorial x {

    if {$x <= 1} {
        return 1;
    }

    expr $x * [factorial [expr $x - 1]]
}

  # ask the user for a machine

puts "Enter the name of the remote machine:"
gets stdin machine

  # get a controlling server

agent_begin

  # compute factorials

set number 0

while {$number != -1} {

  puts "Enter a nonnegative integer (-1 to quit): "
  gets stdin number
 
  if {$number != -1} {
 
      # compute the factorial on the remote machine.  We script the
      # script "factorial $number" along with procedure "factorial"
      # and variable "number" since the script needs these two things

    agent_submit $machine -vars number -procs factorial \
                          -script {factorial $number}

      # the result of the submitted agent is the result of the last
      # command executed in that agent -- i.e. the return value of
      # factorial procedure.  When the submitted agent ends, this
      # result is automatically sent to the root agent (which is this
      # agent).  We just wait until we receive the message.

    agent_receive code result -blocking

      # output the result
 
    puts "$number! is equal to $result\n"
  }
}

  # done

agent_end
