;
; *** Listing 11-17 ***
;
; Demonstrates the calculation of the offset of the word
; matching a keystroke in a look-up table when SCASW is
; used, where the 2-byte overrun of SCASW must be
; compensated for. The offset in the look-up table is used
; to look up the corresponding address in a second table;
; that address is then jumped to in order to handle the
; keystroke.
;
; This is a standalone program, not to be used with PZTIME
; but rather assembled, linked, and run by itself.
;
stack	segment	para stack 'STACK'
	db	512 dup (?)
stack	ends
;
code	segment	para public 'CODE'
	assume	cs:code, ds:nothing
;
; Main loop, which simply calls VectorOnKey until one of the
; key handlers ends the program.
;
start	proc	near
	call	VectorOnKey
	jmp	start
start	endp
;
; Gets the next 16-bit key code from the BIOS, looks it up
; in KeyLookUpTable, and jumps to the corresponding routine
; according to KeyJumpTable. When the jumped-to routine
; returns, is will return to the code that called
; VectorOnKey. Ignores the key if the key code is not in the
; look-up table.
;
; Input: none
;
; Output: none
;
; Registers altered: AX, CX, DI, ES
;
; Direction flag cleared
;
; Table of 16-bit key codes this routine handles.
;
KeyLookUpTable	label	word
	dw	0011bh	;Esc to exit
	dw	01c0dh	;Enter to beep
;*** Additional key codes go here ***
KEY_LOOK_UP_TABLE_LENGTH_IN_WORDS equ (($-KeyLookUpTable)/2)
;
; Table of addresses to jump to when corresponding key codes
; in KeyLookUpTable are found.
;
KeyJumpTable	label	word
	dw	EscHandler
	dw	EnterHandler
;*** Additional addresses go here ***
;
VectorOnKey	proc	near
WaitKeyLoop:
	mov	ah,1	;BIOS key status function
	int	16h	;invoke BIOS to see if
			; a key is pending
	jz	WaitKeyLoop	;wait until key comes along
	sub	ah,ah	;BIOS get key function
	int	16h	;invoke BIOS to get the key
	push	cs
	pop	es
	mov	di,offset KeyLookUpTable
			;point ES:DI to the table of keys
			; we handle, which is in the same
			; segment as this code
	mov	cx,KEY_LOOK_UP_TABLE_LENGTH_IN_WORDS
			;# of words to scan
	cld
	repnz	scasw	;look up the key
	jnz	WaitKeyLoop	;it's not in the table, so
				; ignore it
	jmp	cs:[KeyJumpTable+di-2-offset KeyLookUpTable]
			;jump to the routine for this key
			; Note that:
			;   DI-2-offset KeyLookUpTable
			; is the offset in KeyLookUpTable of
			; the key we found, with the -2
			; needed to compensate for the
			; 2-byte (1-word) overrun of SCASW
VectorOnKey	endp
;
; Code to handle Esc (ends the program).
;
EscHandler	proc	near
	mov	ah,4ch	;DOS terminate program function
	int	21h	;exit program
EscHandler	endp
;
; Code to handle Enter (beeps the speaker).
;
EnterHandler	proc	near
	mov	ax,0e07h ;AH=0E is BIOS print character
			; function, AL=7 is bell (beep)
			; character
	int	10h	;tell BIOS to beep the speaker
	ret
EnterHandler	endp
;
code	ends
	end	start
