#!/bin/sh

# This runs HTK to do a simple segmentation of training data,
# where training data is human-segmented.

set -x

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

TrainingFiat=/proj/aesop/proc/manual.fiat

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



rm -rf training
mkdir training training/mfcc training/lab
python bin/generate_mfcc_lab_train.py $mfccname $TrainingFiat

rm -rf tmp[0-9]
mkdir tmp1
phones=$(cat $rec/phones | tr ' ' '\012')

# labs is a directory containing label files
# config is a file of macros that are applied to everything
# hmmlist is a list of MMF files
# trainlist seems to be a list of audio files
# labs is what?

ls training/mfcc/*.mfcc  |
egrep -v 'mfcc/(photo_|HTKsimple2).mfcc' >$t/trainlist

for phn in $phones
do
  HInit -A -D -T 1 -X lab -C $rec/config -l $phn -L training/lab -S $t/trainlist -H $rec/macros -M tmp1 $rec/$phn ||
	die.sh "HInit" || exit 1
done

for i in 1 2
do
  ti=tmp${i}
  j=$[i+1]
  tj=tmp${j}
  mkdir $tj
  for phn in $phones
  do
    HRest -A -D -T 1 -X lab -C $rec/config -S $t/trainlist -H $rec/macros -M $tj -l $phn -L training/lab $ti/$phn ||
	die.sh "HRest" || exit 1
  done
done


rm -rf tmpR
ln -s $tj tmpR
mkdir tmpR tmpR/reco

(
cd $tj; cat $phones >hmmsdef.mmf;
)

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

# OK.  Now we have the HMM optimized.

# Recognize the training set, just to make sure that everything is working
# properly:
tr ' ' '\012' < $rec/phones >tmpR/hmmlist.txt
for f in $(cat $t/trainlist)
do
  fb=$(basename $f .mfcc)
  HVite -A -D -T 1 -C $rec/config -i tmpR/reco/$fb.mlf -H tmpR/hmmsdef.mmf -w tmpR/net.slf $rec/dict tmpR/hmmlist.txt $f || die.sh "HVite" || exit 1
done

#ADDED BY AL
python bin/convert_ws_lab.py ${rec}_$mfccname $TrainingFiat tmpR/reco
