			SUBTITLE	"< Bank handling >"
			newpage
			SCOPE
			
;	Bank selection SVC handler
;	HL=> transfer address for function B=0
;	C => Bank request <0-2>; Set bit 7 to transfer.
;
;	B => Request function
;	0 => Select bank C
;	1 => Reset in-use bit of bank C
;	2 => Test in-use bit of bank C
;	3 => Set in-use bit of bank C


zBANK		AND	7Fh			;Strip possible bit 7
		CP	2+1			;Bank out of range?
		JP	NC,PERR
			
		DEC	B
		JP	M,SELECTBANK		;Go if function 0, bank select C
			
		LD	C,86h			;Set for reset BUR$
		JR	Z,rst_bur		;Go if function 1, reset in use bit of bank C..
			
		LD	C,46h			;Set for test BUR$
		DEC	B
		JR	Z,tst_but		;Go if function 2, test in-use bit of bank C.
			
		DEC	B	
		JR	Z,set_bur		;Go if function 3, set in-use BUR$ bit of bank C.
		DEC	B
PERRX		JP	NZ,PERR			;SVC parameter error
		LD	A,(LBANK$)		;P/u current bank
		CP	A
		RET
set_bur		LD	B,A			;Save the bank requested
		CALL	tst_but			;Test if in use already
		RET	NZ			;Back if error
		LD	A,B			;Reget the request #
		LD	C,0C6h			;Set for set BUR$
tst_but		AND	7			;Strip to bank 0-7
		RLCA				;Shift <0-2> to <3-5>
		RLCA	
		RLCA
		OR	C			;Merge the code type
		LD	(rst_bur+1),A		;Change the OP code
		XOR	A			;Init Z-flag
		LD	A,8			;Init "Device not avail
		PUSH	HL			;Don"t alter HL
		LD	HL,BUR$			;Point to bank-used-RAM
rst_bur		BIT	0,(HL)			;*** Modified instruction
		POP	HL
		RET

SELECTBANK	PUSH	HL			;Ck if stack is in upper
		LD	HL,8005h		;bank area
		ADD	HL,SP
		POP	HL
			
		JP	C,PERR			;Error if > X"7FFE"
			
		CP	1			;Change <0, 1, 2, 3>
		RLA				;to <1, 2, 4, 6>
		LD	B,A			;& save for later
		LD	A,(BAR$)		;P/u Bank Avail Ram
		AND	B			;Is the bank installed?
		JR	NZ,PERRX		;Error if not in machine
		LD	A,B			;Get the requested bank
		RRA				;Change <1, 2, 4> to
		CCF				;<0, 2, 3> {CF on 0
		ADC	A,0			;switched to 2 & 4}
		RLCA				;Shift bits 0-1
		RLCA				;to 4-5 (MBIT0,1)
		RLCA
		RLCA
		LD	B,A			;Save bit mask
		LD	A,(OPREG$)		;P/u current memory
		AND	08Fh			;configuration &
		OR	B			;mask off old &
		LD	(OPREG$),A		;merge the new
		nop
		nop	; OUT	(084h),a	; Switch hardware.....
		LD	A,(LBANK$)		;Get old bank #
		LD	B,A			;& save it
		LD	A,C			;P/u new bank #
		AND	7Fh			;Strip any bit-7
		LD	(LBANK$),A		;& save new bank #
		XOR	C			;Keep bit-7
		OR	B			;Merge in new bank #
		LD	C,A			;& replace into C
		BIT	7,C			;Transfer to new bank?
		LD	B,0			;Init for invoke later
		RET	Z			;No if bit-7 = 0
		EX	(SP),HL			;Exchange RET with new
		CP	A			;transfer & go to it.
		RET