#include <dos.h>
#include "keyclass.h"

unsigned char __keybuf[128];

KeybHandler::KeybHandler(void)
{
	for(int i=0; i<128; i++)
		__keybuf[i]=0;
	// Get address of the old interrupt.
	Old_KeybIntHandler = getvect(KEYBINT);
}

KeybHandler::~KeybHandler(void)
{
	// Restore the old handler.
	setvect(KEYBINT, Old_KeybIntHandler);
}

void KeybHandler::enableHandler(void)
{
	// Set vector to the new handler.
	setvect(KEYBINT, __KeybIntHandler);
}

void KeybHandler::disableHandler(void)
{
	// Restore the old handler.
	setvect(KEYBINT, Old_KeybIntHandler);
}

int KeybHandler::operator[](int index)
{
	return __keybuf[index];
}

void interrupt __KeybIntHandler(...)
{
	int scancode;
	asm
	{
		in	al,60h
		mov	ah,0
		cmp	al,128
		jnb	breakcode
		mov scancode,ax
	}
	__keybuf[scancode]=1;
	asm jmp cleanup;

	asm
	{
	breakcode:
		and	al,127
		mov	scancode,ax
	}
	__keybuf[scancode]=0;

	asm
	{
cleanup:
		in	al,61h
		mov	ah,ah
		or	al,80h
		out	61h,al
		mov	al,20h
		out	20h,al
	}
}
