/***************************************
 MMC5 Mapper5
***************************************/
function cpu_dump(d, prg_size, banksize)
{
	local i;
	cpu_write(d, 0x5100, 0);
	for(i = 0x80; i < ((prg_size/0x2000) | 0x80) - 2; i += 2){
		cpu_write(d, 0x5114, i);
		cpu_write(d, 0x5115, i | 1);
		cpu_read(d, 0x8000, 0x2000 * 2);
	}
	cpu_write(d, 0x5116, i);
	cpu_write(d, 0x5117, 0xff);
	cpu_read(d, 0xc000, 0x2000 * 2);
}
function ppu_dump(d, chr_size, banksize)
{
	local i;
	cpu_write(d, 0x5101, 2);
	cpu_write(d, 0x5130, 0);
	for(i = 0; (i < (chr_size/0x800)) && (i < 0x100); i += 4){
		cpu_write(d, 0x5121, i);
		cpu_write(d, 0x5123, i | 1);
		cpu_write(d, 0x5125, i | 2);
		cpu_write(d, 0x5127, i | 3);
		ppu_read(d, 0x0000, 0x800 * 4);
	}
	cpu_write(d, 0x5130, 0x03);
	for(; i < (chr_size/0x800); i += 4){
		local j = i & ff;
		cpu_write(d, 0x5121, j);
		cpu_write(d, 0x5123, j | 1);
		cpu_write(d, 0x5125, j | 2);
		cpu_write(d, 0x5127, j | 3);
		ppu_read(d, 0x0000, 0x800 * 4);
	}
}
function cpu_erase(d, prg_size, prg_size_dummy)
{	
	cpu_write(d, 0x5100, 3);
	cpu_write(d, 0x5113, 0);
	cpu_write(d, 0x5114, 0x80);
	cpu_write(d, 0x5115, 0x81);
	cpu_write(d, 0x5116, 0x82);
	
	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)
{
	flash_configure(d,0xAAAA,0xD555,0xAAAA,0xD555);
	for(local i = 0; i < prg_size/0x2000 - 1; i += 1){
		cpu_write(d, 0x5114, 0x80 | i);
		prg_flash(d, 0x8000, 0x2000);
	}
	//$e000- は書き込みが安定しないので末尾 page として $7f を指定する。
	cpu_write(d, 0x5114, 0x80  | 0x7f);
	prg_flash(d, 0x8000, 0x2000);
}

function ppu_erase(d, chr_size, chr_size_dummy)
{
	cpu_write(d, 0x5101, 2);
	cpu_write(d, 0x5121, 5);
	cpu_write(d, 0x5123, 0xa);
	cpu_write(d, 0x5125, 0);
	
	cpu_write(d, 0x5104, 3);
	cpu_write(d, 0x5105, 0);
	
	//ppu_command(d, 0x0000, 0x1000, ppu_banksize);
	//ppu_command(d, 0x2aaa, 0x0000, ppu_banksize);
	//ppu_command(d, 0x5555, 0x0800, ppu_banksize);
	
	ppu_write(d,0xD55,0xF0);
	ppu_write(d,0xD55,0xAA);
	ppu_write(d,0x2AA,0x55);
	ppu_write(d,0xD55,0x80);
	ppu_write(d,0xD55,0xAA);
	ppu_write(d,0x2AA,0x55);
	ppu_write(d,0xD55,0x10);
}
function ppu_flash(d, chr_size, chr_size_dummy)
{
	flash_configure(d,0xD55,0xD55,0x2AA,0xD55);

	local i;
	cpu_write(d, 0x5130, 0);
	for(i = 0; (i < chr_size/0x800) && (i < 0x100); i += 2){
		cpu_write(d, 0x5125, i);
		cpu_write(d, 0x5127, i | 1);
		chr_flash(d, 0x1000, 0x800 * 2);
	}
	cpu_write(d, 0x5130, 0x03);
	for(; i < chr_size/0x800; i += 2){
		cpu_write(d, 0x5125, (i & 0xff));
		cpu_write(d, 0x5127, (i & 0xff) | 1);
		chr_flash(d, 0x1000, 0x800 * 2);
	}
}
