#!/bin/sh

set -x

NP=8
NPR=$(($NP+$NP/2))
SIZE=1.2e12

rec=$1
mfccname=$2
shift; shift; shift;
MetaData=$*
# configfile=$rec/coding
configfile=${mfccname}
#rec is a directory containing initial specification of stuff for
# a particular try at building a HMM.

# TrainingFiat=/proj/aesop/proc/metadata/*.fiat



( cd $rec; make )
NSPL=$( cd $rec >/dev/null 2>&1 ; wc -c $(cat phones) | awk '/total$/ {print int(size/($1*$1*np));}' np=$NP size=$SIZE - )
echo 'NSPL=' $NSPL 'NP=' $NP

if test bin/generate_for_HERest.py -nt all
then
  mv all all.junk && { ionice -c 2 -n 7 rm -rf all & }
  mkdir all all/mfcc all/lab
  python bin/generate_for_HERest.py $configfile all 0 sonority $MetaData || die.sh "Generate fails" || exit 1
fi
rm -f all/trainlist.*
rm -f tmpE0
ln -s $rec tmpE0

phones=$(cat $rec/phones | tr ' ' '\012')

PHONEME_V_FLOOR=0.1
TRANS_V_FLOOR=0.5

ti=$rec
tj=tmp2
rm -rf $tj
mkdir $tj
cp -p $ti/* $tj
for phn in S C S V S 
do
  HRest -A -D -T 1 -t -u mv -v $PHONEME_V_FLOOR -i 20 -t -X lab -C $rec/config -S all/trainlist -H $tj/macros -M $tj -l $phn -L all/lab $tj/$phn ||
	die.sh "HRest" || exit 1
done
for phn in $phones
do
  HRest -A -D -T 1 -t -u mv -v $TRANS_V_FLOOR -i 20 -t -X lab -C $rec/config -S all/trainlist -H $tj/macros -M $tj -l $phn -L all/lab $tj/$phn
done
for phn in S V S C S
do
  HRest -A -D -T 1 -t -u mv -v $PHONEME_V_FLOOR -i 60 -t -X lab -C $rec/config -S all/trainlist -H $tj/macros -M $tj -l $phn -L all/lab $tj/$phn
done

rm -f tmpR
ln -s $tj tmpR

HParse -T 1 -A -C $rec/config -D $rec/gram tmpR/net.slf || die.sh "HParse" || exit 1


mkdir tmpR/reco
# Recognize the training set, just to make sure that everything is working
# properly:
{
for f in $(select_fiat_entries.py -show fncore all/metadata.fiat)
do
  echo HVite -A -D -T 1 -d tmpR -C $rec/config -i tmpR/reco/$f.mlf -H tmpR/macros -w tmpR/net.slf $rec/dict $rec/phones all/mfcc/$f.mfcc
done
} | bash bin/run_several.sh /tmp/$$/stdouts $NPR 3 || die.sh "HVite" || exit 1

python bin/convert_back_HERest.py ${rec}_$mfccname tmpR/reco all/metadata.fiat
