#!/usr/bin/awk -f
# Heiko Purnhagen <purnhage@tnt.uni-hannover.de>
# HP 20011101
#
# Convert cdrdao toc file to a script concatenating all segments on stdout.
#
# usage:
#  toc2plax-cut image.toc | plax -if be - -c 2 -s 44100 -o cut.wav
# or:
#  toc2plax-cut -v script=1 track=2 image.toc > image.plax
#  chmod +x image.plax
#  image.plax | plax -if be - -c 2 -s 44100 -o cut.wav
#
# dflt.: track=0 -> use all tracks

BEGIN {
  track = 0;
  ctrk = 0;
  if (script)
    printf "#!/bin/sh\n";
}

{
  if ($1 == "TRACK") {
    ctrk++;
  }
  if ($1 == "FILE" && (!track || track==ctrk)) {
    filename = substr($2,2,length($2)-2);
    split($3,timestr,":");
    if (timestr[2]=="")
      sta = timestr[1]/44100;
    else
      sta = timestr[1]*60+timestr[2]*1+timestr[3]/75;
    split($4,timestr,":");
    if (timestr[2]=="")
      dur = timestr[1]/44100;
    else
      dur = timestr[1]*60+timestr[2]*1+timestr[3]/75;
    s = sprintf("plax -ts %11.6f -td %11.6f -f integer16,0,44100,big,2,1 %s -o - -of be",sta,dur,filename);
    if (script)
      print s;
    else
      system(s);
  }
  if ($1 == "SILENCE" && (!track || track==ctrk)) {
    split($2,timestr,":");
    if (timestr[2]=="")
      dur = timestr[1]/44100;
    else
      dur = timestr[1]*60+timestr[2]*1+timestr[3]/75;
    s = sprintf("plax -tf %11.6f -f integer16,0,44100,big,2,1 /dev/zero -o - -of be",dur);
    if (script)
      print s;
    else
      system(s);
  }
}
