// Copyright 1994 Brad Pitzel
//
// Feel free to use/distribute/modify as long as credit/copyrights for myself 
// are included.

#include "Joystick.h"

// create Joystick object, open joystick device 0 or 1
Joystick::Joystick( int stick ) : Vstick(stick), 
				VxMax(0), VxMin(0), VxCen(0),
				VyMax(0), VyMin(0), VyCen(0),
				VbLast(0), Vscale(0), Vfd(-1)
	{

#ifdef JOYSTICK
	char *fName;
	
	switch (Vstick) {
		case 0:
			fName="/dev/js0";
			break;
		case 1:
			fName="/dev/js1";
			break;
		default:
			cerr << "Joystick: bad stick # " << Vstick << endl;
			return;
		}
	
	Vfd = open(fName, O_RDONLY);
	if ( Vfd < 0 ) 
		{
		cerr << "Joystick: can't open device " << fName << endl;
		}
	else
		{
		long tmpl;
		tmpl=JS_TIME;
		if (ioctl(Vfd,JS_SET_TIMELIMIT,&tmpl) == -1)
  			cerr << "Joystick:: ioctl failed" << endl;
		}

#endif

	Vjs_data.buttons = 0;
	Vjs_data.x = 0;
	Vjs_data.y = 0;
	}

// set joystick calibration (params to shift >> in order to get max x,y
// below 256)
int Joystick::setCal( int x, int y )
	{

	if (ok())
		{
		struct JS_DATA_TYPE	js_data;
	
		js_data.x = x;
		js_data.y = y;
	
		return ioctl( Vfd, JS_SET_CAL, js_data );
		}
	else
		return -1;
	}


void Joystick::calibrate()
	{

 	if (ok())
 		{
		int tmp;
		
 		cout << "Calibrating joystick " << Vstick << endl;
		cout << endl;


		cout << "Move joystick to LOWER RIGHT and press either button" << endl;

  		while ( (eval()>0) && !aPressed() && !bPressed() );

		// calc correction factors
  		for(tmp=0; Vjs_data.x > 0xff; tmp++, Vjs_data.x=Vjs_data.x >> 1);
  		
  		VxMax = Vjs_data.x;
  		Vjs_data.x=tmp;
  		
  		for(tmp=0; Vjs_data.y > 0xff; tmp++, Vjs_data.y=Vjs_data.y >> 1);
  		
  		VyMax = Vjs_data.y;
  		Vjs_data.y=tmp;

  		if (ioctl(Vfd,JS_SET_CAL,&Vjs_data) == -1)
  			{
  			cerr << "Joystick::calibrate, ioctl failed" << endl;
  			}

		cout << endl;
  		cout << "CENTER joystick and press either button" << endl;

		while ( (eval()>0) && !aPressed() && !bPressed() );

		VxCen = Vjs_data.x;
		VyCen = Vjs_data.y;

		//cout << "Max x:" << VxMax << " Max y:" << VyMax << endl;
		//cout << "Min x:" << VxMin << " Min y:" << VyMin << endl;
		//cout << "Cen x:" << VxCen << " Cen y:" << VyCen << endl;
		}

}
