/************************************************************************
 * toy.c 
 * This code was written by by Nathan Laredo (laredo@gnu.ai.mit.edu)
 * Source code may be freely distributed in unmodified form.
 *************************************************************************/
#include <stdio.h>
#include <getopt.h>
#include <fcntl.h>
#include <unistd.h>

char *midi0 = "/dev/midi00";
char *midi1 = "/dev/midi01";

int midigetch(int f)
{
    unsigned char c;
    read (f, &c, 1);
    return c;
}

void midiputch(int f, unsigned char c)
{
    write (f, &c, 1);
}

int main(argc, argv)
int argc;
char **argv;
{
    extern char *optarg;
    extern int optind;
    char *filename;
    int i, f, db = 0, transpose = 0;
    unsigned char data = 0, cmd = 0;

    filename = midi0;
    while ((i = getopt(argc, argv, "01t:")) != -1)
	switch (i) {
	case '0':
	    filename = midi0;
	    break;
	case '1':
	    filename = midi1;
	    break;
	case 't':
	    transpose = atoi(optarg);
	    break;
	default:
	    fprintf(stderr, "usage: %s [-01] [-t transpose]\n", argv[0]);
	    fprintf(stderr, "  options:\n"
		    "  -0       use /dev/midi00 (default)\n"
		    "  -1       use /dev/midi01\n");
	    exit(-1);
	    break;
	}

    if ((f = open(filename, O_RDWR, 0)) == -1) {
	perror(filename);
	exit(-1);
    }
    midiputch(f, 0xb0);
    midiputch(f, 122);
    midiputch(f, 0);
    while (1) {
	data = midigetch(f);
        if (data & 0x80)
	    cmd = data & 0xf0, db = 0;
	else if ((cmd == 0x80 || cmd == 0x90) && db == 1)
	    fprintf(stderr,"%02x", data += transpose);
	else db = 0;
	midiputch(f, data);
	db++;
    }
    close(f);
    exit(0);
}
