/* dx7tune [-c channel] [value]
** set dx7 master tune to 'value'.
** if no 'value' given, read from stdin.
*/
#include <stdio.h>
#include <midi.h>
#include <ctype.h>

#d e MidiError
#d Dchannel 0
int channel = Dchannel;

use(){
  e("Use: %s [-c channel] [value]\n",av0);
  e("Set master tune on dx7 to 'value'.\n");
  e("If no 'value', read from stdin.\n");
  exit(1);
}

#d SetTune(v) dx7PutControl(midi,channel,DX7_CTL_DE_KNOB,v)

main(ac,av) char *av[]; {
	int i, midi = open(MidiDevice,2);

	for_each_argument {
	Case 'c': if (!inrange(0,channel=atoi(argument)-1,15)) use();
	Default : use();
	}

	if (midi == -1) e("%s: ",av0), perror(MidiDevice), exit(1);
	MpuSend(midi,MPU_RESET,0);
	dx7SysInfoAvail(midi,channel,1);

	dx7Push(midi,channel,DX7function);	/* FUNC... */
	dx7Push(midi,channel,0);		/* ... MASTER TUNE ADJ */
	dx7MemSelect(midi,channel,0);	 /* ... back to internal select */
					 /* (in case user hits voice) */

	if (i<ac) SetTune(atoi(av[i]));
	else {
		char s[100];
		int Value = 50,inc=10;

#d a440 ptoi("a4")

		NoteOn(midi,channel,a440,127);

		while (fgets(s,sizeof s,stdin) && *s != 'q'){
			switch (*s){
			Case '+': Value += (inc = *(s+1)? atoi(s+1) : 10);
			Case '-': Value += (inc = *(s+1)? -atoi(s+1) : -10);
			Case '.': Value += inc;
			Default : if (isdigit(*s)) Value = atoi(s);
			}
			if (Value < 0) Value = 0;
			if (Value > 127) Value = 127;
			SetTune(Value);
		}
		NoteOff(midi,channel,a440);
	}

	dx7SysInfoAvail(midi,channel,1); /* to get out of master tune mode */
	dx7MemSelect(midi,channel,0);	 /* ... back to internal select */

	exit(0);
}
