#!/bin/sh

set -x

NP=8
NPR=$(($NP+$NP/2))

rec=$1
mfccname=$2
#rec is a directory containing initial specification of stuff for
configfile=${mfccname}
mapping=$3
#rec is a directory containing initial specification of stuff for
# a particular try at building a HMM.

TrainingFiat=/proj/aesop/proc/metadata/*.fiat
tdata=training



mv $tdata junk && { rm -rf junk & }
mkdir $tdata $tdata/mfcc $tdata/lab
python bin/generate_for_HERest.py $configfile $tdata 0 $mapping $TrainingFiat || die.sh "Generate fails" || exit 1
ti=tmp0
rm -f $ti
ln -s $rec $ti


PHONEME_V_FLOOR=0.1
TRANS_V_FLOOR=0.5


tj=tmp1
mv $tj $tj.junk
rm -rf $tj.junk &
mkdir $tj $tj/ph
cp -p $ti/* $tj; cp -p $ti/ph/* $tj/ph
python bin/writeHMM.py -p "$(cat $tdata/generated_phones)" $tj/ph <$rec/pmodels.txt || die.sh "writeHMM.py fails." || exit 1
phones=$(cat $tj/ph/phones | tr ' ' '\012')
for phn in $phones
do
  HRest -A -D -T 1 -t -v $TRANS_V_FLOOR -i 20 -t -X lab -C $tj/config -S $tdata/trainlist -H $tj/ph/macros -M $tj/ph -l "$phn" -L $tdata/lab "$tj/ph/$phn"
done

rm -f tmpR
ln -s $tj tmpR

{
python -c 'import sys; sys.stdout.write("$phone = " + " | ".join([q.strip() for q in sys.stdin.readlines()]) + " ;\n")' <$tj/ph/phones
cat $tj/gram
} >$tj/Gram

HParse -T 1 -A -C $tj/config -D $tj/Gram $tj/net.slf || die.sh "HParse" || exit 1


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

python bin/convert_back_fa.py ${rec}_$mfccname $tj/reco $tdata/metadata.fiat
