#include <stdio.h>

/* Color : 30(black) 31(red) 32(green) 33(yellow) 34(blue) 35(purple)
	   36(skyblue) 37(white) , Reverse-->[+10](40-47) , default = 0 */

char ss[16],es[4],s[16];

main(){
	int d,kn=0;
	long i,ii,jj,kk=0L;

	port_init();

	es[0]=0x1b; es[1]='['; es[2]=0;
	strcpy(ss,es); strcat(ss,"2J"); printf("%s",ss);	/* CLS */

	position(1,20);
	color(31);
	color(46);
	printf("Hello World\n\n\n");
	color(0);

	aki80_reset();

	while(1){
		d=csts();
		if(d==0x1b) break;
		else if(d=='r') aki80_reset();
		d=midi_rx();
		if(d>=0){
			printf(" %02x ",d);
			midi_tx(d);
		}
	}
}

midi_rx(){
	long ii,jj=0L;
	int dd;
	if((_inb(0x379)&0x20)!=0) return(-1);
	_outb(0x20,0x37a);	/* Input, [RD] = Low */
	dd=_inb(0x378);
	_outb(0x05,0x37a);	/* Strobe */
	_outb(0x04,0x37a);	/* Default */
	return(dd);
}

midi_tx(data)
	int data;
{
	while(1){
		if((_inb(0x379)&0x10)==0){
			_outb((data&0xff),0x378);
			_outb(0x0c,0x37a);	/* [WR] = Low */
			_outb(0x04,0x37a);	/* [WR] = High */
			return;
		}
	}
}

aki80_reset(){
	long ii,jj=0L;
	_outb(0x06,0x37a);	/* [WR] = [RD] = High , [RES] = Low */
	for(ii=0;ii<50000;ii++){jj++;}
	_outb(0x04,0x37a);	/* [WR] = [RD] = [RES] = High */
}

port_init(){
	_outb(0x04,0x37a);	/* [WR] = [RD] = [RES] = High */
}

color(x) int x; {
	if(x==0){ strcpy(ss,es); strcat(ss,"0m"); printf("%s",ss); x=37; }
	strcpy(ss,es); sprintf(s,"%d",x); strcat(ss,s); strcat(ss,"m");
	printf("%s",ss);
}

position(y,x) int y; int x; {
	strcpy(ss,es); 	sprintf(s,"%d",y); strcat(ss,s); strcat(ss,";");
	sprintf(s,"%d",x); strcat(ss,s); strcat(ss,"H"); printf("%s",ss);
}

