
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "miditypes.h"
#include "util.h"


void FreeEventList(MidiEvent * ev) {
  MidiEvent * next;

  next = ev->next;
  while (next != NULL) {
    if (ev->seqdata != NULL) 
      free(ev->seqdata);

    free(ev);
    ev = next;
    next = next->next;  
  }

  free(ev);
}


void FreeSequence(MidiSequence * seq) {
  int i;
  for (i=0; i<seq->numtracks; i++) 
    FreeEventList(seq->track[i].evlist);
}


void TrackAddEventToEnd(MidiEvent * ev, MidiTrack * track) {
  MidiEvent **last;
  MidiEvent *next;

  next = track->evlist; 
  last = &track->evlist;

  while (next != NULL) {
    last = &next->next;
    next = next->next; 
  }    

  *last = ev;
}

int CountEvents(MidiTrack * track) {
  int i = 0;
  MidiEvent *next;

  next = track->evlist;
  while (next != NULL) {
    next = next->next;
    i++;
  }
  
  return i;
}

MidiEvent * NewEvent(char msg[4], long stamp, int msglen) {
  MidiEvent * ev;

  ev = (MidiEvent *) malloc(sizeof(MidiEvent));
  memcpy(ev->msg, msg, 4);
  ev->stamp = stamp;
  ev->msglen = msglen;
  ev->next = NULL;
 
  ev->seqevent = 0;
  ev->seqdata = NULL;
  ev->seqdatalen = 0;
  return ev;
}


MidiEvent * NewSeqEvent(unsigned char cmd, long stamp, char * data, int len) {
  MidiEvent * ev;

  ev = (MidiEvent *) malloc(sizeof(MidiEvent));
  memset(ev, 0, sizeof(MidiEvent));

  ev->stamp = stamp;
  ev->seqevent = cmd;
  ev->seqdata = (unsigned char *) data;
  ev->seqdatalen = len;

  return ev;
}


void printsequence(MidiSequence * seq) {
  int i;

  for (i=0; i<seq->numtracks; i++) {
    printf("Track %d: ", i);
    printf("%6d events\n", CountEvents(&seq->track[i]));
  }
}




