#!/bin/sh
#
#  Calculate and view DFT-spektrogram
#
#  $Id: DFT.sh,v 1.3 1999/11/19 10:53:22 mummert Exp mummert $
#
#  M.Mummert
#
TRANS=bark
if [ $# -lt 2 ]
then
    echo "Calculate, view and reconstruct DFT-spectrogram" 1>&2
    echo "Default parameters set to match AMS-spectrogram at around 1 kHz"
    echo "Usage: $0 <basename> <tag> [<options>]" 1>&2
    echo "Sample rate <tag> may be 080, 110, 128, 160, 220, 320, 441, 480" 1>&2
    echo "Expected sound file is <basename>.<tag> (16bit signed, raw, mono)" 1>&2
    echo "Pass <options> to override default parameters for \`dft' and \`costximg'" 1>&2
    exit 1
fi
DIR=""
BASE=$1
TAG=${2:-128}
shift 2
OPTPARS=$*
case $TAG in
080)    FSAMP=8000;  M=10; N=1024; HOP=1;;
110)    FSAMP=11025; M=14; N=1024; HOP=1 ;;
128)    FSAMP=12800; M=16; N=1024; HOP=1 ;;
160)    FSAMP=16000; M=20; N=2048; HOP=1 ;;
220)    FSAMP=22050; M=28; N=2048; HOP=1 ;;
320)    FSAMP=32000; M=40; N=4096; HOP=1 ;;
441)    FSAMP=44100; M=55; N=4096; HOP=1 ;;
480)    FSAMP=48000; M=60; N=4096; HOP=1 ;;
*)      echo "Rate tag $TAG not implemented" 1>&2
        exit 1 ;;
esac
SWDOW=b4
SWF3DB=60
WDOW=4p1
FSAMP2=`expr $FSAMP / 2`
FEND=$FSAMP2
WF3DB=25  # B3dB 50Hz
IEND=-2   # `expr $N / 2`
NFI=`expr \( $N / 2 + 1 + $HOP - 1 \) / $HOP`
DF=`awk 'BEGIN { print '$FSAMP2' / '$NFI' }' </dev/null`
if [ ! -f $DIR$BASE.$TAG ]
then
    echo "Input file $DIR$BASE.$TAG not found" 1>&2
    exit 1
fi
SPPFILE=$BASE.DFT.ftp 
SPLFILE=$BASE.DFT.ftt
DFTFILE=$BASE.DFT.dft.par 
COSFILE=$BASE.DFT.costximg.par 
OLAFILE=$BASE.DFT.ola.par 
OFILE=$BASE.DFT.OLA.$TAG 

echo "* Calculate and view DFT-spectrogram"
echo ": Create dft parameter file: $DFTFILE"
echo "idelay -1 ifile $DIR$BASE.$TAG m $M sppfile $SPPFILE splfile $SPLFILE n $N oendidx $IEND window $WDOW wf3db $WF3DB fsamp $FSAMP ohopidx $HOP $OPTPARS" | xargs -n2 > $DFTFILE
DFTCMD="dft loadparm $DFTFILE"
$DFTCMD saveparm $DFTFILE info >/dev/null

echo ": Create costximg parameter file: $COSFILE"
echo "stxfile $SPLFILE stxnti $M stxnfi $NFI stxgrid 1 stxf0 0 stxunitdf hz stxdf $DF fsamp $FSAMP stxfmt ftt stxthresh 20 stxgrydb 3.5 ftrans $TRANS fend $FEND $OPTPARS" | xargs -n2 > $COSFILE
COSCMD="costximg loadparm $COSFILE nolimits"
$COSCMD saveparm $COSFILE info >/dev/null

echo ": Create ola parameter file: $OLAFILE"
echo "ofile $OFILE m $M sppfile $SPPFILE splfile $SPLFILE n $N iendidx $IEND window $SWDOW wf3db $SWF3DB fsamp $FSAMP ihopidx $HOP scale 0.22" | xargs -n2 >$OLAFILE
OLACMD="ola loadparm $OLAFILE"
$OLACMD saveparm $OLAFILE info >/dev/null

echo ": Execute: $DFTCMD"
$DFTCMD || exit 1
echo ": Calculated level-spectrogram: $SPLFILE"
echo ": Calculated phase-spectrogram: $SPPFILE"

echo ": Execute: $COSCMD"
$COSCMD

echo ": Execute: $OLACMD"
$OLACMD || exit
echo ": Reconstructed signal: $OFILE"

echo "* Done."
exit 0
