;--- List 6a: Checks if any key of the keys table is pressed
;    Input:   -
;    Output:  BC = P(3) = Key/combination currently pressed (-1 = none)
;	      DE = P(4) = K/C pressed in the previous call

	org	#8000

;NEWKEY is the system work area where keyboard status is saved by OS.
;It is 11 bytes long, each byte is a row, and for each byte, each bit
;is the state for the corresponding column (1=not pressed, 0=pressed)

NEWKEY: equ	#FBE5

CHKEY:	ld	ix,TABKEY

LOPKEY: ld	a,(ix)
	cp	#FF
	jr	z,NOKEY

	ld	e,(ix+2)
	ld	d,0
	ld	hl,NEWKEY
	add	hl,de
	ld	a,(hl)	;A = Row state
	cpl

	ld	b,(ix+3)
	inc	b
LOPFIL: srl	a
	djnz	LOPFIL
	jr	nc,NEXTKEY	;Cy = Key state (1=Pressed)

	ld	a,(NEWKEY+6)
	cpl
	and	3
	cp	(ix+1)
	jr	nz,NEXTKEY	;Checks for SHIFT and CTRL

OKKEY:	ld	c,(ix)	;Combination pressed?
	ld	b,0
	ld	de,(OLDKEY)
	ld	(OLDKEY),bc
	ret

NEXTKEY:	inc	ix	;Next combination
	inc	ix
	inc	ix
	inc	ix
	jr	LOPKEY

NOKEY:	ld	bc,-1	;No key or combination pressed
	ld	de,(OLDKEY)
	ld	(OLDKEY),bc
	ret

OLDKEY: dw	-1	;For storing previous combination

;--- Keys table
;    Format: identifier + SHICT + row + column
;    (1 byte each one)
;    SHICT = &B000000CS
;    C=1 if CTRL pressed is required
;    S=1 if SHIFT pressed is required
;    In other words:
;    SHICT=0 for key alone
;    SHICT=1 for key + SHIFT
;    SHICT=2 for key + CTRL
;    SHICT=3 for key + SHIFT + CTRL
;    See figure 1 for the corresponding row and column for each key

;NOTE: identifier #FF is reserved for end of table mark (mandatory)

TABKEY: ;Example table
	db	0,0,7,2	;ESC
	db	1,2,7,2	;CTRL+ESC
	db	2,3,7,2	;CTRL+SHIFT+ESC
	db	3,1,7,2	;SHIFT+ESC
	db	4,0,6,5	;F1
	db	5,3,6,3	;CTRL+SHIFT+CAPS
	db	#FF
