;;;; -*- Scheme -*-
;;
;;;; Comm 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 "comm2") followed by
;; (cbf "comm2").  It uses definitions in clubs5d.scm.  See comm2s.scm
;; for simulation setup.  See the HLSIM documentation for further details.
;;
;; This is an extension of comm1.scm, showing speed of propagation.
;; NB Collisions appear white in this example.
;;
;; A "source" processor (processor 0) is assigned an initial "potential".
;; All the processors with non-zero potential repeatedly transmit their 
;; potential.  When a processor receives a message containing a higher
;; potential than its own, it adjusts its own potential towards the
;; received potential.   Hence the initial source "spreads out" over
;; a period of time.  The color of the processor indicates its potential 
;; (values of 7 or over appear white).

(declare (usual-integrations))

;; This processor is the initial source if its processor number is 0.

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

(define potential (if source? 6 0))

(define collisions 0)

(define primitive-message-event (make-event))
(define transmit-event (make-timeout-event (random 1000)))
(define global-timeout (make-timeout-event 100000))

(define (event-loop)
  (color-me potential)
  (select
    (global-timeout 'done)
    (transmit-event (if (> potential 0) 
			(begin (color-me "cyan")
			       (broadcast potential)))
		    (set! transmit-event (make-timeout-event (random 2000)))
		    (event-loop))
    (primitive-message-event
     => (lambda (message)
          (event.clear! primitive-message-event)
	  (if (eq? message 'collision)
              (begin (color-me "white")
		     (set! collisions (1+ collisions)))
	      (begin (color-me "green")
		     (if (> message potential) 
			 (set! potential (1+ potential)))))
	      (event-loop)))))

;; Run the loop

(event-loop)

;; end of comm2.scm
