#include <arch/keyboard.h>
#include <arch/vga.h>

static int resend()
{
	if(in(0x60) == 0xFA)
		return 0;
	else
		return 1;
}

static void clean60()
{
	/* disable and enable in order to get 
	 * another scancode*/
	 
	u8int x = in(0x61);
	out(x|0x80, 0x61);
	out(x&0x7f, 0x61);
	
	return;
}

static void up()
{
	/*enable keyboard controller*/
	
	do{
		out(0x64,0xAE);
	}while(resend());
	
	return;
}

static void down()
{
	/*disable keyboard*/
	do{
		out(0x64,0xAD);
	}while(resend());
	
	return;
}

static u8int read60()
{
	/*read scancode at 0x60*/
	u8int x = in(0x60);
	while(!(in(0x64)&1));
	clean60();
	return x;
}

static void set_scancode(u8int val)
{
	/*set scancode type (1 or 2 or 3)*/
	out(0x60,0xF0);
	while(!(in(0x64)&1));
	out(0x60,val);
	while(!(in(0x64)&1));
	
	
	return;
}



static void time(u8int val)
{
	/*set press key for second and pause time*/
	out(0x60,0xF3);
	while(!(in(0x64)&1));
	out(0x60,val);
	while(!(in(0x64)&1));
		
	return;
}

static void clean_bf()
{
	/*clean output buffer*/
	out(0x60,0xF4);
	while(!(in(0x64)&1));
	
	return;
}

extern void initkey()
{
	kbd.read=read60;
	kbd.set_scancode=set_scancode;
	kbd.up=up;
	kbd.down=down;
	kbd.time=time;
	kbd.clean_bf=clean_bf;
	
	kbd.time(20);
	kbd.set_scancode(2);
	kbd.clean_bf();
	clean60();
	
	return;
}

extern void keyhandler()
{
	kbd.read();
	VGA.drv.write("keyboard interrupt recieved\n");
	kbd.clean_bf();
	
	return;
}

