;;;; -*- Scheme -*-
;;
;; neighbors example for HLSIM
;;
;; David DeRoure Sep 17 1997
;; dder@martigny.ai.mit.edu
;;
;; This file should be compiled with (cps "synchro1") then 
;; (cbf "synchro1").  It uses definitions in club5d.scm.  
;; See synchro1s.scm for the simulation setup.  See the HLSIM 
;; documentation for further details.
;;
;; This is a variation on max1.scm, with each processor "flashing";
;; the flashing of each processor is synchronized to the processor 
;; that colored it, using the received message to adjust the phase.

(declare (usual-integrations))

;; the id of my current master

(define id (random 1000000))

;; my color (and that of my master)

(define color (random 7))

;; Is light on?

(define light? #T)

; the number of collisions detected

(define collisions 0)   

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

(define (event-loop)
  (select
    (global-timeout 'done)
    (cycle (set! light? (not light?))
	   (if (and light? (zero? (random 10))) (broadcast (cons id color)))
	   (set! cycle (make-timeout-event width))	
	   (color-me (if light? color "black"))
	   (event-loop))
    (primitive-message-event
     => (lambda (message)
          (event.clear! primitive-message-event)
	  (if (eq? message 'collision)
	      (set! collisions (1+ collisions))
	      (if (> (car message) id)
		  (begin (set! id (car message))
			 (set! color (cdr message))
			 (set! cycle (make-timeout-event (- width 120)))
			 (set! light? #T))))
	  (event-loop)))))

;; The delay before the first broadcast

(define cycle (make-timeout-event (random 1000)))

;; The global timeout - this needs to be long  

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

;; The length of half a cycle

(define width 200)

;; Initial code

(color-me "white")

(event-loop)

;; end of synchro1.scm

