#include "mapinc.h"

static uint8 lastV ;

static DECLFW(M241wr)
{
//  FCEU_printf("Wr: $%04x:$%02x, $%04x\n",A,V,X.PC);
 if(A<0x8000)
 {
// printf("$%04x:$%02x, $%04x\n",A,V,X.PC);
 }
 else
 {
	 lastV = V ;
  setprg32(0x8000, V);
 }
}

static DECLFR(M241rd)
{
 //DumpMem("out",0x8000,0xffff);
 //printf("Rd: $%04x, $%04x\n",A,X.PC);
 return(0x50);
}
static int StateAction(StateMem *sm, int load, int data_only)
{
 SFORMAT StateRegs[] =
 {
  SFVAR(lastV),
  SFEND
 };

 int ret = MDFNSS_StateAction(sm, load, data_only, StateRegs, "MAPR");

 if(load)
	 setprg32(0x8000, lastV ) ;
 return(ret);
}

static void Power(CartInfo *info)
{
 lastV = 0 ;
	setprg16(0x8000,0);
	setprg16(0xC000,~0);
	setchr8(0);
 setprg32(0x8000, 0);
}

int Mapper241_Init(CartInfo *info)
{
	info->Power = Power ;
	info->StateAction = StateAction;
	info->Reset = Power ;
	
	setprg16(0x8000,0);
	setprg16(0xC000,~0);
	setchr8(0);

 setprg32(0x8000, 0);

	SetReadHandler(0x8000,0xFFFF,CartBR);

 SetWriteHandler(0x5000,0x5fff,M241wr);
 SetWriteHandler(0x8000,0xFFFF,M241wr);
 SetReadHandler(0x4020,0x5fff,M241rd);

 return 1 ;
}
