#!/usr/bin/awk -f
# HP 20000215
# snap all boundaries to 44100/75=588 sample frames
# and ensure continuity
# usage:
#  toc2toc king1_44.toc > king1_44_frm.toc
#  toc2toc contfrm=75 king1_44.toc > king1_44_frm.toc

BEGIN {
  lastfrm = 0;
  lastfile = "";
  contfrm = 7;
  state = 1;
}

{
  if ($1 == "FILE") {
    filename = substr($2,2,length($2)-2);
    split($3,timestr,":");
    if (timestr[2]=="")
      sta = timestr[1]/588;
    else
      sta = timestr[1]*4500+timestr[2]*75+timestr[3]*1;
    split($4,timestr,":");
    if (timestr[2]=="")
      dur = timestr[1]/588;
    else
      dur = timestr[1]*4500+timestr[2]*75+timestr[3]*1;
    stafrm = int(sta+0.5);
    durfrm = int(dur+0.5);
    offsfrm = 0;
    writeprev = 0;
    if (filename != lastfile)
      writeprev = 1;
    else {
      if (stafrm != lastfrm) {
	printf "continuity %02d:%02d:%02d -> %02d:%02d:%02d ...",\
	  lastfrm/4500,(lastfrm/75)%60,lastfrm%75,\
	  stafrm/4500,(stafrm/75)%60,stafrm%75 > "/dev/stderr";
	if (stafrm <= lastfrm+contfrm && stafrm >= lastfrm-contfrm) {
	  offsfrm = lastfrm-stafrm;
	  printf " fixed (%d)\n",offsfrm > "/dev/stderr";
	}
	else {
	  writeprev = 1;
	  if (stafrm < lastfrm)
	    printf " jumping back\n" > "/dev/stderr";
	  else
	    printf " jumping ahead\n" > "/dev/stderr";
	}
      }
    }
    stafrm += offsfrm;
    durfrm -= offsfrm;
    if (durfrm<0)
      durfrm = 0;
    if (state==2 && writeprev) {
      if (prevdurfrm==0)
	printf "Warning: duration is 00:00:00\n" > "/dev/stderr";
      printf "FILE \"%s\" %02d:%02d:%02d %02d:%02d:%02d\n",prevfilename,\
	prevstafrm/4500,(prevstafrm/75)%60,prevstafrm%75,\
	prevdurfrm/4500,(prevdurfrm/75)%60,prevdurfrm%75;
      state = 1;
    }
    if (state==1) {
      prevstafrm = stafrm;
      prevdurfrm = durfrm;
      prevfilename = filename;
    }
    else {
      printf "joining ...\n" > "/dev/stderr";
      prevdurfrm += durfrm;
    }
    state = 2;
    lastfrm = stafrm+durfrm;
    lastfile = filename;
  }
  else {
    if (state==2) {
      if (prevdurfrm==0)
	printf "Warning: duration is 00:00:00\n" > "/dev/stderr";
      printf "FILE \"%s\" %02d:%02d:%02d %02d:%02d:%02d\n",prevfilename,\
	prevstafrm/4500,(prevstafrm/75)%60,prevstafrm%75,\
	prevdurfrm/4500,(prevdurfrm/75)%60,prevdurfrm%75;
      state = 1;
    }
    if ($1 == "SILENCE") {
      split($2,timestr,":");
      if (timestr[2]=="")
	dur = timestr[1]/588;
      else
	dur = timestr[1]*4500+timestr[2]*75+timestr[3]*1;
      durfrm = int(dur+0.5);
      if (durfrm)
	printf "SILENCE %02d:%02d:%02d\n",\
	  durfrm/4500,(durfrm/75)%60,durfrm%75;
    }
    else
      printf "%s\n",$0;
  }
}

