/* simplified transmit sys/ex file */
/*    actually transmits entire contents of file, not just sys/ex */

/*
    describes usage of PutMidiStream() limited buffer size and unknown
    stream length.
*/

#include <midi/midi.h>
#include <functions.h>
#include <fcntl.h>

void *MidiBase;

static int fi;			    /* input file descriptor */
UBYTE buf[512]; 		    /* buffer used for transfer */

main(argc,argv)
char **argv;
{
    struct MSource *source=0;
    struct MRoute *route=0;
    static struct MRouteInfo routeinfo = { -1, -1 };	/* support all msg's */
    extern short Enable_Abort;
    char *fname;
    long fillbuffer();

    printf ("Transmit Sys/Ex\n");
    Enable_Abort = 0;			/* disable auto CTRL-C handling */

    if (argc < 2) {
	printf ("usage: tsx <file>\n");
	exit (1);
    }

    fname = argv[1];			/* get file name */

    if (!(MidiBase = OpenLibrary (MIDINAME,MIDIVERSION))) {
	printf ("can't open midi.library\n");
	goto clean;
    }
					/* create our source node (private) */
    if (!(source = CreateMSource (NULL,NULL))) {
	printf ("can't create Source\n");
	goto clean;
    }
					/* create our route to MidiOut */
    if (!(route = MRouteSource (source,"MidiOut",&routeinfo))) {
	printf ("can't create Route (can't find MidiOut?)\n");
	goto clean;
    }
					/* open input file */
    if ( (fi=open(fname,O_RDONLY)) == -1) {
	printf ("can't open %s\n",fname);
	goto clean;
    }
					/* convert file to midi messages */
    PutMidiStream (source,fillbuffer,buf,(long)sizeof buf,0L);

clean:
    if (route) DeleteMRoute (route);
    if (source) DeleteMSource (source);
    if (MidiBase) CloseLibrary (MidiBase);
}



/* fill our buffer with data from the file, called by PutMidiStream() */

static
long fillbuffer()
{
    register long len;

    geta4();			    /* Aztec small data model */
    return (len = read(fi,buf,sizeof buf)) == -1 ? 0 : len;
}
