;--- List 4a: Icon scanner in assembler
;    With a given pair of coordinates, it scans a coordinates table
;    corresponding to icons positions, and it returns the icon number
;    which contains the given coordinates.
;    Input:   P(3) = BC = X coordinate
;	      P(4) = DE = Y coordenada
;    Output:  P(5) = HL = Found icon identifier (-1:none)

	org	#8000

	push	bc,de	;So P(3) and P(4) are not modified
	call	CHKICON
	pop	de,bc
	ret

CHKICON:	ld	ix,TABLE_ICON

LOOPICON:	 ld	 a,(ix)
	cp	#FF
	jr	z,ENDICON

	ld	l,(ix+1)
	ld	h,(ix+3)
	ld	a,c
	call	RANGE
	jr	nz,NOICON

	ld	l,(ix+2)
	ld	h,(ix+4)
	ld	a,e
	call	RANGE
	jr	nz,NOICON

YESICON: ld	 l,(ix)
	ld	h,0
	ret

NOICON:	inc	ix
	inc	ix
	inc	ix
	inc	ix
	inc	ix
	jr	LOOPICON

ENDICON:	ld	hl,-1
	ret

;--- Subroutine: RANGE
;      Checks a byte for being or not inside a given range
;    INPUT:	 H = Upper value of range (inclusive)
;		 L = Lower value of range (inclusive)
;                A = Byte
;    OUTPUT:	 Z = 1 if inside range (Cy = ?)
;		 Cy= 1 if above range (Z = 0)
;		 Cy= 0 if below range (Z = 0)
;    MODIFY:	 AF

RANGE:	cp	l	;Smaller?
	ccf
	ret	nc

	cp	h	;Bigger?
	jr	z,R_H
	ccf
	ret	c

R_H:	push	bc	;=H?
	ld	b,a
	xor	a
	ld	a,b
	pop	bc
	ret


;--- Icons coordinates table
;    Format: identifier + start x + start y + end x + end y
;    (1 byte each one)

;    NOTE: identifier #FF is reserved for the end of table mark (mandatory)

;    Assuming that all icons are placed in a rectangular array starting with
;    base position (BX, BY), and icons have a size TX x TY, we can use
;    the macro "icon":

BX:	equ	0	;Sample values
BY:	equ	200
TX:	equ	11
TY:	equ	11

icon:	macro	@num,@xi,@yi
	db	@num,BX+@xi*TX,BY+@yi*TY,BX+@xi*TX+TX-1,BY+@yi*TY+TY-1
	endm

;Sample: 5 x 2 icons table:
;01234
;56789

TABLE_ICON:
_0:	icon	0,0,0
_1:	icon	1,1,0
_2:	icon	2,2,0
_3:	icon	3,3,0
_4:	icon	4,4,0
_5:	icon	5,0,1
_6:	icon	6,1,1
_7:	icon	7,2,1
_8:	icon	8,3,1
_9:	icon	9,4,1
END:	db	#FF
