#ifndef lint
static char sccsid[] = "@(#)miditoscore.c	1.1 (mg@ukc.ac.uk) 2/11/90";
#endif
/*
 *	miditoscore - convert midi events from stdin to csound score file
 *		on stdout.
 *
 *	Events are timed by midiparse(), which sets
 *		extern struct timeb last_event_time
 *	to time when the command byte os received in milliseconds.
 *	
 *	Because we are piping straight into csound, output needs to be in the
 *	form put out by scsort.  Empirically, it doubles up the 2nd and 3rd
 *	parameters to f- and i- statements (!).
 */

#include <stdio.h>

#include <sys/types.h>
#include <sys/timeb.h>		/* for ftime() */

static struct timeb start_time;

main()
{
	/* function definitions */
	puts("w 0 60");		/* One beat per second */
	puts("f 1 0 0 1024 1024 10 1"); /* Sine wave table */
	fflush(stdout);

	ftime(&start_time);	/* milliseconds are ignored for simplicity */

	while (1) {
		midiparse();
	}
}

static struct timeb last_event_time;

time_stamp()
{
	ftime(&last_event_time);
}

control(){}
program(){}
aftertouch(){}
pitchbend(){}
sysexcl(){}

/*
 *	Convert midi events
 *	midi note values start at 
 *	score middle c is 8.00
 *	What would be midi note 0 is cscore note 3.00
 */

#define MIDI_MIDDLE_C 60

keyon(cmd, note_number, velocity)
{
	register int octave, pitch_class;

	/* Convert midi note numbering system to pitch class notation */
	/* What would be midi note 0 is cscore note 3.00 */
	octave = note_number/12 + 3;
	pitch_class = note_number % 12;

	printf("i 1.%d %d.%d %d.%d %d %d 0 %d.%02d\n",
		note_number,
		last_event_time.time - start_time.time,
		last_event_time.millitm,
		last_event_time.time - start_time.time,
		last_event_time.millitm,
		(velocity ? -1 : 0),
		(velocity ? -1 : 0),
		octave, pitch_class);

	fflush(stdout);
}

/*
 * Reassure csound that time is still passing.  It always waits for
 * the next event to know how long it should proceed with the current.
 */
active()
{
	printf("f 0 %d.%d %d.%d\n",
		last_event_time.time - start_time.time,
		last_event_time.millitm,
		last_event_time.time - start_time.time,
		last_event_time.millitm
		);
	fflush(stdout);
}

/* called on EOF by midipars.c */
finish()
{
	printf("s\ne\n");
	exit(0);
}

error(fmt, arg1, arg2)
char *fmt;
{
	fprintf(stderr, fmt, arg1, arg2);
	putc('\n', stderr);
}
