/***************************************
  MMC1
***************************************/
function mmc1_write(d, addr, data)
{
	cpu_write(d, addr, data>>0,addr, data>>1,addr, data>>2,addr, data>>3,addr, data>>4);

}
function cpu_dump(d, prg_size, banksize)
{
	cpu_write(d, 0x8000, 0x80); //serial count reset
	mmc1_write(d, 0x8000, 0x0c);
	if(prg_size>0x40000)//512k?
	for(local i = 0; i < prg_size/0x4000; i += 0x10){
		mmc1_write(d, 0xa000, (i & 0x10) | 1);
		for(local j = 0; j < 0x10 - 1; j += 1){
			mmc1_write(d, 0xe000, j | 0x10);
			cpu_read(d, 0x8000, 0x4000);
		}
		cpu_read(d, 0xc000, 0x4000);
	}
	else
	for(local i = 0; i < (prg_size/0x4000)- 1; i += 1){
		mmc1_write(d, 0xe000, i | 0x10);
		cpu_read(d, 0x8000,0x4000);
	}
	cpu_read(d, 0xc000,0x4000);
}
function ppu_dump(d, chr_size, banksize)
{
	for(local i = 0; i <  chr_size/0x1000; i += 2){
		mmc1_write(d, 0xa000, i);
		mmc1_write(d, 0xc000, i | 1);
		ppu_read(d, 0,0x1000* 2);
	}
}

function cpu_erase(d, prg_size, prg_size_dummy)
{
	cpu_write(d, 0x8000, 0x80);
	mmc1_write(d, 0xa000, 0x10); //SNROM + MMC1A disable W-RAM
	mmc1_write(d, 0x8000, 0x1c);
	mmc1_write(d, 0xe000, 0x10); //MMC1B disable W-RAM
	//29F
	/*
	*/
	//39SF0X0
	cpu_write_flash(d,0xD555,0xF0);
	cpu_write_flash(d,0xD555,0xAA);
	cpu_write_flash(d,0xAAAA,0x55);
	cpu_write_flash(d,0xD555,0x80);
	cpu_write_flash(d,0xD555,0xAA);
	cpu_write_flash(d,0xAAAA,0x55);
	cpu_write_flash(d,0xD555,0x10);
}
function cpu_flash(d, prg_size, prg_size_dummy)
{
	local i = 0;
	local wram = 1 << 4; //W-RAM disable flag
	flash_configure(d,0xAAAA,0xD555,0xAAAA,0xD555);//39SF
	//flash_configure(d,0x8000,0x8555,0x82AA,0x8555);//29F
	for(i = 0; i < (prg_size/0x4000) - 2; i += 2){
		mmc1_write(d, 0x8000, 0x1c);
		mmc1_write(d, 0xe000, i | 0 | wram);
		prg_flash(d, 0x8000, 0x4000);
		
		mmc1_write(d, 0x8000, 0x18);
		mmc1_write(d, 0xe000, i | 1 | wram);
		prg_flash(d, 0xc000, 0x4000);
	}
	mmc1_write(d, 0x8000, 0x1c);
	mmc1_write(d, 0xe000, i | wram);
	prg_flash(d, 0x8000, 0x4000);
	prg_flash(d, 0xc000, 0x4000);
}

function ppu_erase(d, chr_size, chr_size_dummy)
{
	
	cpu_write(d, 0x8000, 0x80);
	mmc1_write(d, 0xa000, 0x10); //SNROM + MMC1A disable W-RAM
	mmc1_write(d, 0x8000, 0x1c);
	mmc1_write(d, 0xe000, 0x10); //MMC1B disable W-RAM
	
	ppu_write(d,0x000,0xF0);
	ppu_write(d,0x555,0xAA);
	ppu_write(d,0x2AA,0x55);
	ppu_write(d,0x555,0x80);
	ppu_write(d,0x555,0xAA);
	ppu_write(d,0x2AA,0x55);
	ppu_write(d,0x555,0x10);
}
function ppu_flash(d, chr_size, chr_size_dummy)
{
	flash_configure(d,0x555,0x555,0x2AA,0x555);
	
	for(local i = 0; i < (chr_size/0x1000); i+=2){
		mmc1_write(d, 0xa000, i)
		mmc1_write(d, 0xc000, i | 1);
		chr_flash(d, 0x0000, 0x1000 * 2);
	}
}

function ram_dump(d, prg_size, banksize)
{
	//cpu_write
	//ram_read_write
	mmc1_write(d, 0x8000, 1 << 3);
	mmc1_write(d, 0xe000, 0);
	mmc1_write(d, 0xa000, 0);
	for(local i = 0; i < 0x2000; i += 0x400)
	ram_read_write(d, 0x6000+i, 0x400);
	mmc1_write(d, 0xe000, 0xff);
}