#include <stdio.h>
#include "midi.h"
/* 
Copright 1988, G.E.S. Consulting

INTERRUPT MODE tutorial, RECORD and PLAY


NOTE:
struct eventlist {
	struct event *f; ptr to first event on que
	struct event *c; ptr to current event on que
	struct event *l; ptr to last event on que
	}
Library does NOT maintain  (or have knowledge of) this structure.
You are free to devise you own way to manage event lists if you wish.
*/

main(ac,av)
char **av;
	{
	char *ofile; /* output file name */
	static struct eventlist elist; /* anchor for ques */
	int x,i;
	
	if (ac > 1)
		ofile = av[1];
	else
		ofile = "events.lst";
	
	mpu_init(); /* install the driver */
	
	init_event_list(14); /* allocate 14,000 events for demo */
	
	reset_mpu(); /* get mpu401 into a known state */
	
	if ((i = get_version()) < 0) /* see if one is there */
		{
		printf("MPU401 not FOUND\n");
		exit(1);
		}
	
	all_thru_off();
	
	midi_thru(OFF); /* keep input from echoing to output
					assumes keyboard is in local mode */
	
	set_record_que(&elist.f); /* tell driver where to put stuff */
	
	printf("Press any key to start recording\n"); /* ready, set... */
	getch();
	
	record_start(); /* go */
	
	printf("Press any key to Stop Recording\n");
	printf("Events Remaining: ");
	
	while(!kbhit()) /* keep user posted as to how much room is left */
		{
		printf("%06ld\b\b\b\b\b\b",events_available());
		}
	getch(); /* all done */
	printf("\n");
	
	record_stop(); /* stop recording */
	
	do /* quick review */
		printf("Play back before saving? (y/n) ");
	while((i=(getch()&0x7f)) != 'y' && i != 'n');
	printf("\n");
	
	if (i == 'y')
		{
		printf("Playing...\n");
		set_play_que(0,elist.f); /* tell driver where track data is */
		active_tracks(TRACK_1); /* tell MPU which tracks to play */
		clear_play_counters(); /* must do to start from beginning of track */
		play_start(); /* go */
		while(!que_done()) /* could be doing something else here */
			;
		}

	/* save it away for another day */
	
	printf("Saving Recording in file: %s\n",ofile);
	save_list(&elist,ofile);
	mpu_close();
	}

/* simple  disk storage routine */
save_list(struct eventlist *p, char *n)
	{
	int f = creat(n,0666);
	struct event *ep = p->f,*oldep;
	
	/* walk the list, writing stuff out along the way */
	while(ep)
		{
		write(f,&ep->tbyte,sizeof (ep->tbyte));
		write(f,&ep->status,sizeof (ep->status));
		write(f,&ep->dlen,sizeof(ep->dlen));
		if (ep->dlen)
			{
			write(f,ep->d.data,ep->dlen);
			}
		oldep = ep;
		ep = ep->n;
		}
	close(f);
	}
