#!/bin/bash

set -x

tdata=$1
rec=$2
ti=$3
NP=$4
mfccname=$5
mapname=$6
shift; shift; shift
shift; shift; shift;
MetaData=$*

rm -f $ti; rm -rf $ti
bin/mkscratch.sh $ti
mkdir $ti/ph
cp -p $rec/* $ti

# mv $tdata $tdata.junk && { ionice -c2 -n7 rm -rf $tdata.junk & }
# mkdir $tdata
bin/mkscratch.sh $tdata
cp -p $rec/coding $tdata
# ( cd $tdata; ln -s ../$rec/coding; )

mkdir $tdata/lab $tdata/mfcc
python bin/generate_VY_HERest.py $mfccname $tdata $rec $mapname $MetaData ||
	die.sh "Generate fails" || exit 1
python bin/basename.py .mfcc <$tdata/trainlist > $ti/trainlist
mv $tdata/lab $ti/lab

python bin/writeHMM.py -p "$(cat $tdata/generated_phones)" $ti/ph <$rec/pmodels.txt || die.sh "writeHMM.py fails." || exit 1
phones=$(cat $tdata/generated_phones)

p=${ti#tmpE}
bash bin/redo_trainlist.sh $tdata $ti $ti $NP < $ti/trainlist || die.sh "Redo_trainlist.sh fails" || exit 1

awk '{print tdata "/mfcc/" $1 ".mfcc"; }' tdata=$tdata $ti/trainlist >$ti/trainlist.tmp
tlist=$ti/trainlist.tmp
for phn in $phones
do
  HCompV  -A -D -T 1 -C $rec/config -m -D -L $ti/lab -H $ti/ph/macros -M $ti/ph	\
  	-S $tlist -l $phn $ti/ph/$phn
done

(
cd $ti/ph
cat macros $phones > ../acoustics.mmf
)
wait
