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


// define JOYSTICK during compile to allow joystick support

#ifndef __Joystick__
#define __Joystick__

#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <iostream.h>

#define JS_TIME 1
#define JS_SENS 50

#ifdef JOYSTICK
#	include <linux/joystick.h>
#else
	// just so this will compile even if you don't have the 
	// complete joystick kit (utils and kernel patches).
#	include "joystick-stub.h"
#endif

class Joystick {
    public:
    
	Joystick( int numb );	// pass in either 0 or 1 for joystick 0 or 1

	void	calibrate();	// calibrate joystick, screen must be in
				// text mode for this.
	    
	int eval() 		// read joystick data
		{ 

		if (ok())
			{
			VbLast = Vjs_data.buttons;
			return read(Vfd, &Vjs_data, JS_RETURN); 
			}
		else
			return -1;
		}


	int x() const { return Vjs_data.x; }
	int y() const { return Vjs_data.y; }
	char a() const { return Vjs_data.buttons&1; }
	char b() const { return (Vjs_data.buttons&2)>>1; }
	
	// was button 'a' JUST pressed down ?
    	char aPressed() const 
    		{ 
    		return  a()&!(VbLast&1);
    		}
    	char bPressed() const 
    		{ 
    		return  b()&!( (VbLast>>1)&1 );
    		}

#ifdef JOYSTICK
	char up()    const { return ( Vjs_data.y < (VyCen - JS_SENS) ); }
	char down()  const { return ( Vjs_data.y > (VyCen + JS_SENS) ); }
	char left()  const { return ( Vjs_data.x < (VxCen - JS_SENS) ); }
	char right() const { return ( Vjs_data.x > (VxCen + JS_SENS) ); }
#else
	char up()    const { return 0; }
	char down()  const { return 0; }
	char left()  const { return 0; }
	char right() const { return 0; }
#endif

	// returns -1 if we couldn't open the joystick device
	// i.e. - joystick no good, not available, etc..
#ifdef JOYSTICK
	int	ok() const { return Vfd>=0; }
#else
	int	ok() const { return 0; }
#endif
	
    private:
	int	Vstick;
    	int	Vfd;
    	int	VxMin,VyMin,VxMax,VyMax,VxCen,VyCen,Vscale;
    	struct	JS_DATA_TYPE Vjs_data;
    	char	VbLast;    

	int setCal( int x, int y );

    };
    
#endif
