/* 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 INLINE void M49PRG(void)
{
   if(mapbyte4[1]&1)
   {
    int t;
    t=mapbyte4[1]&0xC0;
    t>>=2;
    if (MMC3_cmd&0x40) 
		       {ROM_BANK8(0x8000,(0xFE)+t);
			ROM_BANK8(0xC000,(mapbyte3[6]&0xF)+t);}
                       else 
	 {
         ROM_BANK8(0xC000,(0xE)+t);
	 ROM_BANK8(0xe000,(0xF)+t);
         ROM_BANK8(0x8000,(mapbyte3[6]&0xF)+t);
    	}
    ROM_BANK8(0xA000,(mapbyte3[7]&0xF)+t);
   }
  else
   ROM_BANK32((mapbyte4[1]>>4)&7);
}
static INLINE void M49CHR(void)
{
   int t;
   int cbase=((MMC3_cmd^0x80)&0x80)<<5;   
   t=mapbyte4[1]&0xC0;
   t<<=1;  
   VROM_BANK2((cbase^0x1000),(mapbyte3[0]+t)>>1);
   VROM_BANK2((cbase^0x1800),(mapbyte3[1]+t)>>1);
   VROM_BANK1(cbase^0x000,mapbyte3[2]+t); 
   VROM_BANK1(cbase^0x400,mapbyte3[3]+t); 
   VROM_BANK1(cbase^0x800,mapbyte3[4]+t); 
   VROM_BANK1(cbase^0xC00,mapbyte3[5]+t);
}

DECLFW(Mapper49_write)
{
        switch(A&0xE001){
        case 0x8000:
        {
         int t=MMC3_cmd;
         MMC3_cmd = V;

          if((V&0x40) != (t&0x40))
           M49PRG();

         if(VROM_size)
         {         
          if((V&0x80) != (t&0x80))
            M49CHR();
         }
         
        }
        break;

        case 0x8001:
                switch(MMC3_cmd&0x07)
		{
		default: mapbyte3[MMC3_cmd&0x7]=V;M49CHR();break;
		case 6: case 7: mapbyte3[MMC3_cmd&0x7]=V;M49PRG();break;
                }
                break;

        case 0xA000:
        MIRROR_SET(V&1);
        break;
        case 0xA001:
		    mapbyte4[0]=V&0x80;
                    break;
	#include "mmc3irq.h"
 }
}
DECLFW(M49low)
{
 if(mapbyte4[0]&0x80)
 {
  mapbyte4[1]=V;
  M49PRG();
  M49CHR();
 }
}
void Mapper49_init(void)
{
 mapbyte3[7]=1;
 M49PRG();
 M49CHR();
 SetWriteHandler(0x6000,0x7FFF,M49low);
 SetWriteHandler(0x8000,0xFFFF,Mapper49_write);
 GameHBIRQHook=MMC3_hb;
}
