/* XRACER (C) 1999-2000 Richard W.M. Jones <rich@annexia.org> and other AUTHORS
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: joystick_linux.c,v 1.2 2000/01/18 23:24:21 rich Exp $
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <fcntl.h>
#include <linux/joystick.h>

#include "xracer.h"
#include "xracer-joystick.h"
#include "xracer-log.h"

/* File descriptor for the joystick device. */
static int fd = -1;

/* Joystick device. */
const char *xrJoystickDevice = "/dev/js0";

/* Program-level initializations. */
void
xrJoystickInit ()
{
  if ((fd = open (xrJoystickDevice, O_RDONLY)) < 0)
    {
      xrLogPerror ("failed to open joystick device %s", xrJoystickDevice);
      return;
    }
}

/* Read the status of the joystick. */
int
xrJoystickRead (struct xrJoystickStatus *status_rtn)
{
  int status, x, y;
  size_t expected;
  struct JS_DATA_TYPE js;

  if (fd == -1) return -1;

  status = read (fd, &js, expected = JS_RETURN);

  if (status == expected)
    {
      x = js.x;
      y = js.y;

      if (x < 0) x = 0; else if (x > 255) x = 255;
      if (y < 0) y = 0; else if (y > 255) y = 255;

      /* Scale this so that (0,0) is the joystick centre, and the
       * range is [-1,1].
       */
      status_rtn->x = (x - 128) / 128.;
      status_rtn->y = (y - 128) / 128.;

      status_rtn->button[0] = js.buttons & 1;
      status_rtn->button[1] = js.buttons & 2;
      status_rtn->button[2] = js.buttons & 4;
      status_rtn->button[3] = js.buttons & 8;

      return 0;
    }
  else
    {
      xrLogPerror ("unknown status from joystick: %d (ignored)", status);
      return -1;
    }
}
