*******************************************************************
*
*  BINLOAD.ASM
*    Binary loader for loading through the UIO serial port. Uses
*    The same data record sync and jump record sync bytes as
*    the 8800 format tapes.
*
*    Mike Douglas, Dec 3, 2023
*
*******************************************************************
OUTCH	equ	$FF81		;display char from B (in monitor)
SIOSR	equ	$F006		;UIO 6850 status register
SIODR	equ	$F007		;data register

DATAREC	equ	$3C		;flag that a data record follows
JUMPREC	equ	$78		;flag that a jump record follows

*----------------------------------------------------------------
*  The loader is located at $3F00 at the top of the 1st
*  16K RAM board. 
*----------------------------------------------------------------
	org	$3F00		;loader at top of 1st 16K

	ldaa	#3		;reset the UIO 6850
	staa	SIOSR
	ldaa	#$15		;8N1
	staa	SIOSR

main	bsr	uioRead		;look for a sync byte
	cmpb	#DATAREC	;data record?
	beq	loadRec		;yes
	
	cmpb	#JUMPREC	;jump record?
	bne	main		;no, keep looking

	bsr	getAddr		;get jump-to address in X
	ldx	saveX		;X=start adddress
	jmp	0,x		;jump to loaded code
	
* loadRec - Load a data record

loadRec	bsr	getAddr		;get pointer in X for data	
	bsr	uioRead		;get byte count to read
	stab	byteCnt
	clra			;init checksum
	
loadLp	bsr	uioRead		;load, save, and verify byte
	stab	0,x
	cmpb	0,x
	bne	memErr
	
	aba			;update checksum
	inx
	dec	byteCnt
	bne	loadLp
	
	bsr	uioRead		;read checksum
	sba
	bne	csumErr		;didn't match
	
	bra	main		;else, look for next record

* getAddr - Read two byte address from the cassette interface
*   and return it in X

getAddr	bsr	uioRead		;get MSB
	stab	saveX
	bsr	uioRead		;get LSB
	stab	saveX+1
	ldx	saveX		;X contains the address
	rts

* csumErr, memErr - Die in a loop displaying the error code

csumErr	ldab	#'C		;display C for checksum errors
	bra	dieLoop
	
memErr	ldab	#'M		display M for memory errors

dieLoop	jsr	OUTCH		;die here sending error code
	bra	dieLoop

* uioRead - Read a byte from the console serial port into B

uioRead	ldab	SIOSR		;wait for new byte
	rorb
	bcc	uioRead

	ldab	SIODR		;load and return byte
	rts

* Data area

saveX	rmb	2
byteCnt	rmb	1

	end
