*-------------------------------------------------------------------
* BILOAD - Load binary tape of X1 records saved by BIPNCH into
*     RAM. If upon entry, X contains a valid port address, that
*     port is used for loading, otherwise port 1 ($8004) is used.
*
*     Note: SWTBUG "A" and "E" set $A046 to the port address used 
*     for the most recent "L" command. If this program is executed
*     with "G" after loading with "L", then X will be set to
*     the port address that loaded this program.
*
* Input and updated by Mike Douglas 2/16/20
*-------------------------------------------------------------------

* EQUATES

CONTRL	EQU	$E0E3		;RETURNS TO MONITOR
LOAD19	EQU	$E040		;DISPLAYS ? AND RETURNS TO MONITOR

* START OF PROGRAM

	ORG	$2000		;MUST BE ABOVE THE PROGRAM BEING LOADED

START	LDS	#$A042		;STACK MUST BE BELOW REGISTER SAVE AREA

	STX	PORTADR		;X=PORT ADDRESS THAT LOADED THIS
	LDAA	PORTADR		;SEE IF IT LOOKS REASONABLE
	CMPA	#$80
	BEQ	PORTRES		;IT DOES, CONTINUE

	LDX	#$8004		;ELSE, DEFAULT TO PORT 1
	STX	PORTADR

PORTRES	CPX	#$8004		;CONSOLE PORT?
	BEQ	SKPRES		;YES SKIP RESET

	LDAA	#3		;RESET THE 6850
	STAA	0,X

SKPRES	LDAA	#$15		;8N1
	STAA	0,X

* READ LOOP - LOOK FOR AN X1 OR X9 RECORD

XREC	BSR	INPUT		;WAIT FOR "X"
	CMPA	#'X
	BNE	XREC

	BSR	INPUT		;X1?
	CMPA	#'1
	BEQ	READ		;YES

	CMPA	#'9		;X9?
	BNE	XREC		;NO, KEEP WAITING FOR X1

	JMP	CONTRL		;EXIT TO MONITOR

* READ X1 RECORD AND STORE INTO MEMORY

READ	CLR	CKSM		;INIT CHECKSUM

	BSR	INPUT		;GET BYTE COUNT-1
	TAB	
	INCB			;B=ACTUAL BYTE COUNT	

	BSR	INPUT		;GET ADDRESS OF WHERE TO PUT DATA
	STAA	MEMPTR
	BSR	INPUT
	STAA	MEMPTR+1
	LDX	MEMPTR		;X->WHERE TO PUT DATA

STORE	BSR	INPUT		;GET DATA BYTE
	STAA	0,X		;STORE IT
	NOP	
	CMPA	0,X		;DID IT STORE PROPERLY?
	BNE	ERREXIT		;NO, EXIT WITH ERROR

	INX			;MOVE TO NEXT BYTE
	DECB	
	BNE	STORE

	BSR	INPUT		;GET CHECKSUM
	INC	CKSM
	BEQ	XREC		;VALID, GET NEXT RECORD

ERREXIT	JMP	LOAD19		;EXIT THROUGH MONITOR ERROR POINT

* INPUT - GET NEXT BYTE FROM SPECIFIED PORT

INPUT	STX	SAVEX		;SAVE X
	LDX	PORTADR		;X->CASSETTE SERIAL PORT

INWAIT	LDAA	0,X		;CHECK STATUS REGISTER
	LSRA			;CHECK RDRF (LSBIT)
	BCC	INWAIT

	LDAA	1,X		;A=CHARACTER RECEIVED

	PSHA			;UPDATE CHECKSUM
	ADDA	CKSM
	STAA	CKSM
	PULA			;RESTORE CHARACTER

	LDX	SAVEX		;RESTORE X
	RTS

* DATA AREA

PORTADR	RMB	2		;I/O PORT ADDRESS USED
MEMPTR	RMB	2		;MEMORY ADDRESS FROM X1 RECORD
CKSM	RMB	1		;CHECKSUM ON RECORD
SAVEX	RMB	2

* PUT START ADDRESS AT $A048

	ORG	$A048		;SET ADDRESS FOR "G"
	FDB	START

	END

