#include "SDL.h"
#include "joystick_SDL.h"


int numJoy; // number of joystick available
int numAxes;
SDL_Joystick* joystick;
	
	

int joystick_init()
{
	int dummy;
	numJoy = SDL_NumJoysticks();
	
	if (numJoy<0)
	{
		joystick = SDL_JoystickOpen(0); //use first joystick, if any
		numAxes = SDL_JoystickNumAxes (joystick);
		fprintf( stderr, "Joystick found, Number of axes: %d \n", numAxes);
		dummy = SDL_JoystickEventState(SDL_QUERY);
	}
	else
	{
		fprintf( stderr, "No Joystick could be opened!! \n");
	}
	
	return 1;
}



void joystick_getXYZR(float *X, float *Y, float *Z, float *R, bool doX, bool doY, bool doZ, bool doR)
{
	if (SDL_JoystickOpened(0))
	{
		if (numAxes>0 && doX) *X = (float(SDL_JoystickGetAxis(joystick, 0))/32768.0f) - 1.0f;
		if (numAxes>1 && doY) *Y = (float(SDL_JoystickGetAxis(joystick, 1))/32768.0f) - 1.0f;
		if (numAxes>2 && doR) *Z = (float(SDL_JoystickGetAxis(joystick, 2))/32768.0f) - 1.0f;
		if (numAxes>3 && doZ) *R = (float(SDL_JoystickGetAxis(joystick, 3))/32768.0f) - 1.0f;
	}
}



void joystick_close()
{
	if (numJoy<0)
	{
		SDL_JoystickClose(joystick); // Close joystick, if any
	}
}