#include "clip.h"

#define Z80_CLOCK	6000000
#define PSG_CLOCK	1500000

typedef struct _DRIVER {
	Z80 z80;
	unsigned char mem[0x10000];
	//
	AY38910 psg[2];
} DRIVER;
DRIVER _driver;
DRIVER* driver = &_driver;

unsigned char
z80_read(Z80* z80, unsigned short addr)
{
	DRIVER* driver = (DRIVER*)z80;
	unsigned char* mem = driver->mem;
	return mem[addr];
}

void
z80_write(Z80* z80, unsigned short addr, unsigned char data)
{
	DRIVER* driver = (DRIVER*)z80;
	unsigned char* mem = driver->mem;
	mem[addr] = data;

	switch(addr) {
	//case 0xa080:
	case 0xa082:
	//case 0xa090:
	case 0xa092:
		if(mem[addr - 2] != 7 && data) printf("%04x: %02x, %02x\n", addr, mem[addr - 2], data);
		break;
	}
}

void
init()
{
	Z80* z80 = &driver->z80;
	unsigned char* mem = driver->mem;
	AY38910* psg1 = &driver->psg[0];
	AY38910* psg2 = &driver->psg[1];
	//
	FILE* fp;

	fp = fopen("sf_r05.bin", "rb");
	if(!fp) DIE();
	fread(&mem[0x0000], 1, 0x2000, fp);
	fclose(fp);

	/* MainCPU=>SoundCPU初期化開始指示待ち潰し。 */
	mem[0x1c3c+0] = 0x00; /* NOP */
	mem[0x1c3c+1] = 0x00; /* NOP */

	/* サムチェッカ潰し。 */
	mem[0x1c49+0] = 0xaf; /* XOR A */

	/* NMIフラグ監視ループ→HALT。 */
	mem[0x287+0] = 0x76; /* HALT */
	mem[0x287+1] = 0x00; /* NOP */

	z80_reset(z80, z80_read, z80_write, NULL, NULL);
	ay38910_reset(psg1, PSG_CLOCK, NULL, NULL);
	ay38910_reset(psg2, PSG_CLOCK, NULL, NULL);

	/* 初期化実行。(この間、NMIを発行しない) */
	z80_run(z80, Z80_CLOCK);
}


int
main(int argc, char* argv[])
{
	Z80* z80 = &driver->z80;
	unsigned char* mem = driver->mem;
	AY38910* psg1 = &driver->psg[0];
	AY38910* psg2 = &driver->psg[1];

	int i = 0;

	init();

	mem[0xc800] = 25;
	for(;;) {
		z80_run(z80, Z80_CLOCK / 180);
		z80_nmi(z80);
	}

}

