/*
** TRIM -- Copy MIDI data from the standard input to the standard output,
** trimming off blank time at the beginning and end.
** The output has TCIP commands repositioned logically.
** Example: 'trim -h <foo >fum' deletes only the leading silence.
*/
#include <stdio.h>
#include <midi.h>

main(argc, argv)
char *argv[];
{
	int head = 0, tail = 0, stat;
	long now, ptcwme, offset, lastwhen, lasttcwme;
	MCMD *mp;

	while (--argc > 0) {
	    if (argv[argc][0] == '-') {
		switch (argv[argc][1]) {
		case 'h':
		    head++;
		    break;
		case 't':
		    tail++;
		    break;
		default:
		    goto syntax;
		}
	    } else {
syntax:
		fprintf(stderr, "Usage: %s [-h] [-t] <file\n", argv[0]);
		exit(2);
	    }
	}
	if (head == 0 && tail == 0)
	    head = tail = 1;
	ptcwme = -1L;
	now = lastwhen = offset = 0L;
	while (mp = getmcmd(stdin, now)) {
	    now = mp->when;
	    stat = mp->cmd[0];
	    if (stat == RT_TCWME) {
		ptcwme = now - offset;
		if (ptcwme == lasttcwme)
		    ptcwme = -1L;
		continue;
	    }
	    if (head) {
		offset = now;
		head = 0;
		ptcwme = -1L;
	    }
	    if (ptcwme >= 0) {
		Rt_tcwme.when = ptcwme;
		putmcmd(stdout, &Rt_tcwme);
		lasttcwme = ptcwme;
		ptcwme = -1L;
	    }
	    mp->when -= offset;
	    putmcmd(stdout, mp);
	    lastwhen = mp->when;
	}
	if (ptcwme == lastwhen) {
	    Rt_tcwme.when = ptcwme;
	    putmcmd(stdout, &Rt_tcwme);
	}
}
