#!/bin/sh

# This runs HTK to do a simple segmentation of training data,
# where there is no human segmentation, just a word-level transcription.
# It uses the UNISYN code to generate phoneme-level transcription
# and HERest to do the training.

date >>LOG
echo ARGS: $0 $* >>LOG
set -x

NP=8
PRUNE=0.0
tdata=training

if test "$1" = -continue
then
  # flaglist='mvt mvw mvtw e mvt mvtw r mvtw mvt mvtw'
  flaglist='e mv mvtw e mv mvtw mvtw'
  init=0
  ti=$2
  shift; shift
elif test "$1" = -Continue
then
  flaglist='e mv mvtw e mvtw r mvtw e mvtw mvtw e mvtw mvtw e mvtw mvtw'
  init=0
  ti=$2
  shift; shift
elif test "$1" = -tmpR
then
  init=2
  tc=$2
  flaglist='r mv mvtw mvtw r mv mvtw mvtw mvtw r mv mvtw mvtw'
  ti=tmpE0
  shift; shift;
elif test "$1" = -shortR
then
  init=2
  tc=$2
  flaglist='r mv mvtw mvtw r mv mvtw mvtw r mvtw mvtw'
  ti=tmpE0
  shift; shift;
else
  flaglist='m m mvw m mv mvtw mvw mvt mvw r mv mvtw r mv mvtw mvtw r mv mvtw r mvtw'
  init=1
  ti=tmpE0
fi

V=0.001
rec=$1
mfccname=$2
mapname=$3
shift; shift; shift
MetaData=$*
#rec is a directory containing initial specification of stuff for
# a particular try at building a HMM.

if test $init = 1
then
  bash bin/initialize_HERest.sh $tdata $rec $ti $NP $mfccname $mapname $MetaData ||
  	die.sh "Initialize.sh fails" || exit 1
elif test $init = 2
then
  bash bin/initialize_copy.sh $tdata $rec $tc $ti $NP $mfccname $mapname $MetaData ||
  	die.sh "Initialize.sh fails" || exit 1
fi

for flags in $flaglist
do
  p=${ti#tmpE};
  tj=tmpE$(($p+1))
  mv $tj $tj.junk && { rm -rf $tj.junk & }
  mkdir $tj $tj/accumulators
  cp -p $ti/* $tj
  cp -r -p $ti/trainlist.d $tj
  cp -r -p -l $ti/lab $tj

  if test $flags = "r"
  then
    bash bin/HParse_intermediate.sh $tdata $rec $p $NP $PRUNE || die.sh "HParse_intermediate fails." || exit 1
  elif test $flags = "e"
  then
    bash bin/HHed_script.sh $tdata $rec $p ||
	die.sh "HHed_script.sh fails." || exit 1
  else
    bash bin/HERest_script.sh $tdata $rec $p $NP "$flags" $V ||
	die.sh "HERest_script.sh fails." || exit 1
  fi
  ti=$tj
done


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

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

# bash bin/recognize_training_set.sh

rm -f tmpR
ln -s $tj tmpR
# tr ' ' '\012' < $tdata/generated_phones >tmpR/hmmlist.txt
mkdir tmpR/ph
cd tmpR/ph
ln -s ../acoustics.mmf macros
cp ../../$tdata/generated_phones phones
