#include <stdio.h>
#include <conio.h>
#include <dos.h>


class JOYSTICK{
int xmin,xmax,ymin,ymax;

inline void getpos(int &x,int &y){
	union REGS regs;
	regs.h.ah=0x84;
	regs.x.dx=1;
	int86(0x15,&regs,&regs);
	x=regs.x.ax;
	y=regs.x.bx;
	}

public:
JOYSTICK(){
	FILE *in;
	in=fopen("JOYSTICK.CAL","rb");
	if (in==NULL){
		calibrate();
		}
	else{
		xmin=getw(in);
		xmax=getw(in);
		ymin=getw(in);
		ymax=getw(in);
		fclose(in);
		}
	}
~JOYSTICK(){
	FILE *out;
	out=fopen("JOYSTICK.CAL","wb");
	putw(xmin,out);
	putw(xmax,out);
	putw(ymin,out);
	putw(ymax,out);
	fclose(out);
	}
void calibrate(){
	union REGS regs;
	xmin=ymin=xmax=ymax=0;
	printf("Move joystick to upper left and press a button.\n");
	while (!button());
	getpos(xmin,ymin);
	while (button());
	printf("Move joystick to lower right and press a button.\n");
	while (!button());
	getpos(xmax,ymax);
	while (button());
	}
int button(int which=0){
	union REGS regs;
	regs.h.ah=0x84;
	regs.x.dx=0;
	int86(0x15,&regs,&regs);
	switch(which){
		case 0:
			return (~regs.h.al)&0xF0;
		case 4:
			return (~regs.h.al)&0x80;
		case 3:
			return (~regs.h.al)&0x40;
		case 2:
			return (~regs.h.al)&0x20;
		case 1:
			return (~regs.h.al)&0x10;
		}
	}
void position(int &x,int &y){
	union REGS regs;
	getpos(x,y);
	x=long(x-xmin)*256L/long(xmax-xmin);
	y=long(y-ymin)*256L/long(ymax-ymin);
	if (x<0) x=0; else if (x>255) x=255;
	if (y<0) y=0; else if (y>255) y=255;
	}

};


/*void main(){
JOYSTICK J;
for (int a=0;a<5000;++a){
	int b1,b2,b3,b4,x,y;
	b1=J.button(1);
	b2=J.button(2);
	b3=J.button(3);
	b4=J.button(4);
	J.position(x,y);
	printf("%i %i %i %i %i %i\n",b1,b2,b3,b4,x,y);
	}
} */




