;;;; -*- Scheme -*-
;;
;; bnawki example for HLSIM
;;
;; David DeRoure Sep 14 1997
;; dder@martigny.ai.mit.edu
;;
;; This definition file is used by bnawki1.scm.  It should be compiled 
;; with (cf "td1d") and loaded with (load "td1d").  See td1s.scm 
;; for the simulation setup.  See the HLSIM documentation for further 
;; details.

(declare (usual-integrations))

;; The message constructor and accessors.  The data structure is
;; trivial (just a cons cell) but this abstraction is useful later.
;; Note that (define message-source car) in the Gunk program
;; would fail, because the Gunk compiler requires that car appear
;; in operator position.

(define make-message cons)
(define message-id car)
(define message-state cdr)

;; Table to maintain neighbors and states, consisting of
;; list of neighbor ids and list of corresponding states.

(define (make-table) (cons (list) (list)))

;; Update table according to information in message (id, state).
;; This is either a new neighbor and state, or a state update
;; for an existing neighbor.  If the table doesn't change then
;; return current state.  If it changes, check that current state 
;; is still okay, and if it isn't then find a new one.

(define (update-table table m id state)

  (define (check-state ids states)
    (cond ( (null? states) state )
	  ( (and (= (car states) state) 
		 (> (car ids) id)) (find-free-state 0) ) ; I lose
	  ( else (check-state (cdr ids) (cdr states)) )))

  (define (find-free-state i)
    (if (member i (cdr table))
	(find-free-state (1+ i))
	i))

  (let loop ((ids (car table)) (states (cdr table)))
    (cond ( (null? ids) (set-car! table (cons (message-id m) (car table)))
			(set-cdr! table (cons (message-state m) (cdr table)))
			(check-state (car table) (cdr table)) )
	  ( (and (= (car ids) (message-id m))
		 (= (car states) (message-state m))) state )
	  ( (= (car ids) (message-id m)) (set-car! states (message-state m))
					 (check-state (car table) (cdr table)))
	  ( else (loop (cdr ids) (cdr states)) ))))

;; end of td1d.scm
