/*
*     ___                       ____               __
*    / _ \___ _    _____ ____  /  _/__  ___  __ __/ /_
*   / ___/ _ \ |/|/ / -_) __/ _/ // _ \/ _ \/ // / __/
*  /_/   \___/__,__/\__/_/   /___/_//_/ .__/\_,_/\__/
*                                    /_/
*
*   Original Code by John Garrison
*   Written August 25-27, 1999
*   To be released under the LGPL
*  
*   Joystick interface routines
*
*   See LICENSE.TXT for more LGPL info
*/

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#ifndef __WIN32__
   #include <sys/ioctl.h>
#endif

#include "powerinput.h"
#include "joystick.h"

int *axis, num_of_axis, num_of_buttons;
int PIJoyHighValue;
char name_of_joystick[80];
int joy_fd1, joy_fd2;

///////////////////////////////////////////////
//          BASIC JOYSTICK ROUTINES          //
///////////////////////////////////////////////

int PI_OpenJoystick(int Joy)
{
   PIJoyHighValue=255;

   PIJoysticks[Joy] = SDL_JoystickOpen(Joy);
   if (PIJoysticks[Joy] == NULL)
      return -1;
   else return 0;
}



PI_JoyData PI_ReadJoystick(int Joy)
{
   int axis, i;
   PI_JoyData JoyDat;

   PI_PollEvent();

   for (i = 0; i < SDL_JoystickNumAxes(PIJoysticks[Joy]); i++){
      axis = (int)(SDL_JoystickGetAxis(PIJoysticks[Joy], i));
      if (axis < -PIJoyHighValue) axis = -PIJoyHighValue;
      else if (axis > PIJoyHighValue) axis = PIJoyHighValue;
      JoyDat.axis[i] = axis;
   }
   for (i = 0; i < SDL_JoystickNumButtons(PIJoysticks[Joy]); i++){
      if (SDL_JoystickGetButton(PIJoysticks[Joy], i) == SDL_PRESSED)
         JoyDat.button[i] = 1;
      else
         JoyDat.button[i] = 0;
   }

   return JoyDat;
}



int PI_CloseJoystick(int Joy)
{
   SDL_JoystickClose(PIJoysticks[Joy]);

   return 0;
}

////////////////////////////////////////
//          WRAPPER ROUTINES          //
////////////////////////////////////////

int PI_IsJoyButtonDown(int Joy, int Button)
{
   PI_PollEvent();

   if (SDL_JoystickGetButton(PIJoysticks[Joy], Button) == SDL_PRESSED)
      return 1;
   else return 0;
}



int PI_JoyAxisDirection(int Joy, int Axis)
{
   PI_JoyData joydat;

   joydat = PI_ReadJoystick(Joy);

   return joydat.axis[Axis];
}



int PI_JoyX(int Joy)
{
   PI_JoyData joydat;

   joydat = PI_ReadJoystick(Joy);

   return joydat.axis[0];
}



int PI_JoyY(int Joy)
{
   PI_JoyData joydat;

   joydat = PI_ReadJoystick(Joy);

   return joydat.axis[1];
}



void PI_SetJoystickHighValue(int Value)
{
   PIJoyHighValue=Value;
}



int PI_AreAnyJoyButtonsDown(int Joy)
{
   int i;
   PI_JoyData joydat;

   joydat = PI_ReadJoystick(Joy);
   for (i = 0; i < SDL_JoystickNumButtons(PIJoysticks[Joy]); i++)
      if (joydat.button[i] == 1)
         return 1;
   return 0;
}
