/*

	TEST MIDI.C Midi Read and Write functionality.


*/

#include <stdio.h>
#include <stdlib.h>
#include "std.h"
#include "midi.h"
#include <conio.h>


#define PROGNAME "DELAYTST"

#define printf cprintf
#define CR "\r\n"

void midiError(int midi_error_code) {
	printf(PROGNAME ": %s\n",MidiErrorString(midi_error_code));
	exit(9);
}

#pragma argsused
int main(int argc, char**argv) {
	int i;
	long t;
	int result;
	MidiChannelT *channel;
	MidiMessageT *msg;

	directvideo = 1;
	fprintf(stderr,"DELAYTST v1.0 - Echo incoming events with delay\n"
						"by Larry Troxler" CR
						CR
	);
	channel = CreateMidiChannel(
				0, 		// base_address
				0,		// int #
				8192,  // buffer size
				RECORDPLAY_MODE,   // Operating mode
				MPU_INTERNAL_CLOCK, // internal clock
				120,			// Beats per minute
				MPU_TIMEBASE_192, // Timebase
				0,				 // Metronome beats per measure
				MPU_RX_ALL | MPU_DEFAULT_THRU, // rx/thru messages
				-1,			// midi_channel_mask (rx all midi channels)
				1,		    // Playback tracks
				&result
			);

	if (channel == NULL) {
		midiError(result);
	}

	while (YES) {
		msg = ReceiveMidiMessage(channel);
		if ((result = MidiStatus(channel)) != 0) {
			midiError(result);
		}
		if (msg != NULL  && msg != ((MidiMessageT*)(-1))) {
			ScheduleMidiMessage(
			  channel,
			  0,
			  GetMidiMessageReceiveTime(msg) + 1024,
			  msg
			);
		} else {
			if (kbhit())
				break;
		}
	}
	DestroyMidiChannel(channel);
	getch();
	return 0;
}
