#include <midi.h>
#include <ctype.h>
#define e MidiError
Error(s) { e("%s: ", av0); perror(s); exit(1); }

use(){
  e("Use: %s [-c channel] [[+-]button] ...\n",av0);
  e("  button   push button (down, up) #\n");
  e("  +button  press button down\n");
  e("  -button  let button up\n");
  e("Buttons are:\n");
  e("  1-32   voice buttons,\n");
  e("  33-36  Store, MPint, MPcart, OpSelect\n");
  e("  37-40  Edit, MSint, MScart, Function\n");
  e("  41     no\n");
  e("  42     yes\n");
  e("Letter names ('store', 'edit', etc) can be used instead of numbers.\n");
  e("Example: to turn MEM PROTECT INTERNAL OFF, do:\n");
  e("  %s +MPint off -MPint MSint\n",av0);
  exit(1);
}

check(n){
	if (n<0 || n>41) e("warning: button %d is dubious...\n", n+1);
	return n;
}

button(s) char *s; {
	int i;
	if (!s || !*s)
		e("%s: huh? null button??\n"), use();
	i = dx7buttoi(s);
	if (i== -1) e("%s: huh? what button is '%s'\n",s), use();
	return i;
}

#define arg *s? s : (++i<ac)? (s=av[i]) : (char *)0

main(ac, av) char **av; {
	int i, midi, channel = 0;
	char *s;

	av0 = av[0];
	if ((midi = open(MidiDevice, 2)) == -1) Error(MidiDevice);
	MpuSend(midi, MPU_RESET, 0);

	for (i=1;i<ac;i++) switch (*(s=av[i])){
	Case '-': ++s;
		  if (*s == 'c'){
		      ++s; channel = atoi(arg)-1;
		      if (channel < 0 || channel > 15)
				e("%s: bad channel number; using ch. 1\n"),
				channel = 0;
		  } else dx7Button(midi,channel,button(s),0);
	Case '+': dx7Button(midi,channel,button(s+1),1);
	Default : dx7Push(midi,channel,button(s));
	}

	if (ac==1) use();
	exit(0);
}
