/*
 *  pocket - SHARP PC-1450エミュレータ
 *
 *  Copyright (C) 1994, 1995 by Dai Ishijima
 */

#include <stdio.h>
#include "pocket.h"

#define NOAUTOPOWOFF
#define KBDEOF '\004'

#define COREFILE "pc1450.bin"
#define CORESIZE 65536

/*extern unsigned char *mainram;*/
unsigned char mainram[CORESIZE];

main()
{
    FILE *fp;
    int x, y, ch, k;
    int lastdisp;
    
    if ((fp = fopen(COREFILE, "r")) == NULL) {
	fprintf(stderr, "%s: can't open\n", COREFILE);
	exit(1);
    }
    if (fread(mainram, 1, CORESIZE, fp) < CORESIZE) {
	fprintf(stderr, "%s: read failed\n", COREFILE);
	exit(1);
    }
    fclose(fp);
    for (x = 0x2000; x < 0x8000; x++) {
	mainram[x] = 0;
    }
    lcdinit();
    keyinit();
    initsc();
    clearall();
    displayall();
    scstatus();
    showkeytab();
    x = k = 0;
    lastdisp = disp_on;
    ch = -1;
    ttraw();
#ifdef LOGFILE
    fp = fopen("logfile", "w");
#endif    
    while (1) {
	y = interpret();
#ifdef LOGFILE
	fprintf(fp, "%04x\n", y);
#endif	
#if 0
	++k;
	if ((k > 100) && ((ch = getkey()) > 0)) {
	    k = 0;
	    keyscan(ch);
	}
	else if (k > 1000) {
	    keyscan(0);
	    k = 0;
	}
	if (ch == 4) {
	    break;
	}
#endif
	if (disp_on && !lastdisp) {
	    x = 0;
	}
	lastdisp = disp_on;
	if (--x <= 0) {
	    displayall();
	    scstatus();
	    if (disp_on) {
		x = 40000;
	    }
	    else {
		busy();
		x = 150000;
	    }
	    fflush(stdout);
	}
#ifndef NOAUTOPOWOFF
	if (!power_on) {
	    printf("Power off\r\n");
	    break;
	}
#endif
	if (!power_on) {
	    ungetc(getchar(), stdin);
	}
	if (kbdpowoff) {
	    printf("Power off\r\n");
	    break;
	}
    }
    closesc();
#ifdef LOGFILE
    fclose(fp);
#endif	
    ttcooked();
    exit(0);
}
