k_sccbuf	equ	0x201140	; last 4 scancodes
kbd_eflg	equ	0x201144	; flags for e0, e1 scancode escape values (byte)
kb_bufpos	equ	0x201145	; offset into the circular eventb keyboard buffer (byte)
kb_sstat	equ	0x201146	; bitfield for the keyboard shift status and LEDs (short)
kb_eventb	equ	0x201148	; 128 entries at 8 bytes each = 1K = 0x400
mouse_ack	equ	0x2015cb		; flag that a mouse ACK byte was seen & discarded
m_reinit	equ	0x2015cc	; flag that a mouse 0xff init byte was seen & discarded
m_flags		equ	0x2015cd	; flag bits: 7-activity, 1-btn4&5 NOT exist, 0-3/4 byte
; bits 2 through 6 in m_flags are mouse-button state (1= down)
m_pktpos	equ	0x2015ce		; byte count in current mouse packet
kbd_ack		equ	0x2015cf		; flag that a kbd ACK byte was seen

irq1h:
;	push ebp
;	mov bp, ds	eventually also save DS (when ring3 is active)
	push eax
	push ebx
	push edx
	push edi
	mov eax, 0x20		; clear upper eax until all done
i12_entry:			; mouse interrupt entrypoint
	out 0x20, al		; ack to the PIC for hw interrupt

.kb_rdlp:
	in al, 0x64		; any scancodes/bytes left to read?
	test al, 1
	jne short .chk_mse
	sti
	pop edi			; no -- handler is done
	pop edx
	pop ebx
	pop eax
;	mov ds, bp
;	pop ebp
	iret
.chk_mse:
	test al, 0x20			; is incoming byte from the mouse?
	je short .kb_notmse

	or [m_flags], byte 0x80		; set the "mouse activity" flag
	in al, 0x60			; get the mouse byte
	mov ah, [m_pktpos]
	test ah, ah			; in the middle of a mouse packet?
	je short .not_pkt
.strt_pkt:
	call mouse_pakt		; decode the byte into X Y Z, according to ah= m_pktpos
	jmp short .kb_rdlp
.not_pkt:
	cmp al, 0xFA			; is byte an ACK?
	jne short .m_isnak
	mov [mouse_ack], byte 1		; got a command ack
	jmp short .kb_rdlp
.m_isnak:
	cmp al, 0xFE			; is it a NAK?
	jne short .m_isrst
	mov [mouse_ack], byte 0		; command ACK failed
	jmp short .kb_rdlp
.m_isrst:
	cmp al, 0xAA			; it is a reset code?
	jne short .m_isID
	mov [m_reinit], byte 1		; flag to reinitialize the mouse
	jmp short .kb_rdlp
.m_isID:
	test al, 8			; is this the 1st byte of a packet?
	jne .strt_pkt			; if so, jump back to the packet decoder
	mov [mouseID], al		; store byte in mouseID
	jmp short .kb_rdlp

.kb_notmse:
	in al, 0x60		; get the scancode from the keyboard
	mov edi, k_sccbuf
	mov ebx, [edi]		; recover 4b scancode "buffer"
	shl ebx, 8		; shift buffer up one byte

	mov bl, al		; insert new scancode into buffer
	mov [edi], ebx		; save dword scancode buffer

	mov al, [p61_disabl]	; flash the disable bit on p61h to ack scancode
	out 0x61, al
	and al, 0x7f
	out 0x61, al

	mov al, bl		; get the scancode back into AL

	call key_xlat		; try to do "unshifted" key translation
	je near .kb_rdlp	; need another scancode to complete escape sequence? - HIHI! change back to short jmp when removing kbd_notran

	; dl = "unshifted" translated scancode, dh = keyup flag, ah = 0
	mov [kbd_eflg], ah	; whenever the code gets to here, escape flag should be cleared
	mov al, [kb_bufpos]	; calculate the new kbd event buffer position
	inc al
	mov [kb_bufpos], al	; and save it

	btr eax, 7		; force sign bit to 0, and test it
	lea edi, [kb_eventb + eax*8]	; edi -> current event buf entry
	mov [edi + 4], ebx	; save the scancode buffer
	mov [edi + 1], dl		; store the partial key translation
	movzx ebx, word [kb_sstat]	; bx = shift status

