/* for simulation */
/* #define THRSim11 */

typedef unsigned char byte;

volatile byte index=4;	

void rtti_isr(void) __attribute__((interrupt));

void rtti_isr(void) {
	static byte count=0;
	volatile byte* porta=(byte*)0x1000;
	volatile byte* tflg2=(byte*)0x1025;
	static byte olda0=1;
	static byte olda1=1;
	if (count==24) {
		count=0;
		*porta^=0x20;
		if (olda0!=(*porta&0x01)) {
			olda0=*porta&0x01;
			if (olda0==0 && index>0) 
				/* key a0 pressed = Down */
				--index;
		}
		if (olda1!=(*porta&0x02)) {
			olda1=*porta&0x02;
			if (olda1==0 && index<9) 
				/* key a1 pressed = Up */
				++index;
		}
		
	}
	else
		++count;
	*tflg2=0x40;
}

typedef void (*isr)(void);

int main() {
	volatile byte*  tmsk2 =(volatile byte*) 0x1024;
	volatile byte*  oc1m  =(volatile byte*) 0x100c;
	volatile byte*  oc1d  =(volatile byte*) 0x100d;
	volatile byte*  tctl1 =(volatile byte*) 0x1020;
	volatile byte*  tflg1 =(volatile byte*) 0x1023;
	volatile unsigned short* toc1  =(volatile unsigned short*)0x1016;
	volatile unsigned short* toc2  =(volatile unsigned short*)0x1018;
	/* set vector for Simplex board */
	volatile byte* rtti_ram_vector_jmp=(byte*)0x00eb;
	volatile isr* rtti_ram_vector_addr=(isr*)0x00ec;

	const unsigned short values[10]={
		0x07ff, 0x07c0, 0x0780, 0x0700, 0x0680,
		0x0600, 0x0540, 0x0400, 0x0200, 0x0000
	};
	*rtti_ram_vector_jmp=0x7e;
	*rtti_ram_vector_addr=rtti_isr;
	*tmsk2=0x40;
	*toc2=0x0800;
	*toc1=0x0800+values[index];
	*tctl1=0xc0;
	*oc1m=0x40;
	*oc1d=0x00;
	*tflg1=0xc0;
	while (1) {
		while ((*tflg1&0x40)!=0x40);
		*toc2+=0x0800;
		*tflg1=0x40;
		while ((*tflg1&0x80)!=0x80);
		*toc1=*toc2+values[index];
		*tflg1=0x80;
	}
	return 0;		
}

#ifdef THRSim11
#ifdef __cplusplus
extern "C" void _start(void);
#else
extern void _start(void);
#endif

isr vectors[32] __attribute__ ((section (".vectors"))) = {
	0, 0, 0, 0,
	0, 0, 0, 0,
	0, 0, 0, (isr)0x00c4,
	(isr)0x00c7, (isr)0x00ca, (isr)0x00cd, (isr)0x00d0, 
	(isr)0x00d3, (isr)0x00d6, (isr)0x00d9, (isr)0x00dc,
	(isr)0x00df, (isr)0x00e2, (isr)0x00e5, (isr)0x00e8,
	(isr)0x00eb, (isr)0x00ee, (isr)0x00f1, (isr)0x00f4,
	(isr)0x00f7, (isr)0x00fa, (isr)0x00fd, _start
};
#endif

