#!/bin/bash

# sfcheck  : script that checks soundfile headers and report whether a soundfile
# is in WAVE or AIFF or does not have a readable soundfile header in
# one of these 2 formats A.S. 7/24/2000, revised 7/2003, 9/2004

if  ( [ $# == 0 ] ) ; then  # print usage summary
    echo "   sfcheck  syntax :"
    echo "    sfcheck  inputfile1  [inputfile2  inputfileN]"
    echo " Example: sfcheck myvoice1.wav goodstuff.aif  amix"
    echo " Result: sfcheck will check the soundfile headers of these 3 files and report their formats."
    echo " Metacharacters such as * can be used, but MUST be preceded by a backslash."
    echo " Example:   sfcheck MIXES/\* "
    echo " Result: sfcheck will check the soundfile headers of all files in your soundfile"
    echo " subdirectory MIXES"
    echo " --  --  --  --  --  --  --  --  --  --  --  --  --  --  --"
    exit 1
fi

cd $SFDIR    

TMPOUT=/tmp/tmpsfcheck$$
for i in $* ; do

# 1. See if file exists
  if [ -e $i ] ; then
    SOURCESF=$i
  elif [ -e $i.wav ] ; then
    SOURCESF=$i.wav
  elif [ -e $i.aif ] ; then
    SOURCESF=$i.aif
  elif [ -e $i.aiff ] ; then
    SOURCESF=$i.aiff
  else
    echo " ERROR: No file named >> $i << found. Quitting."
          echo " (Your current working soundfile directory is $SFDIR)"
    # exit 1
  fi
# 2. run csound to get header info
csound -U sndinfo $SOURCESF  >& $TMPOUT
# 3. check for WAVE or AIFF in header info
  if ( ( grep  -e "WAVE\ soundfile" $TMPOUT >& /dev/null ) && ( grep  -e "$SOURCESF: WAVE" $TMPOUT >& /dev/null  ) ) ; then
   echo "WAVE  $SOURCESF"
  elif ( ( grep  -e "AIFF\ soundfile" $TMPOUT >& /dev/null ) && ( grep  -e "$SOURCESF: AIFF" $TMPOUT >& /dev/null ) ) ; then
   echo "AIFF  $SOURCESF"
 # errors: 
   elif ( file $i | grep -e "$i:\ directory" >& /dev/null ) ; then
       echo " ERROR: File $SOURCESF is a directory, not a soundfile"

   elif [ -e $i ] ; then
    #echo " ERROR: File $i exists but is not a WAVE or AIFF soundfile:"
    echo -n " ERROR: File $i is not a WAVE or AIFF soundfile: "
    file $i
fi
rm -f $TMPOUT
done
