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

INTERRUPT MODE tutorial:   PLAY and do something useful while driver
	does it's thing


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;
	{
	mpu_init(0); /* install driver */
	
	init_event_list(14); /* allocate 14,000 events for demo */
	
	if (reset_mpu() < 0) /* no MPU installed */
		exit(1 );
	
	while(*(++av)) /* while there are files */
		{
		printf("%s...\n",*av);
		play(*av); /* play em */
		}
	mpu_close();
	}
play(char *s)
	{
	char c,r=0;
	char stopped = 0;
	struct event *op,*ip,*read_event();
	struct eventlist elist;
	
	if (read_list(&elist,s) == 0) /* load events from disk */
		{
		 set_play_que(0,elist.f); /* tell driver where track data is */
		 active_tracks(TRACK_1); /* tell MPU what to play */
		 clear_play_counters(); /* start from beginning of track */
		 printf("Press a key if you want to do something else while listening...\n");
		 play_start(); /* go */
		 while(!que_done()) /* test for end of track */
		 	if (kbhit()) /* if user wants to do something else */
				{
				getch(); /* give em a shell */
				printf("Type EXIT to return to program\n");
				system("command");
				printf("You are Back in PLAY\n");
				}
		
		printf("Track has finished\n"); /* all done */
		 
		 /* free up events for next song */
		 
		 op = elist.f;
		 while(op)
		 	{
			struct event *t = op->n;
			event_free(op);
			op = t;
			}
		 }
	}

/* simple disk storage routines */

read_list(struct eventlist *p,char *n) /* initialize a list from disk */
	{
	FILE *f;
	struct event *ep;
	struct event *read_event();

	printf("loading song %s\n",n);
	
	/* dont assume anything */
	p->f = p->c = p->l = (struct event *)0;
	
	if ((f = fopen(n,"rb")) == (FILE *)0)
		return(-1);
	
	while((ep=read_event(f))) /* while there are more */
		{
		if (p->f) /* first one */
			{
			p->l->n = ep;
			p->l = ep;
			}
		else
			p->f = p->c = p->l = ep; /* string em up */
		};
	fclose(f);
	printf("song loaded\n");
	return(0);
	}

struct event *read_event(FILE *fp) /* read one event from disk */
	{
	struct event *ep = event_alloc(); /* get a place to store data */
	
	if (fread(&ep->tbyte,sizeof(ep->tbyte),1,fp) == 0) /* EOF */
		{
		event_free(ep);
		return((struct event *)0);
		}
	
	fread(&ep->status,1,sizeof(ep->status),fp);
	fread(&ep->dlen,1,sizeof(ep->dlen),fp);
	
	if (ep->dlen)
		{
		fread(ep->d.data,1,ep->dlen,fp);
		}
	return(ep);
	}
