/*

	TEST MIDI.C Midi Read functionality.


*/

#include <stdio.h>
#include <stdlib.h>
#include "std.h"
#include "midi.h"
#include <conio.h>


#define PROGNAME "WRITETST"

#define printf cprintf
#define CR "\r\n"

void midiError(int midi_error_code) {
	printf(PROGNAME ": %s\n",MidiErrorString(midi_error_code));
	exit(9);
}

void SendRandomNote(MidiChannelT *channel) {
	MidiMessageT *msg;
	static int send_time = 0;

	msg = AllocMidiMessage();
	SetMidiMessage(msg,NOTE_ON_MSG,36+random(36),64,0,NULL);
//	SendMidiMessage(channel,msg);
	ScheduleMidiMessage(channel,0,send_time,msg);
	send_time += random(64);

//	delay(random(1000));
}
#pragma argsused
int main(int argc, char**argv) {
	int result;
	MidiChannelT *channel;
	MidiMessageT *msg;

	directvideo = 1;
	fprintf(stderr,"WRITETST v1.0 - Write random MIDI note events\n"
					   "Copyright (c) 1990, Robin Davies" CR
					   CR
	);
	channel = CreateMidiChannel(
				0, 		// base_address
				0,		// int #
				32760,  // buffer size
				PLAY_MODE,   // Operating mode
				MPU_INTERNAL_CLOCK, // internal clock
				60,			// 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 (!kbhit()) {
		if (MidiMessagesPending(channel) < 10) {
			SendRandomNote(channel);
			if ((result = MidiStatus(channel)) != 0) {
				midiError(result);
			}
		} else {
			if (kbhit())
				break;
		}

	}
	DestroyMidiChannel(channel);
	getch();
	return 0;
}