; event buffer entry format:
; fully xlated char, xlated key "unshifted", shft state + flag bit (word), last 4 scancodes
; shift state bits= lshft, rshft, l-ctl, r-ctl, l-alt, r-alt, (later?) fake lshft, fake rshft
; shift state byte 2 (bits, low to high) = (blank), (blank), scrlk, numlk, capslk, (3 blank)

	call kb_shift		; calculate dl = fully translated code

	mov [edi], dl		; final output byte (fully translated)
	mov [edi + 2], bx	; store the current shift status with the current event
	mov [kb_sstat], bx 	; and save any new shift status externally, too
	jmp near .kb_rdlp	; then try to process the next input byte


; translation utility for irq1 -- apply ctl, shift, numlock, capslock to "unshifted" scancode
kb_shift:
	btr edx, 8		; test if this was a keyup event (and force dh to 0)
	jnc short .kbd_kdwn
	cmp dl, 5		; Test for shift, ctl, alt status changes (and fake L and Rshift?)
	ja short .k_upout
	btr ebx, edx		; clear the dl shift bit
.k_upout:
	mov dl, 190		; keyup event message number
	ret

.kbd_kdwn:			; finish translating the output byte
	cmp dl, 5		; test for any shift, ctl, alt status changes
	ja short .k_fakes
	bts ebx, edx		; set bit for keydown of shift, ctl, alt
	jmp short .k_movctl	; Note: these keys repeat their keydowns!
	; could check the carry bit and swallow repeated keydowns ...
.k_fakes:
; handle fake L and Rshifts for now -- could flip bx status bits later
	cmp dl, 8
	jb short .k_movctl

	cmp dl, 27		; test for Esc key
	je short .k_alldone	; it's fully translated
	cmp dl, 10		; test for backspace, tab
	jb short .k_alldone	; BS, tab are fully translated
	cmp dl, 13		; test for enter, scrllk, numlk, capslk
	ja short .k_movctl
	je short .k_alldone	; enter is fully translated
	btc ebx, edx		; toggle the dl shift bit for the proper Lock key (bit 10 to 12)
.k_movctl:
	cmp dl, 0x1f		; is current code in the traditional ctl char range?
	ja short .k_iskpad
	add dl, 156		; move to range 156 - 187
	ret			; anything in this range is fully translated now
.k_iskpad:
	cmp dl, 140		; translate keypad keys according to NumLk
	jb short .k_xshift
	cmp dl, 155
	ja short .k_xshift
	bt ebx, 11		; is NumLk on?
	jc short .k_numlk
	cmp dl, 149		; NO! Is it a numeric key?
	ja short .k_nonnum
	add dl, 38		; translate all numeric keys properly, except 5
	cmp dl, 183		; was it a 5?
	jne short .k_alldone
	mov dl, '5'		; fix the 5, and it can't be shifted
	ret
.k_nonnum:
	cmp dl, 154		; is it the Keypad . key?
	jne short .k_notnum
	mov dl, 0x7f		; Del -- fully translated
	ret

.k_numlk:			; Keypad key down with NumLk ON
	cmp dl, 149		; is it numeric?
	ja short .k_notnum
	sub dl, 92		; Yes, convert to a digit, 0x30 - 0x39, fully translated
	ret
.k_notnum:
	sub dl, 108		; No. Fully translate everything except Kp-Ent
	cmp dl, 44		; was it a Kp-Ent?
	jne short .k_alldone
	mov dl, 13		; match Kp-Ent to regular Enter
	ret
.k_xshift:
	cmp dl, 0x7d
	ja short .k_alldone	; anything in this range is fully translated now

; Anything left is printable, or a control char

	cmp dl, 0x20		; can't modify a space
	je short .k_alldone
	test bx, 3		; is either shift active?
	je short .k_unshft
	test bx, 0xc		; Yes, and is either Ctrl key active, too?
	jne short .k_alldone	; if so, that's untranslatable
	bt ebx, 12		; is CapsLk on?
	jc short .k_alldone	; if so, there is no translation left to do
.k_capme:
	cmp dl, '`'		; CAPITALIZE dl
	jbe short .k_tstbck
	sub dl, 0x20		; it's a letter -- cvt to upper
.k_alldone:
	ret
.k_tstbck:			; already did the cmp to `
	jne short .k_brkt
	mov dl, '~'
	ret
.k_brkt:
	cmp dl, '['
	jb short .k_squote
	add dl, 0x20		; make curly brackets, or |
	ret
.k_squote:
	cmp dl, 39
	jne short .k_slkup
	mov dl, '"'
	ret
.k_slkup:
	; edx is somewhere between 44 and 61 -- need to use it as an index into ks_lookup
	mov dl, [ks_lkup - 44 + edx]
	ret

.k_unshft:
	test bx, 0xc		; Is either Ctrl key active?
	jne short .k_ctlaz	; if so, start by testing a-z
	bt ebx, 12		; is CapsLk active?
	jc short .k_capme
	ret
.k_ctlaz:
	cmp dl, '`'
	jbe short .k_ctl@
	and dl, 0x1f		; it's a letter, get rid of non-ctl bits
	ret
