; remote-fact.scm
; Demo file for Agent Scheme.
; To run a test, type (do-test <string> <integer>)

(define self "localhost")


; Pretty basic recursive factorial function.
(define (factorial x)
  (if (<= x 1)
    1
    (* x (factorial (- x 1)))))


(define (do-test target x)
  
   ; If we don't know who we are, ask.
  (if (equal? self "nowhere")
    (begin
     (display "Where am I?")
     (display #\newline)
    
    
     (let ( (answer (read)) )
       
       ; If they gave us a symbol, make it a string.
       (if (symbol? answer)
         (set! answer (symbol->string answer)))
       
       ; Now define ourselves to be that machine.
       (set! self answer)
       (display "I am now ")
       (display self)
       (display #\newline))))
  
  ; Become an agent.
  (agent-begin (self my-id)
               
               
               ; Compute the factorial on the remote machine.
               (agent-submit target factorial (list x))
               
               ; Display our result.
               (let* ( (message (agent-receive 60))
                      (id (car message))
                      (security (cadr message))
                      (code (caddr message))
                      (result (cadddr message)) )
    
                 (if (= code agent-error-message-code)
                   (begin
                    (display "A horrible error occurred on the remote machine.")
                    (display #\newline))
                   (begin
                    (display "Result is: ")
                    (display result)
                    (display #\newline))))))

  

