/* Mednafen - Multi-system Emulator
 *
 * 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
 */

#include <stdlib.h>

#include "pce.h"
#include "input.h"
#include "../movie.h"
#include "../netplay.h"

static uint8 *jp_ptr;
//static 
uint8 pce_jp_data[5]; // Accessed in HES playing code
static uint8 sel;
static uint8 read_index = 0;

void PCEINPUT_SetInput(int port, int type, void *ptr, int attrib)
{
 jp_ptr = (uint8 *)ptr;
}

void INPUT_Frame(void)
{
 SFORMAT StateRegs[] =
 {
  SFARRAY(jp_ptr, 5),
  SFEND
 };
 #ifdef NETWORK
 if(MDFNnetplay)
  NetplayUpdate(jp_ptr);
 #endif
 MDFNMOV_AddJoy(StateRegs);

 for(int x = 0; x < 5; x++)
  pce_jp_data[x] = jp_ptr[x];
}

uint8 INPUT_Read(unsigned int A)
{
 uint8 ret = 0xF;
 int tmp_ri = read_index;

 if(tmp_ri > 4)
  ret ^= 0xF;
 else
 {
  if(sel & 1)
   ret ^= pce_jp_data[tmp_ri] >> 4;
  else
   ret ^= pce_jp_data[tmp_ri] & 0x0F;
 }
 return(0x80 | 0x30 | ret); // always-set bits | return value.  Simple as pumpkin doughnuts!
}

void INPUT_Write(unsigned int A, uint8 V)
{
 if((V & 1) && !(sel & 2) && (V & 2))
  read_index = 0;
 else if((V & 1) && !(sel & 1))
 {
  if(read_index < 255)
   read_index++;
 }
 sel = V & 3;
}

int INPUT_StateAction(StateMem *sm, int load, int data_only)
{
 SFORMAT StateRegs[] =
 {
  SFARRAY(pce_jp_data, 5),
  SFVAR(sel),
  SFVAR(read_index),
  SFEND
 };
 int ret =  MDFNSS_StateAction(sm, load, data_only, StateRegs, "JOY");
 
 return(ret);
}
