#include <stdio.h>
#include <mpuvar.h>
#include <midi.h>

char	*Midi_dev	= MPU_DEV_0;	/* default mpu */

#define error return perror(Midi_dev),0

/*
** Initialize midi device for playing on some number of tracks.
** If 'file' is given, it contains ascii initialization commands
** which are written to the device.
** Otherwise a default sequence is sent (set track 0, clear play, 'mode').
** The open midi file descriptor is returned,
** or 0 if there was an error.
** 'numtracks' tells how many of the 8 available midi tracks
** will be used.
** 'mode' is one of: 'MPU_START_PLAY', 'MPU_START_RECORD',
** or 'MPU_START_OVERDUB'.
** `Bugs:` the initialization of multiplay tracks is not yet
** known to be robust... Also, note that 'MidiPlayInit' does
** an 'MPU_START_mode', so don't wait too long before transmitting
** play buffers.
*/
MidiPlayInit(file, numtracks, mode)
char	*file;
{
	int f = open(Midi_dev,2);
	register i, tracks=0;
	if (f == -1) error;

	if (numtracks == 0) numtracks = 1;
	for (i=0; i<numtracks; i++) {
	   /* send bogus play buffer to initialize */
	   char s[3]; int n=3, x;
	   s[0] = 68, s[1] = 0xc0+i, s[2] = -1;
	   tracks |= (1<<i);
	   if (MpuSetTrack(f,i) == -1 || write(f,s,n)!=n) error;
	}
	/* send initialization sequence */
	if (file) {
		int d;
		FILE *f = fopen(file,"r");
		if (!f) Error(file);
		while (fscanf(f,"%x",&d) == 1) MpuSet(d);
		fclose(f);
	} else	/* default initialization sequence */
		MpuSet(MPU_ACTIVE_TRACKS), MpuSet(tracks),
		MpuSet(MPU_CLEAR_PLAY_COUNTERS),
		MpuSet(MPU_BENDER_ON),
		MpuSet(mode==0? MPU_START_PLAY : mode);

	if (MpuSetTrack(f,MPU_TR_COM) == -1 || 
	    MpuFlush(f) ||
	    MpuSetTrack(f,0) == -1) error;
	return f;
}
