;;;; -*- Scheme -*-
;;
;;;; "potential" example for HLSIM
;;
;; David DeRoure June 12 1997, revised Sep 10 1997
;; dder@martigny.ai.mit.edu
;;
;; This Gunk file should be compiled with (cps "pot1") followed by
;; (cbf "pot1").  It uses definitions in clubs5d.scm.  See pot1s.scm
;; for simulation setup.  See the HLSIM documentation for further details.
;;
;; A "source" processor (processor 0) transmits a message containing
;; a potential of 36.  
;;
;; When any other processor receives a message, it compares the potential
;; in the message with the highest potential it has recorded.  If the
;; potential in the message is greater, the processor updates its highest
;; potential, changes its color to reflect the potential, and broadcasts
;; a message with a potential one less than that received.  If the potential
;; in the received message is less than or equal to the highest recorded
;; potential, no action is taken.  When a processor detects a collision, 
;; it flashes white for 100 time units.

(declare (usual-integrations))

(define potential 0)

;; This processor should originate messages if its processor number is 0.

(define (source?) (zero? (processor-number)))

;; The initial color of this processor depends whether it's a source.

(define my-color (if (source?) "cyan" "blue"))

;; The loop for propagators.
;;
;; The mapping from potential to color is achieved my mapping
;; each potential band of width 5 to an integer between 0 and 6,
;; and passing this to the color-me procedure.

(define primitive-message-event (make-event))

(define (propagator-loop)
  (select
    (global-timeout 'done)
    (primitive-message-event
     => (lambda (message)
          (event.clear! primitive-message-event)
          (if (eq? message 'collision)
              (begin (color-me "white") 
		     (wait (make-timeout-event 100)) 
		     (color-me my-color))
	      (if (and (number? message) (> message potential))
		  (begin
		    (set! potential message)
		    (broadcast (-1+ message))
		    (set! my-color (remainder (truncate (/ message 5)) 7))
		    (color-me my-color))))
          (propagator-loop)))))

;; Run the loop

(define global-timeout (make-timeout-event 10000))

(color-me my-color)

(if (source?)
    (broadcast 36)
    (propagator-loop))

;; end of pot1.scm