.k_ctl@:
	cmp dl, '2'
	jne short .k_ctl6
	xor dl, dl
	ret
.k_ctl6:
	cmp dl, '6'
	jne short .k_ctl_
	mov dl, 0x1e
	ret
.k_ctl_:
	cmp dl, '-'
	jne short .k_ctlbrk
	mov dl, 0x1f
	ret
.k_ctlbrk:
	cmp dl, '['
	jb short .k_alldone
	cmp dl, ']'
	ja short .k_alldone
	and dl, 0x1f
	ret


; utility function for IRQ1 handler -- partial scancode translation (without "shifts")
key_xlat:

; upflag = 0;			// a pseudoC version of this scancode translator
; edi = xtbl;
; if (al > 0x7f){
;  al &= 0x7f;		// all further calculations account for the fact that this bit is gone
;  // deal with theoretical 3 scancode PAUSEup sequence
;  if (escc == 0x40){
;   if (al == 0x1d){ escc= 0x80; goto more; }
;   if (al == 0x61) goto more;		// e1 start of keyup sequence on PAUSE
;  }
;  if (escc == 0x80){
;   if (al == 0x45){ xlate = PAUSE; upflag = 1; goto done; }
;  }
;  // now, the e0 keyup sequences:
;  if ((escc&1) !=0){ edi = e0xtbl; upflag = 1; goto XLAT; }
;  if (al == 0x7a) { xlate= ACK; goto done; }	// keyboard command ACK
;  if (al == 0x7e) { xlate= NAK; goto done; }	// keyboard command NAK, resend if possible
;  if (al == 0x61) { escc= 0x10; goto more; }	// 0xe1 -- start of PAUSE sequence
;  if (al == 0x60) { escc= 1; goto more; }	// 0xe0 -- std escape code
;  upflag = 1;
; }
;  // deal with theoretical 3 scancode PAUSE sequence
; if (escc == 0x10 && al == 0x1d){ escc= 0x20; goto more; }
; if (escc == 0x20 && al == 0x45){ escc= 0x40; xlate = PAUSE; goto done; }
; if ((escc&1) !=0){ edi = e0xtbl; }
;XLAT:
; xlate = edi[al];
;done:
; if (xlate == 0xff) goto KEYERR;
; escc= 0;

	xor edx, edx		; clear dh = keyup flag
	mov dl, [kbd_eflg]
	mov edi, kbd_table

	btr eax, 7		; test & get rid of the high bit
	jnc short .kb_ph10	; is it a keyup event or escape code?

	cmp dl, 0x40		; PAUSEup detection section -- 0x40
	jne short .kb_ph80
	cmp al, 0x1d		; 2nd char of PAUSEup
	jne short .k_pe1up
	mov dl, 0x80
	jmp short .k_donefn
.k_pe1up:
	cmp al, 0x61		; 1st char of PAUSEup -- 0xe1
	je short .k_donefn	; dl is already 0x40
.kb_ph80:
	cmp dl, 0x80		; looking for last char of PAUSEup?
	jne short .kb_e0up
	cmp al, 0x45		; is it the right char?
	jne short .k_tstack
	mov dl, 153		; completed e1 PAUSEup sequence
	mov dh, 1		; mark it as a keyup event
	jmp short .kb_event
.kb_e0up:
	test dl, 1		; in an e0 escape sequence?
	je short .k_tstack
	mov edi, kbd_e0tbl	; use the e0 lookup table instead
	mov dh, 1		; mark it as a  keyup event
	jmp short .kb_xlat
.k_tstack:
	cmp al, 0x7a		; ACK response to keyboard command
	jne short .k_tstnak
	mov [kbd_ack], byte 1
	mov dl, 188		; dl = output char storage
	jmp short .kb_event
.k_tstnak:
	cmp al, 0x7e		; NAK response to keyboard command
	jne short .k_tste1p
	mov [kbd_ack], byte 0
	mov dl, 189
	jmp short .kb_event
.k_tste1p:
	cmp al, 0x61		; test for start of PAUSE sequence
	jne short .k_tste0
	mov dl, 0x10
	jmp short .k_donefn
