#!/usr/bin/perl -w

use strict;
use File::Basename;

my $prompts2mlf = check_prog("prompts2mlf");

if (@ARGV != 3) {
    print STDERR "Usage: prompts2lab.pl <out dir> <dictionary> <training utterance file>\n";
    exit 2;
}

my ($out_dir,$dictionary,$train_utts) = @ARGV;

if (! -d $out_dir) {
    print STDERR "Output directory '$out_dir' not found\n";
    exit 2;
}

if (! -f $dictionary) {
    print STDERR "Dictionary '$dictionary' not found\n";
    exit 2;
}

if (! -f $train_utts) {
    print STDERR "Training utterance file '$train_utts' not found\n";
    exit 2;
}

my $tmpdir = "tmp";

# Create a list of all the phones used in the application
# dictionary.

# Make all words upper case and add word-end pauses 
# for each pronunciation.

open MKDICT, ">$tmpdir/mkdict.ded";
print MKDICT<<END;
AS sp
UW
END
close MKDICT;

print "Creating application dictionary...\n";
system "HDMan32 -g $tmpdir/mkdict.ded -m $tmpdir/dict '$dictionary'";


# Translate the list of training utterances to
# a word-level transcription file.

run("$prompts2mlf '$train_utts' > $tmpdir/train_utts_words.mlf");

open MKPHONES0, ">$tmpdir/mkphones0.led";
print MKPHONES0<<END;
EX
IS sil sil
DE sp
END
close MKPHONES0;

# Create a phone-level transcription file from the word-level
# transcriptions and the dictionary. The transcriptions use the 
# first available pronunciation for each word. This problem will
# will be taken care of in later steps.

print STDERR "Creating phone-level MLF file for training utterances...\n";
system "HLEd32 -l $out_dir -d $tmpdir/dict $tmpdir/mkphones0.led $tmpdir/train_utts_words.mlf";


sub run {
    my $command = shift;
    print "$command\n";
    system $command;
}


sub check_prog {
    my $prog_dir = (fileparse($0, qr/\.[^.]*/))[1];
    my $prog = ($prog_dir ne "") ? 
	         (($prog_dir =~ /\/$/) ? $prog_dir.$_[0] : $prog_dir."/".$_[0])
		 : $_[0];

    if (! -x $prog) {
	print STDERR "$prog is not an executable file.\n";
	print STDERR "Maybe you need to run 'make'?\n";
	exit 1;
    }

    return $prog;
}
