		SUBTITLE    "< System Loader and associated routines >"
		NEWPAGE
		scope
						
; System command file loader.

		ORG	zspace.LOADER$

LOADER		LD	A,B		;Set overlay # (0 on non SYStem file).
		LD	(LDR14+1),A
		PUSH	DE		;Save IX & xfer FCB to IX
		EX	(SP),IX
		LD	DE,SBUFF$+255	;Init to end of buffer
		CALL	LDR01		;Do the load
		POP	IX		;Recover IX
		RET

;	Routine to ignore the LMF record.

LDR05		CALL	LDR15		;Get length of "comment"
		LD	B,A
LDR06		CALL	LDR15		;Read & ignore that many
		DJNZ	LDR06		;bytes then fall thru

;	Routine to parse LMF record types.

LDR01		CALL	LDR15		;Get record type
LDR02		CP	1		;Start of block?
		JR	Z,LDR08
		CP	2		;Start of TRAADR?
LDR03		JR	Z,LDR07
		CP	4		;End of LIB member?
		JR	Z,LDR12
		CP	8		;Begin ISAM table entry?
		JR	Z,LDR13
		CP	10		;End of ISAM map?
		JR	Z,LDR04
		CP	20h		;Ignore all other control
		JR	C,LDR05
LDR04		LD	A,22h		;Load file format err
		OR	A
		RET

;	Grab transfer address.

LDR07		CALL	LDR15		;Bypass 2nd X"02"
		CALL	GETADR		;P/u transfer address
		RET			;Ret Z or NZ

;	Grab load block.

LDR08		CALL	LDR15		;P/u block len
		LD	B,A
		CALL	GETADR		;P/u load address
		RET	NZ
		DEC	B		;Adj length for adr
		DEC	B
LDR09		CALL	LDR15		;P/u block byte
		LD	(HL),A
		INC	HL	
		DJNZ	LDR09		;Loop until block end
		JR	LDR01
LDR12		POP	HL
		RET

;	Routine to check ISAM table match.

LDR13		CALL	LDR15		;Get record length
		LD	B,A	
		CALL	LDR15		;Get ISAM number
		DEC	B		;& decrement counter
LDR14		CP	0		;Either ISAM# or 0
		JR	NZ,LDR06	;Go if not a match
		CALL	GETADR		;else get the TRAADR
		PUSH	HL		;& save it
		CALL	Z,GETADR	;Get the NRN for member
		JR	NZ,LODERR
		CALL	LDR15		;Get the sector offset
		LD	E,A		;Update pointer offset
		PUSH	BC
		LD	B,H		;Xfer NRN position needed
		LD	C,L
		PUSH	DE		;Save buffer ptr offset
		PUSH	IX
		POP	DE		;P/u FCB into DE
		CALL	zPOSN		;Position to ISAM rec
		POP	DE		;Rcvr buffer ptr offset
		POP	BC
		JR	NZ,LODERR
		CALL	LDR17		;Read the sector
		JR	LDR02		;Now go read the member

;	Routine to get the next file byte.

LDR15		INC	E		;Bump buf pointer
		JR	Z,LDR17		;Read sector if needed
LDR16		LD	A,(DE)		;P/U byte from buffer
		RET
LDR17		PUSH	HL		;Save regs
		PUSH	DE
		PUSH	BC
		CALL	NXTSECT		;Read next record
		POP	BC		;Restore regs
		POP	DE
		POP	HL
		JR	Z,LDR16		;Bypass if no error
LODERR		POP	BC		;Pop return address
		RET

;	Routine to get an address field.

GETADR		CALL	LDR15		;Get low order byte
		LD	L,A
		CALL	LDR15		;Get hi order byte
		LD	H,A
		CP	A
		RET

;	End loader module