/*
   Cosmo Gang the Puzzle を Towns Pad で遊ぼう！

    Pad 対応にあたり
      XKOBO (Akira Higuchi a-higuti@math.hokudai.ac.jp さん作)
    の Pad の読みとり部分を参考にさせて頂きました。
*/

#ifdef USE_PAD

#include <stdio.h>
#include <sys/time.h>
#include <linux/pad.h>
#include <linux/fcntl.h>
#include "main.h"
#include "setup.h"
#include "ex.h"

static int pfd;
static int bf;

#define check_pad(KEY)\
 (KEY==keys.up     ||\
  KEY==keys.down   ||\
  KEY==keys.left   ||\
  KEY==keys.right  ||\
  KEY==keys.fall   ||\
  KEY==keys.drop   ||\
  KEY==keys.rot    ||\
  KEY==keys.star   ||\
  KEY==keys.decide ||\
  KEY==keys.yes    ||\
  KEY==keys.no     ||\
  KEY==keys.quit   ||\
  KEY==keys.pause)

unsigned int pad()
{
  fd_set readfds;
  struct timeval timeout;
  KeySym cb=0,cret=0;
  struct pad_event cev;
  static struct pad_event pev;
  static KeySym pb=0,pret=0;

  bf=0;
  FD_ZERO(&readfds);
  FD_SET(pfd,&readfds);
  timeout.tv_sec = 0;
  timeout.tv_usec = 0;    
  select(32,&readfds,NULL,NULL,&timeout);
  if(FD_ISSET(pfd,&readfds)==0) return pb;
  read(pfd, &cev, sizeof(cev));
  bf=1;

  cb=cev.buttons;

  if(cb==pb) cb=pret;
  else
  {
    if(!check_pad(cb)) cb&=~pb;
    pb=cb;
  }
    
  cret=cb;

  if(pret!=0    && cret==0) event.type=KeyRelease;
  if(cret!=pret && cret!=0) event.type=KeyPress;
  if(key==keys.quit||key==keys.pause) qp_f=key;

  return pret=cret;
}

void clear_pad_buffer()
{
  event.type=0;

  do {
    key=pad();
  } while(bf);
}

int pad_init(char *dev)
{
  if((pfd=open(dev, O_RDONLY))>0) return 1;

  fprintf(stderr,"Can't open device: %s\n",dev);
  return 0;
}

#endif
