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

#define	MCPSM	(2 * MPU_CLOCK_PERIOD)	/* MPU clocks per standard measure */

/*	MpuPut(out, mp, when)
** Write MPU commands to 'out', adding TCIP commands.  Ignore times specified
** in the MpuCmd entry, just use "when" (also ignore TCIP commands).
** The calls to MpuPut() must occur in chronological order.
**
** Example: 'MpuPut(out, &m, t)' writes out the event in m
** (assuming it's not a TCIP command) such that it will be played at time t,
** inserting any TCIP commands as necessary.
**
** NOTE: a call with mp = 0 will pad timing commands out to the specified
** time and reinitialize the static data for another run.
** Example: 'MpuPut(out, (MpuCmd *) 0, t)'
**
** FURTHER: a call with mp = 0 and when = 0 will pad timing commands out to the
** next multiple of MCPSM and reinitialize the static data for another run.
** Example: 'MpuPut(out, (MpuCmd *) 0, 0L)'
*/

MpuPut(out, mp, when)
FILE	*out;
MpuCmd	*mp;
long	when;
{
	register int dt;
	static long last = 0;

	if (mp == (MpuCmd *) 0) {
	    if (when == 0)
		when = MCPSM * ((last + MCPSM - 1) / MCPSM);
	} else if (mp->time_tag == RT_TCIP)
	    return;
	dt = when - last;
	while (dt >= MPU_CLOCK_PERIOD) {
	    PutTCIP(out);
	    dt -= MPU_CLOCK_PERIOD;
	}
	if (mp == (MpuCmd *) 0) {
	    PutTCWME(out, dt);
	    last = 0;
	} else {
	    mp->time_tag = (unsigned char) dt;
	    mp->mpu_time = (long) dt;
	    PutMpuCmd(out, mp);
	    last = when;
	}
}
