#!/bin/csh -f

#    fixmc60wav v.1.02
#           by
# L. Padilla (e-mail: padilla at domain "gae ucm es")
#  Madrid, August 2004 - December 2006
#
# Latest version at http://www.gae.ucm.es/~padilla/extrawork/fixmc60wav.csh

# Fix: Write first 32 bytes of input file, then overwrite two bytes, which are
# the file size in bytes minus 56, in binary and both bytes swapped. Then write
# next 4 bytes of file and overwrite another two bytes using the formula
# 2 * (file size in bytes - 60) + 1, in binary and both bytes swapped. Then
# write rest of bytes of input file. Output file is named fixed_<file>.

set echo_style = both
set infile = "$1"

if ("$infile" == "" || ! -e "$infile") then

  echo "Usage: fixmc60wav <file>"
  exit

endif

set FileSizeDec = `ls -la "$infile" | awk '{print $5}'`

set BlockAlignHex = `echo "obase=16; $FileSizeDec - 56" | bc`
set ByteA1Hex = `echo $BlockAlignHex | cut -c 3-4`
set ByteA2Hex = `echo $BlockAlignHex | cut -c 1-2`
set ByteA1Oct = `echo "ibase=16; obase=8; $ByteA1Hex" | bc`
set ByteA2Oct = `echo "ibase=16; obase=8; $ByteA2Hex" | bc`

set SamplesPerBlockHex = `echo "obase=16; 2 * ($FileSizeDec - 60) + 1" | bc`
set ByteB1Hex = `echo $SamplesPerBlockHex | cut -c 3-4`
set ByteB2Hex = `echo $SamplesPerBlockHex | cut -c 1-2`
set ByteB1Oct = `echo "ibase=16; obase=8; $ByteB1Hex" | bc`
set ByteB2Oct = `echo "ibase=16; obase=8; $ByteB2Hex" | bc`

dd if="$infile"         bs=1 count=32           > fixed_"$infile"
echo "\0$ByteA1Oct""\0$ByteA2Oct" | tr -d '\n' >> fixed_"$infile"
dd if="$infile" skip=34 bs=1 count=4           >> fixed_"$infile"
echo "\0$ByteB1Oct""\0$ByteB2Oct" | tr -d '\n' >> fixed_"$infile"
dd if="$infile" skip=40 bs=1                   >> fixed_"$infile"
