/*	Copyright Alex Hornby 1994/1995. All rights reserved.
 	See file README for details
*/
#ifdef JOYSTICK

#include "Joystick.h"
#include <iostream.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <vga.h>

Joystick::Joystick(int j) : Control()
{
	if(j!=1 && j!=2) 
	{
		cerr << "Joystick out of range" << endl;
		exit(1);
	}
	init(j);
	calibrate();
}

void 
Joystick::waitfire(void)
{
	int status=read (joyfd, &js_data, JS_RETURN);
	while( !(js_data.buttons & 1) )
		status=read (joyfd, &js_data, JS_RETURN);
	while( (js_data.buttons & 1) )
		status=read (joyfd, &js_data, JS_RETURN);
}

void
Joystick::calibrate(void)
{
	cout << "Centre joystick and press fire\n";
	waitfire();
	centre.x=js_data.x; centre.y=js_data.y;
	cout << "Move joystick to top left and press fire\n";
	waitfire();
	topleft.x=js_data.x; topleft.y=js_data.y;
	cout << "Move joystick to bottom right and press fire\n";
	waitfire();
	botright.x=js_data.x;botright.y=js_data.y;

	right=centre.x+(botright.x-centre.x)/2;
	left=centre.x-(centre.x-topleft.x)/2;
	down=centre.y+(botright.y-centre.y)/2;
	up=centre.y-(centre.y-topleft.y)/2;
}

void
Joystick::fetch(void)
{
	int status = read (joyfd, &js_data, JS_RETURN);
        if (status != JS_RETURN)
        {
                perror ("Joystick::read()");
        }
	for(int i=0;i<=FIRE4;i++)
		last[i]=FALSE;
 
	if(js_data.x>right)
		last[RIGHT]=TRUE;
	if(js_data.x<left)
		last[LEFT]=TRUE;
	if(js_data.y>down)
		last[DOWN]=TRUE;
	if(js_data.y<up)
		last[UP]=TRUE;
	if(js_data.buttons & 1) 
		last[FIRE1]=TRUE;
	if(js_data.buttons & 2) 
		last[FIRE2]=TRUE;
	int key=vga_getkey();
	if(key=='q')
		last[FIRE4]=TRUE;
}


void
Joystick::init(int stick)
{
	/* open joystick device file */
	switch(stick)
	{
	case 1:
        	joyfd = open ("/dev/js0", O_RDONLY);
		break;
	case 2:
		joyfd = open ("/dev/js1", O_RDONLY);
		break;
	}
	
        if (joyfd < 0) {
                perror ("js init");
                exit (1);
        }
}

#endif
