/*
 *	midread.c
 *
 *	A sample program for reading Midi sysex dumps from /dev/midi
 *
 *	by Hannu Savolainen
 *	hsavolai@cs.helsinki.fi
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/soundcard.h>

int fd;

main(int argc, char *argv[])
{
	unsigned char buf[100];
	int i, l, n, tmp;

	if (argc < 2)
	{ 
		fprintf(stderr, "usage: %s mididev hexval ...\n",
			argv[0]);
		exit(-1);
	}

	if ((fd=open(argv[1], O_RDWR, 0))==-1)
	{
		perror("/dev/sequencer");
		exit(-1);
	}

/*
 * Dump the cmdline arguments to the line
 */

	for (i=2;i<argc;i++)
	{
		if (sscanf(argv[i], "%x", &tmp)!=1)
		{
			fprintf(stderr, "%s??\n", argv[i]);
			exit(0);
		}
		buf[0] = (unsigned char)(tmp & 0xff);

		write(fd, buf, 1);
		fprintf(stderr, "%02x ", buf[1]);
	}
	if (argc>2) fprintf(stderr,"\n");

/*
 * 	Set the pre byte timeout.
 */

	i = 100;	/* 10 seconds */
	if (ioctl(fd, SNDCTL_MIDI_PRETIME, &i)==-1)
	{
		perror("SNDCTL_MIDI_PRETIME");
		exit(-1);
	}

/*
 *	Receive bytes. Ignore any timeouts (l=0) if no characters have
 *	been received yet (n=0). A timeout after the first received byte
 *	signals end of the dump.
 */
        n = 0;

	while ((l=read(fd, buf, sizeof(buf))) != -1 && (l>0 || n==0))
	{
		n += l;

		if (write(1, buf, l) != l)
		{
			perror("stdout");
			exit(-1);
		}
	}

	if (l == -1)
	{
		perror(argv[1]);
		exit(-1);
	};

	exit(0);
}
