#include <stdio.h>
#include <midi.h>

static Period = MPU_CLOCK_PERIOD;

MidiClock(in,out)
	FILE *in, *out;
/*
** Copy MIDI data from 'in' to 'out', adding TCIP & TCWME commands
** Example: 'MidiClock(in,out)' inserts Timing Clock In Progress and
** Timing Clock With Measure End commands in the Midi data from 'in'
** and writes it to 'out' (stripping out the old TCIP & TCWME commands).
*/
{
	int put, dur;
	long last = 0, next, when, nexttcwme = 2*Period;
	MpuCmd m;

	while (GetMpuCmd(in, &m)) {
		if (m.time_tag == RT_TCIP)
			dur = Period, put = 0;
		else
			dur = m.time_tag, put = m.mpu_cmd[0] != RT_TCWME;
		when = last + dur;
		do {
			next = nexttcwme < when? nexttcwme : when;
			while (next - last >= Period)
				PutTCIP(out), last += Period;
			if (next == nexttcwme) {
				PutTCWME(out, next - last);
				last = next;
				nexttcwme = last + 2 * Period;
			}
		} while (next < when);
		if (put) {
			m.time_tag = (unsigned char) next - last;
			m.mpu_time = (long) next - last;
			PutMpuCmd(out,&m);
			last = next;
		}
	}
	if (last > nexttcwme - 2 * Period) {
		while (nexttcwme - last >= Period)
			PutTCIP(out), last += Period;
		PutTCWME(out, nexttcwme - last);
	}
}
