#include <midi.h>
#include <dx7voice.h>
#include <ctype.h>

#d e MidiError
Error(s) { e("%s: ", av0); perror(s); }

#d Dchannel 0
int channel = Dchannel;	/* which channel to write to */

use(){
	e("Use: %s [-c channel] [-s] [-S] file [position]...\n",av0);
	e("   -c #  use channel # (1-16, default %d)\n", Dchannel+1);
	e("   -s    store voices in internal memory\n");
	e("   -S    store voices in cartridge memory\n");
	e("'file' is a dx7 voice file.\n");
	e("Example:\n");
	e("   %s -s flute 1 piccolo 2\n",av0);
	e("stores the flute in internal voice 1 and piccolo in voice 2\n");
	exit(1);
}

/*
** vput [-c channel] [-s] [-S] voice [where]
** load the midi voice from file 'voice' into the current voice program
** (or program #'where', from 1-32) on the dx7.
*/
main(ac, av) char **av; {
	int i,midi, n=0, mem=0 /* 0 for internal, 1 for cartridge */;
	int store = 0;  /* if true, save voice in whichever 'mem' */
	Dx7Voice *dx7ReadVoice(), *v;
	char *VoiceFile();

	for_each_argument {
	Case 'c': if (!inrange(0, channel = atoi(argument)-1, 15)) use();
	Case 's': store = 1;	   /* save voice in dx7 internal mem */
	Case 'S': store = mem = 1; /* save voice in dx7 cartridge mem */
	Default : use();
	}

	if (i==ac) use();

		/* get the dx7 ready: make SYS INFO AVAIL, MEM PROTECT OFF,
		 * and leave it ready to receive voice button pushes.
		 */
	if ((midi = open(MidiDevice, 2)) == -1) Error(MidiDevice), exit(1);
	MpuSend(midi, MPU_RESET, 0);
	dx7SysInfoAvail(midi,channel,1);
	dx7MemProtect(midi,channel,0,mem);
	dx7Push(midi,channel,DX7mem_select_internal+mem);

	while (i<ac){
		char *s = VoiceFile(av[i++]);
		int position = (i<ac && isdigit(*av[i]))? atoi(av[i++])-1 : -1;
		if (!s) { Error(s); continue; }
		e("%s => %d...",s,position+1);
		v = dx7ReadVoice(s);
		if (!v) { Error(s); continue; }
		if (position == -1 && n++ > 1)
			e("(warning -- overwriting current position)");
		dx7PutVoice(midi,channel,v,position);
		if (position != -1 && store)
			dx7StoreVoice(midi,channel,position,mem);
		free(v);
		e("\n");
	}
}
