;;;; -*- Scheme -*-
;;
;; max example for HLSIM
;;
;; David DeRoure Sep 17 1997
;; dder@martigny.ai.mit.edu
;;
;; This file should be compiled with (cps "max1") then 
;; (cbf "max1").  It uses definitions in club5d.scm.  
;; See max1s.scm for the simulation setup.  See the HLSIM 
;; documentation for further details.
;;
;; Each processor has two state variables: a color, and an id.
;; Initially, both are chosen at random.  Every processor repeatedly
;; broadcasts its color and id.  When a processor receives a message,
;; it checks whether the id in the message is higher than its own.
;; If so, it updates its color and id to those in the message; if not, 
;; it does nothing.

(declare (usual-integrations))

;; my initial id

(define id (random 1000000))

;; my initial color

(define color (random 7))

; the number of collisions detected

(define collisions 0)    

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

(define (event-loop)
  (select
    (global-timeout 'done)
    (transmit (broadcast (cons id color))
	      (set! transmit (make-timeout-event (random 5000)))
	      (event-loop))
    (primitive-message-event
     => (lambda (message)
          (event.clear! primitive-message-event)
	  (if (eq? message 'collision)
	      (set! collisions (1+ collisions))
	      (if (> (car message) set-by)
		  (begin (set! id (car message))
			 (set! color (cdr message))
			 (color-me color))))
	  (event-loop)))))
	      
;; Initial delay 

(define transmit (make-timeout-event (random 5000)))

;; Global timeout

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

;; Initial code

(color-me color)

(event-loop)

;; end of max1.scm

