#include <stdio.h>
#include <unistd.h>
/* Alpha: #include <getopt.h> */
#include "manager.h"
#include "text.h"
#include "6502P.h"
#include "dis6502.h"
#include "6522.h"

#define pushb(val) writebq(SP + 0x100, val); SP--
#define pullb()    (SP++, readbq(SP + 0x100))

#define pushw(val) pushb((val) / 0x100); pushb((val) & 0xff)

int debug = 0;
int do_irq = 0;

int main(int argc, char **argv) {
    extern char *optarg;
    time_t time = 0;
    int i, c;

    while (-1 != (c = getopt(argc, argv, "dD:"))) {
	switch (c) {
	case 'd':
	    debug = 1;
	    break;
	case 'D':
	    chdir(optarg);
	    break;
	case '?':
	case 'h':
	    puts("beeb [-d] [-D directory]");
	    return 1;
	}
    }

    /* initialise our modules */
    for (i = 0; i < N_MODULES; i++) {
	module[i]->init();
    }
    init_screen();

    for (;;) {
#ifdef DEBUG
	if (debug) {
	    printf("%04x: %02x %02x %02x, A=%02x, X=%02x, Y=%02x, S=%02x,"
		   " P=%02x ; ", PC, readbq(PC),
		   readbq(PC+1), readbq(PC+2),
		   A, X, Y, SP, P);
	    disassemble(readbq(PC));
	}
#endif
	opcode[readbq(PC)]();
#if defined(USER_VIA) || defined(SYSTEM_VIA)
	if (do_irq) {
	    clr_B();
	    /*
	    printf("Interrupt generated at &%X, P=&%X\n", PC, P);
	    debug=1;
	    */
	    
	    pushw(PC);
	    pushb(P);
	    PC = readwq(0xFFFE);
	    do_irq = 0;
	}
#endif
    }

    return 0;
}
