; zeropage.asm: zero page functions (RST nn plus NMI handler).

		org #0000
		ld SP, #600		; Set stack ptr
		jp J_main		; Run.


;-----------------------------------------------------------------------
; RST #30: F_kpgetchar - Poll the keypad for a key down.
; Key pressed returned in A. Carry flag set if no key down.
		ASSERT $ <= #30
		BLOCK #30-$, 0

F_kpgetchar	
		push BC
		push DE
		ld B, 4		; Number of iterations - 4 rows.
		ld C, C_PIO_PortB_DATA
		ld D, #80	; 1000 0000. Scan the most sig. nibble
F_kpgetchar.ScanLoop
		out (C), D
		in A, (C)
		and #0F
		jr nz, F_kpgetchar.DecodeRowCol
		rr D		; ...activate next output line on PIO
		djnz F_kpgetchar.ScanLoop
		scf		; We got this far, so nothing was pressed
		jr F_kpgetchar.Exit
F_kpgetchar.DecodeRowCol
		; at this stage A contains the row, and B the column.
		; But B will be 1-4, we want it to be 0-3
		dec B		; make sure B=0..3
		rl B		; shift it up two bits
		rl B
		; Count out the bits from the accumulator to compact the
		; row. Result stored in D
		ld D, 0
F_kpgetchar.FindRow
		bit 0, A
		jr nz, F_kpgetchar.MakeLookupByte
		rra
		inc D
		jr F_kpgetchar.FindRow
F_kpgetchar.MakeLookupByte
		ld A, D		; Result into A
		or B		; OR in the result from the first operation

		; The layout of the keypad is not amenable to an algorithmic
		; way of finding it. So we have to use a lookup table.
		push HL		; save HL
		ld HL, T_kpLookup
		ld B, 0		
		ld C, A		; BC = A
		add HL, BC
		ld A, (HL)	; fetch lookup table byte
		pop HL
		
F_kpgetchar.Exit
		pop DE
		pop BC
		ret


;-----------------------------------------------------------------------
; Non-maskable interrupt routine.
		ASSERT $ <= #66
		BLOCK #66-$, 0

NMI		ex af, af'
		exx

		; Update the system counter.
		ld HL, V_syscounter
		inc (HL)

		exx
		ex af, af'
		retn

;-----------------------------------------------------------------------
; System variables
V_syscounter	defw 0
;-----------------------------------------------------------------------
; Lookup tables etc.
T_kpLookup	defb #C, #D, #E, #F, #B, 9, 6, 3, 0, 8, 5, 2, #A, 7, 4, 1

