#!/bin/sh

#Calculate how periodic the main microphone signal is.

t=/tmp/$$
mkdir $t
trap "rm -rf $t" EXIT

err="$0: OXIVOICE needs to be set.  Try /home/mint/gpk/voicing."
OV=${OXIVOICE:?$err}
test -x $OV/hpfilter.py || g_die "$0: Cannot find $OV/hpfilter.py" || exit 1

rewrite=0
DT=0.010
while true
do
	arg=$1; shift;
	case "$arg" in
	'') break;;
	-rewrite) rewrite=1;;
	-dt) DT=$1; shift;;
	*)	g_die "Unrecognized arg: $arg" || exit 2;;
	--) break;;
	esac
done

select_fiat_entries.py -show "'%s/%s %s' % (d, f, sex)" DB.fiat >$t/dbfiat

(
while read n sex
do
    echo 'Working on' $n $sex

    if test "$sex" = "m" -o "$sex" = "male"
    then f0prm=$OXIROOT/lib/Pget_f0_m
    elif test "$sex" = "f" -o "$sex" = "female"
    then f0prm=$OXIROOT/lib/Pget_f0_f
    else
	    g_die "No sex specified for $n" || exit 1
    fi

    if test ! -s $n/raw.dat
    then
      g_die "No data: $n" || exit 1
    elif test $rewrite = 1 -o "$n/raw.dat" -nt "$n/f0.sd" -o "$n/raw.dat" -nt "$n/f0.dat"
    then
      rm -f "$n/f0.sd" "$n/f0.dat" "$t/filtered.sd"
      python $OV/hpfilter.py 50 "$n/raw.dat" "$t/filtered.sd" ||
      		g_die "hpfilter.py failed on $n" || exit 2
      get_f0 -P $f0prm -i $DT $t/filtered.sd "$n/f0.sd"
      test -s "$n/f0.sd" && ESPS_to_data.sh "$n/f0.sd" >"$n/f0.dat"
    fi
done
) <$t/dbfiat

