;Name:	Derek Marston and Kristin Kelly
;Date:  10/29/02
;Description:  This program will send a busy
;	token when a free token is received

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

;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

;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
dspBuff:	DS	17t;	Define space for data
KBBuff:		DS	17t;	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:		ProcessFreeToken
;Input:		None
;Output:	None
;Destroys:	A, X, Y, Flags
;Desc:		Send a busy token if there is data to send
;		Otherwise send a free token

ProcessFreeToken:
	clr	RecFlag		;token received
	clra
	cmpa	Data2SendFlag	;do we have data2send?
	bne	prepBusy	;yes
	
	jsr	sendFree	;no-pass free on
	rts	
prepBusy:
	ldx	#KBBuff
	ldy	#RecBuff	;copy busy token
	iny			;into Tx/Rx buffer
	jsr	CopyBuff
	jsr	sendBusy
	clr	Data2SendFlag
	rts

;Name:		ProcessBusyToken
;Input:		None
;Output:	None
;Destroys:
;Desc:		

ProcessBusyToken:
	clr	RecFlag		;token received

	ldx	#RecBuff	;display token
	jsr	CopyBuff
	jsr	dspData

;Name:		sendBusy
;Input:		None
;Output:	None
;Destroys:	A, B, Y, Flags
;Desc:		Sends the contents of the keyboard buffer
;		with the appropriate token data
sendBusy:
	ldy	#RecBuff	;adds the source byte

	ldaa	#'3'		;to the Tx/Rx buffer
	staa	0,y

	ldaa	#0AAh		;send AA BB
	jsr	TransmitA
	ldaa	#0BBh
	jsr	TransmitA

	ldab	#17t;		;initialize counter

startBusy:
	
	ldaa 	0,y		;load a byte to send
	jsr	TransmitA	;send it
	iny	
	decb			;decrement counter
	bne	startBusy

	ldaa	#0AAh		;append final AA to token
	jsr	TransmitA	

	rts
