#!/usr/bin/awk -f
# Heiko Purnhagen <purnhage@tnt.uni-hannover.de>
# HP 20000212 20000215 20010406 20010818
#
# Convert cdrdao toc file to a script extracting all tracks and their
# indexed segments as wav files from CD image file.
#
# usage:
#  toc2plax-idx FILE=image.bin image.toc > image.plax
#  source image.plax

function plaxcmd() {
  if (sta >= 0)
    printf "plax -ts %8.3f -td %8.3f -f integer16,0,44100,big,2,1 %s -o %s%02d%s%01d%s\n",\
      sta,dur,filename,FILE "_",trkno,"_",idxno,".wav";
  sta = -1;
}

BEGIN {
  trkno = 0;
  idxno = 0;
  sta = -1;
  printf "#!/bin/sh\n";
}

{
  if ($1 == "FILE") {
    plaxcmd();
    trkno++;
    filename = substr($2,2,length($2)-2);
    split($3,timestr,":");
    if (timestr[2]=="")
      statrk = timestr[1]/44100;
    else
      statrk = timestr[1]*60+timestr[2]*1+timestr[3]/75;
    split($4,timestr,":");
    if (timestr[2]=="")
      durtrk = timestr[1]/44100;
    else
      durtrk = timestr[1]*60+timestr[2]*1+timestr[3]/75;
    idxno = 1;
    sta = statrk;
    dur = durtrk;
  }
  if ($1 == "START") {
    split($2,timestr,":");
    if (timestr[2]=="")
      idx = timestr[1]/44100;
    else
      idx = timestr[1]*60+timestr[2]*1+timestr[3]/75;
    idxno = 0;
    sta = statrk;
    dur = idx;
    plaxcmd();
    idxno = 1;
    sta = statrk+idx;
    dur = durtrk-idx;
  }
  if ($1 == "INDEX") {
    split($2,timestr,":");
    if (timestr[2]=="")
      idx = timestr[1]/44100;
    else
      idx = timestr[1]*60+timestr[2]*1+timestr[3]/75;
    dur -= durtrk-idx;
    plaxcmd();
    idxno++;
    sta = statrk+idx;
    dur = durtrk-idx;
  }
}

END {
  plaxcmd();
}
