	TITLE   kbd

	.386

_DATA	SEGMENT
$P1	db	'kb_init: saved %x:%x, kbint %x:%x, eax %x, ecx %x, esi %x, edi %x', 10, 0
_DATA	ENDS

_BSS	SEGMENT word public 'BSS'
	align	4
saveip	dd	?
savecs	dw	?
_BSS	ENDS

DGROUP	GROUP	_DATA,_BSS
CGROUP	GROUP	_TEXT

	extrn	kbdint:near

_TEXT	SEGMENT	dword public use32 'CODE'
	ASSUME	cs:CGROUP, ds:DGROUP

	PUBLIC	kbd_int
kbd_int	PROC FAR
	ASSUME	ds:nothing
	push	eax
	in	al,60h		; read character
	mov	al,20h
	out	020h,al
	pop	eax
	iretd

	pushad
	push	fs
	push	gs
	push	ds
	push	es
	mov	ax,cs:save_ds
	mov	ds,ax
	mov	es,ax
	ASSUME	ds:DGROUP, es: DGROUP
	cld
;	call	kbdint
	in	al,60h		; read character
	mov	al,20h
	out	020h,al
	pop	es
	pop	ds
	ASSUME	ds:nothing, es:nothing
	pop	gs
	pop	fs
	popad
	iretd
save_ds	dw	?
kbd_int	ENDP

	PUBLIC	kbd_init
kbd_init	PROC NEAR
	push	ebx
	push	es
	push	ds
	ASSUME	ds: DGROUP

	mov	ax,cs
	mov	es,ax
	mov	es:save_ds,ds

	mov	ax,03509h		; get vector 09
	int	21h
	mov	saveip,ebx
	mov	savecs,es
	mov	edx,offset kbd_int
	mov	ax,cs
	mov	ds,ax
;	mov	ax,02509h
;	int	21h

	pop	ds
	pop	es

	push	edi
	push	esi
	push	ecx
	push	eax
	push	edx
	movzx	eax,ax
	push	eax
	push	ebx
	movzx	eax,savecs
	push	eax
	push	offset $P1
	extrn	printf:near
	call	printf
	add	esp,36

	pop	ebx
	ret
kbd_init	ENDP

PUBLIC	kbd_exit

kbd_exit	PROC NEAR
	push	ds
	mov	edx,saveip
	mov	ds,savecs
	mov	ax,02509h
	int	21h
	pop	ds
	ret
kbd_exit	ENDP

_TEXT	ends
	end
