;Name:	Derek Marston and Kristin Kelly
;Date:  10/29/02
;Description:  This program will process a
;	busy token

Monitor 	EQU	0FF7Ch
CmdReg		EQU	8800h
PortA		EQU	1000h
StatusReg	EQU	8800h
DataReg		EQU	8000h
SCIStatusReg	EQU	102Eh
SCIDataReg	EQU	102Fh
CharOut		EQU	0FFB8h
StrOut		EQU	0FFC7h
LineFeed	EQU	0FFC4h

US		EQU	'3'  ;Our node address
BROADCAST	EQU	'0'  ;Broadcast address
			     ;for change order #2

;Subroutines in EEPROM:
Config8251A             EQU	0B600h
InitializeVars	        EQU	0B603h
InstallInterruptVector  EQU    	0B606h
TransmitA	        EQU	0B609h
Receive		        EQU	0B60Ch
dspData		        EQU	0B60Fh
ProcessKey		EQU	0B612h
CopyBuff		EQU	0B615h
SendFree		EQU	0B618h
IntrRoutine		EQU	0B61Bh
CollectToken		EQU	0B61Eh
sendBusy		EQU	0B621h
ProcessFreeToken	EQU	0B624h

;put flags early in memory so they can
;be used with the direct address mode
	org	00h
RecFlag:	DS 	1t;	Define flag
dspFlag:	DS	1t;	Define flag
Data2SendFlag:	DS	1t;	Define flag
KBFlag:		DS	1t;	Define flag

	org	100h
	bra	main

RecBuff:	DS	19t; Define space for largest token+2
dspBuff:	DS	19t;	Define space for data
KBBuff:		DS	19t;	Define space for data
KBPtr:		DS	2t;


main:
	jsr	Config8251A;	Configure USART
	jsr	InstallInterruptVector;
	jsr	InitializeVars;
	
WaitLoop:
	;TOKEN
	brset	RecFlag,0Fh,ProcessToken;token to get
			;just checking last nybble
	;KEYBOARD
	jsr	ProcessKey
;	brset	Data2SendFlag,0FFh,dspKB

	;DISPLAY
	brclr	dspFlag,0FFh,Waitloop

	jsr	dspData
	bra	Waitloop

dspKB:
	ldx	#KBBuff
	ldy	#dspBuff
	jsr	CopyBuff
	
	bra	Waitloop

ProcessToken:
	ldaa	RecFlag
	cmpa	#0BFh		;see if token is busy
	beq	tokenisbusy
				;otherwise assume free
	jsr	ProcessFreeToken
	bra	WaitLoop
tokenisbusy:
	jsr	ProcessBusyToken
	bra	WaitLoop

;Name:		ProcessBusyToken
;Input:		None
;Output:	None
;Destroys:	A, X, Flags
;Desc:		Determines action when a busy token
;		arrives

ProcessBusyToken:
	clr	RecFlag		;token received
	ldx	#RecBuff
	ldaa	2,x		;load destination address

	cmpa	#BROADCAST	;see if message is broadcast
	beq	ToUs		;(change order)

	cmpa	#US		;see if message is TO us
	bne	NotToUs
ToUs:
	ldy	#dspBuff	;copy busy token to display
	jsr	CopyBuff
	jsr	dspData		;display the message
	
NotToUs:	;skip ToUs code (display message)

	ldx	#RecBuff
	ldaa	1,x		;load source address	
	cmpa	#US		;see if message is FROM us
	bne	NotFromUs

FromUs:
	
	;display here instead of after entering it

	ldx	#RecBuff	;display our own message
	ldy	#dspBuff
	jsr	CopyBuff
	jsr	dspData

	jsr	SendFree	
	rts

NotFromUs:

	jsr	SendBusy	;send entire token back out
	rts