/* FCE Ultra - NES/Famicom Emulator
 *
 * Copyright notice for this file:
 *  Copyright (C) 2002 Ben Parnell
 *
 * 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 "mapinc.h"

static uint8 rg[2] ;

static void DoPRG(void)
{
  int32 b=((rg[0]>>1)&0xF) | ((rg[0]>>3)&0x10) | ((rg[1]&1)<<5);
  if(rg[0]&0x20)        // 16 KB
  {
   setprg16(0x8000,(b<<1)|(rg[0]&1));
   setprg16(0xC000,(b<<1)|(rg[0]&1));
  }
  else
   setprg32(0x8000, b);
}

static DECLFW(Mapper226_write)
{
 rg[A&1]=V;
 DoPRG();
 if(A&1)
 {
  if(rg[1]&2)
   PPUCHRRAM=0;  // Write protected.
  else
   PPUCHRRAM=0xFF; // Not write protected.
 }
 else
	 setmirror( (rg[0]>>6)&1 ? MI_V : MI_H );
  //MIRROR_SET2((rg[0]>>6)&1);
}

static void M26Reset(void)
{
 rg[0]=rg[1]=0;
 DoPRG();
 PPUCHRRAM=0xFF;
 setmirror( MI_V ) ;
 //MIRROR_SET2(0);
}

static void M26Restore(int version)
{
 DoPRG();
 if(rg[1]&2)
  PPUCHRRAM=0;  // Write protected.
 else
  PPUCHRRAM=0xFF; // Not write protected.
	 setmirror( (rg[0]>>6)&1 ? MI_V : MI_H );
// MIRROR_SET2((rg[0]>>6)&1);
}


static int StateAction(StateMem *sm, int load, int data_only)
{
 SFORMAT StateRegs[] =
 {
  SFARRAY( rg, 2),
  SFVAR(PPUCHRRAM),
  SFEND
 };

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

 if(load)
  M26Restore(0) ;
 return(ret);
}

static void Power(CartInfo *info)
{
	setprg8r(1,0x6000,0);
	setprg16(0x8000,0);
	setprg16(0xC000,~0);
	setchr8(0);
	M26Reset() ;

 //rg[0]=rg[1]=0;
 //DoPRG();
 //PPUCHRRAM=0xFF;
 //setmirror( MI_H ) ;
}



int Mapper226_Init(CartInfo *info)
{
	info->Power = Power ;
	info->StateAction = StateAction;
	info->Reset = Power ;

	setprg8r(1,0x6000,0);
	setprg16(0x8000,0);
	setprg16(0xC000,~0);
	setchr8(0);
	SetReadHandler(0x8000,0xFFFF,CartBR);

  SetWriteHandler(0x8000,0xffff,Mapper226_write);
  //MapperReset=M26Reset;
  //GameStateRestore=M26Restore;
  M26Reset();

  return 1 ;
}