.k_tste0:
	cmp al, 0x60	; escape code for extended scancode sequence (except pause type 1)
	jne short .keyup
	mov dl, 1		; e0 escape -- set flag for one escaped scancode
.k_donefn:
	mov [kbd_eflg], dl	; need another scancode to complete the sequence
	ret
.keyup:
	mov dh, 1		; mark the keyup event -- end of keyup section

.kb_ph10:
	cmp dl, 0x10		; PAUSE detection section -- 0x10
	jne short .kb_ph20
	cmp al, 0x1d
	jne short .kb_xlat
	mov dl, 0x20
	jmp short .k_donefn
.kb_ph20:
	cmp dl, 0x20		; e1 PAUSE detection, 0x20
	jne short .k_e0esc
	cmp al, 0x45
	jne short .kb_xlat
	mov dl, 0x40		; next sequence MUST be PAUSEup! (no typematic on PAUSE)
	mov al, 16		; PAUSE message completed
	jmp short .kb_event
.k_e0esc:
	test dl, 1		; in an e0 escape sequence?
	je short .kb_xlat
	mov edi, kbd_e0tbl	; use the e0 lookup table instead

.kb_xlat:
	mov dl, 0xff
	cmp eax, 0x60		; 0x60 or above are illegal values
	jae short .kb_event
	mov dl, [edi + eax]	; grab the "unshifted" translated character from table
.kb_event:
	inc edi			; force the "zero" flag to clear
	ret


; ********* utility for kbd/mouse irq1 handler -- parse mouse state packet **********
; decode the current byte into X Y Z & buttons, according to ah= m_pktpos
mouse_pakt:
;	decode mouse packet byte here, however you want
	inc ah
	mov [m_pktpos], ah	; prepare to receive next mouse packet byte
	ret


kbd_table:
 	db	255,  27, '1234567890-=', 8, 9		; bad, esc, backspace & tab
 	db	'qwertyuiop[]', 13, 2			; Enter & left ctl
 	db	'asdfghjkl;', 39, '`', 0		; Left shift
 	db	'\zxcvbnm,./', 1			; Right shift
 	db	150, 4, ' ', 12			; Kp*, Left Alt, sp, NumLock
 	db	128, 129, 130, 131, 132, 133, 134, 135, 136, 137	; F1 - F10
 	db	11, 10, 147, 148, 149, 153	; CapsLock, ScrlLck, Kp7-9, Kp-
 	db	144, 145, 146, 151		; Kp4-6, Kp+
 	db	141, 142, 143, 140, 154, 14	; Kp1-3, Kp0, Kp., Alt-PrtSc
 	db	255, 255, 138, 139, 255		; 2 bad, F11, F12, 1 bad
 	db	255, 255, 255, 255, 255, 255	; 5a to 5f are bad
; and now for all the codes with an e0 in front
kbd_e0tbl:
 	db	255, 255, 255, 255, 255, 255, 255, 255		; most e0 esc's are illegal
 	db	255, 255, 255, 255, 255, 255, 255, 255		; 8 to 0f
 	db	255, 255, 255, 255, 255, 255, 255, 255		; 10 to 17
 	db	255, 255, 255, 255, 152, 3, 255, 255		; 18 to 1b, KpEnt, Rctl, 1e, 1f
 	db	255, 255, 255, 255, 255, 255, 255, 255		; 20 to 27
 	db	255, 255, 6, 255, 255, 255, 255, 255		; 28, 29, fake Lshft, 2b to 2f
	db	255, 255, 255, 255, 255, 155, 7, 15		; 30 to 34, Kp/, fake Rshft, ctlPrtScn
 	db	5, 255, 255, 255, 255, 255, 255, 255		; Right Alt, 39 to 3f
 	db	255, 255, 255, 255, 255, 16, 17, 29		; 40 to 44, Pause, ctlPause, Home
 	db	30, 31, 255, 26					; arrUp, PgUp, bad, arrLeft
 	db	255, 28, 255, 23				; bad, arrRight, bad, End
 	db	24, 25, 22, 0x7f				; arrDown, PgDn, Ins, Del
 	db	255, 255, 255, 255				; 54 to 57
 	db	255, 255, 255, 20				; 58 to 5a bad, LWindow
 	db	21, 18, 255, 255				; RWindow, Menu, 5e, 5f
ks_lkup:
	db	'<_>?)!@#$%^&*(', 255, ':', 255, '+'		; a few shifted ascii chars

