// mouse.c
// 10/03/03
// Author: Josh Holtrop


//This method initializes the ps/2 mouse
void mouse_init()
{
	outportb(0x64, 0x20);		//tell keyboard controller we are going to read keyboard controller command byte
	byte temp = inportb(0x60);	//read keyboard controller command byte
	outportb(0x64, 0x60);		//tell keyboard controller we are going to write keyboard controller command byte
	outportb(0x60, 0x03 | (temp&0x40));	//write keyboard controller command byte: enable mouse/keyboard ints, include original XLATE bit from temp (bit6)

 	outportb(0x64, 0xA8);	//enable mouse port

	outportb(0x64, 0xD4);	//send command to mouse, not kbd
	outportb(0x60, 0xF4);	//enable data reporting
	
	mouse_x = video_mode.XResolution >> 1;
	mouse_y = video_mode.YResolution >> 1;

	//outportb(0x64, 0xD4);
	//outportb(0x60, 0xE7);	//scaling 2:1
}


//This method is called when a mouse interrupt occurs
void isr_mouse()
{
	byte inb = inportb(0x60);	//read mouse byte
	//printf("InB: %x\n", inb);
	//return;
	if ((inb == 0xFA) && (mouse_bytesRead < 1))		//ACK
		return;
	mouse_inbuffer[mouse_bytesRead] = inb;
	mouse_bytesRead++;
	if (mouse_bytesRead == 3)	//complete packet received
	{
		mouse_bytesRead = 0;
		int adjx = (char) mouse_inbuffer[1];
		int adjy = (char) mouse_inbuffer[2];
		mouse_x += adjx;
		mouse_y -= adjy;						//-= because screen y coordinates are opposite mouse y coordinates
		if (mouse_x < 0)
			mouse_x = 0;
		if (mouse_x >= video_mode.XResolution)
			mouse_x = video_mode.XResolution - 1;
		if (mouse_y < 0)
			mouse_y = 0;
		if (mouse_y >= video_mode.YResolution)
			mouse_y = video_mode.YResolution - 1;
		if (mouse_inbuffer[0] & 0x01)	//left button
		{
			video_pset(mouse_x, mouse_y, 0x00FF8800);
			printf("X: %d, Y: %d\n", mouse_x, mouse_y);
		}
		else
		{
			video_pset(mouse_x, mouse_y, 0x00FFFFFF);
			printf("X: %d, Y: %d\n", mouse_x, mouse_y);
		}
	}
}





