#include "trackstate.h"
#include <assert.h>
#include <stdio.h>

void init_trackstate(trackstate_t *track,MIDITRACK *t) // {{{
{
  assert( (track)&&(t) );
  track->t=t;
  track->end=track->t->data+track->t->len;
  init_midi_event(&track->next);
}
// }}}

void free_trackstate_data(trackstate_t *track) // {{{
{
  if (!track) {
    return;
  }
  free_midi_event_data(&track->next);
}
// }}}

int track_rewind(trackstate_t *track) // {{{
{
  if ( (!track)||(!track->t) ) {
    assert(0);
    return -1;
  }
  track->tickpos=0;
  track->pos=track->t->data;
  track->status=0x70;
  
  const int res=midi_event_read(&track->next,&track->status,track->pos,track->end);
  if (!res) {
    return -1;
  }
  track->pos+=res;
  return track->tickpos+track->next.time;
}
// }}}

int track_next(trackstate_t *track) // {{{
{
  if ( (!track)||(!track->t) ) {
    assert(0);
    return -1;
  }
  if (track->next.time<0) { // beyond end
    return -1;
  }

  // consume current event 
  if (midi_event_isEOT_fast(&track->next)) {
    if (track->pos!=track->end) {
      fprintf(stderr,"Excess data in track: %d bytes\n",track->end-track->pos);
    }
    track->next.time=-1;
    return -2; // EOT
  } else if (track->pos>=track->end) {
    fprintf(stderr,"Missing EOT in track\n");
    track->next.time=-1;
    return -1;
  }
  track->tickpos+=track->next.time;

  // read next
  const int res=midi_event_read(&track->next,&track->status,track->pos,track->end);
  if (!res) {
    return -1;
  }
  track->pos+=res;

assert(track->next.time>=0);
  return track->tickpos+track->next.time;
}
// }}}

//int track_peek()

