/************************************************************************
 * resetmidi.c 
 * Really-really-really resets a midi synth (with some useless effects)
 *
 * 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>

#define BUFSIZE 128
char *midi0 = "/dev/midi00";
char *midi1 = "/dev/midi01";
int f, offset = 0;
unsigned char buf[BUFSIZE];

void dump()
{
    if (offset)
	if (write(f, buf, offset) < offset) {
	    perror("write");
	    exit(-1);
	}
    offset = 0;
}

void midich(c)
unsigned char c;
{
    buf[offset++] = c;
    if (offset >= BUFSIZE)
	dump();
}

int main(argc, argv)
int argc;
char **argv;
{
    extern char *optarg;
    extern int optind;
    char *filename;
    int i, j;

    filename = midi0;
    while ((i = getopt(argc, argv, "01")) != -1)
	switch (i) {
	case '0':
	    filename = midi0;
	    break;
	case '1':
	    filename = midi1;
	    break;
	default:
	    fprintf(stderr, "usage: %s [-01]\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_WRONLY, 0)) == -1) {
	perror(filename);
	exit(-1);
    }
    for (i = 0; i < 16; i++) {
	midich(0xfe); midich(0xb0 + i); midich(0x40); midich(0);
	midich(0x7d); midich(0); midich(0x7f); midich(0);
	midich(0xc0 + i); midich(0); midich(0x90 + i);
	/* bunch of note on/off for effect (useless)*/
	for (j = 24; j < 108; j++) {
	    midich(0x90 + i);
	    midich(j);
	    midich(64);
	    midich(0x80 + i);
	    midich(j);
	    midich(64);
	}
    }
    dump();
    close(f);
    exit(0);
}
