/* simplified Hex Transmit to midi */
/*
    Shows usage of PutMidiStream() when buffer size is known and of managable
    size.
*/


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

void *MidiBase;

main (argc,argv)
char **argv;
{
    struct MSource *source=0;
    struct MRoute *route=0;
    static struct MRouteInfo routeinfo = { -1, -1 };	/* route spec's: transmit all */
    char buf[128];		/* buffer used for midi transfer */
    long len;
    extern int Enable_Abort;

    Enable_Abort = 0;		/* disable auto CTRL-C termination */

    if (argc < 2) {
	printf ("MIDI Hex Transmit\n");
	printf ("usage: ht <hex byte>...\n");
	exit (1);
    }

    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 out Route to MidiOut */
    if (!(route = MRouteSource (source,"MidiOut",&routeinfo))) {
	printf ("can't create Route (can't find MidiOut?)\n");
	goto clean;
    }
				/* parse the command line for hex bytes, make into an array */
    len = makestream (buf,argc-1,argv+1);
				/* convert array to midi messages and send */
    PutMidiStream (source,NULL,buf,len,len);

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

makestream (buf,argc,argv)	/* convert args into an array of bytes, return length */
char *buf;
char **argv;
{
    int len=0;

    while (argc--) {
	*buf++ = atox(*argv++);
	len++;
    }
    return len;
}


atox(cp)			/* like atoi() but read string as hex rather than decimal */
char *cp;
{
    int x;

    sscanf (cp,"%x",&x);
    return x;
}
