/*
 *	midread.c
 *
 *	A sample program for reading Midi sysex dumps from /dev/sequencer
 *
 *	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[4];
	int *ibuf = (int*)&buf[0];
	int i, tmp;

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

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

	for (i=1;i<argc;i++)
	{
		buf[0]=SEQ_MIDIPUTC;

		if (sscanf(argv[i], "%x", &tmp)!=1)
		{
			fprintf(stderr, "%s??\n", argv[i]);
			exit(0);
		}

		buf[1] = tmp;
		buf[2] = 0;
		buf[3] = 0;

		write(fd, buf, 4);
		fprintf(stderr, "%02x ", buf[1]);
	}
	fprintf(stderr,"\n");

/*
 *	Receive bytes
 */

	while (1)
	{
		if (read(fd, buf, 4) != 4)
		{
			perror("/dev/sequencer");
			exit(-1);
		};

		if (buf[0]==SEQ_MIDIPUTC)
		{
			write(1, &buf[1], 1);	/* Save the byte */
			if (buf[1]==0xf7) fprintf(stderr, "<eot>\n");
		}
	}

}
