//////////////////////////////////////////////////////////////////////////////
//
//  This file is part of the Atari Machine Specific Library,
//  and is Copyright 1992 by Warwick W. Allison.
//
//  You are free to copy and modify these sources, provided you acknoledge
//  the origin by retaining this notice, and adhere to the conditions
//  described in the file COPYING.
//
//////////////////////////////////////////////////////////////////////////////

#include <osbind.h>
#include "Joystick.h"
#include "JoyISR.h"

/* GLOBAL */ volatile int JoyFlags[2]={0,0};

const char JoyJoyString[]="\024";
const char MouseJoyString[]="\010";

int XDif[16] = { 0,0,0,0,-1,-1,-1,-1,1,1,1,1,0,0,0,0 };
int YDif[16] = { 0,-1,1,0,0,-1,1,0,0,-1,1,0,0,-1,1,0 };

static int Enabled[2];
static void* OldJoy;

Joystick::Joystick(int port=1)
{
	if (port==0 || port==1) {
		if (!Enabled[port]) {
			if (!Enabled[1-port]) {
				// Very first!
				_KBDVECS * KV=Kbdvbase();
				OldJoy=KV->joyvec;
				KV->joyvec=JoyISR;
			}
			if (port==0) Ikbdws(0,JoyJoyString);
		}

		Enabled[port]++;
		Flags=&JoyFlags[port];
	} else {
		// What shall we do with the drunken sailor?
	}
}

Joystick::~Joystick()
{
	int port=Flags==&JoyFlags[1]; // Resurect "port" from init

	Enabled[port]--;

	if (!Enabled[port]) {
		if (!Enabled[1-port]) {
			// Very last!
			_KBDVECS * KV=Kbdvbase();
			KV->joyvec=OldJoy;
		}
		if (port==0) Ikbdws(0,MouseJoyString);
	}
}
