#!/bin/bash



exportwave () {

# WAVE file is of the format:
# bytes 1-4: characters "RIFF"
# bytes 5-8: unsigned int (little endian) length of data to follow
# bytes 9+: WAV data (data format is unimportant to us)


base=$1
target=$2

# fetch length of WAV data in xxd format, which is hex character format, bytes space-separated, little endian
lenstrb="$(dd if=$source bs=1 iseek=$((base+4)) count=4 2> /dev/null | xxd)"

# convert xxd output to hex character format, no spaces, big endian
lenstr="$(echo $lenstrb | cut -c 17-18)$(echo $lenstrb | cut -c 15-16)$(echo $lenstrb | cut -c 12-13)$(echo $lenstrb | cut -c 10-11)"

# convert length to decimal
lenstr=$((0x$lenstr))

# extract to .WAV file
wavlen=$((lenstr+8))
dd if=$source of=$target bs=1 iseek=$base count=$wavlen 2> /dev/null

nextbase=$((base+wavlen))
echo $nextbase
}





exportuax () {

source=$1

echo "Exporting $uaxfile $source ..."
base=0
offset=8000
offset=0
found=

while [[ -z $found && $offset -lt 12000 ]] ; do
  key="$(dd if=$source bs=1 iseek=$((base+offset)) count=4 2> /dev/null)"
  if [ "$key" == "RIFF" ] ; then
    found=1
  else
    offset=$((offset+1))
  fi
done

if [ -z $found ] ; then
  echo "FAILED on $source"
else
  base=$((base+offset))
  echo "uax base = $base"
  vers=1
  while [ "$key" == "RIFF" ] ; do
    tfilename="${source}_${vers}.wav"
    echo "Exporting \"$tfilename\" ..."
    #dd if=$source bs=1 iseek=$base count=500 2> /dev/null | xxd
    nextbase=$(exportwave $base $tfilename)
    base=$nextbase
    echo "nextbase = $nextbase"
    key="$(dd if=$source bs=1 iseek=$base count=4 2> /dev/null)"
    vers=$((vers+1))
    offset=0
    found=
    while [[ -z $found && $offset -lt 50 ]] ; do
      key="$(dd if=$source bs=1 iseek=$((base+offset)) count=4 2> /dev/null)"
      if [ "$key" == "RIFF" ] ; then
        found=1
      else
        offset=$((offset+1))
      fi
    done
  base=$((base+offset))
  echo "offset to next is $offset"
  done
fi
}



cd "${0%/*}"
echo
echo
ls *.uax | while read src ; do
  exportuax $src
  if [ -f "${src}_1.wav" ] ; then
    mv $src "${src}_done"
  fi
done
echo
echo
exit

