#!/usr/bin/perl -w

use strict;
use File::Basename;

my $proto2hmmdefs = check_prog("proto2hmmdefs");

if (@ARGV != 1) {
    print STDERR "Usage: flatstart_hmms.pl <training data dir>\n";
    exit 2;
}

my ($train_data) = @ARGV;

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

my $tmpdir = "tmp";
if (! -d $tmpdir) {
    mkdir $tmpdir;
}

my $current_hmm = 0;

my ($hmm0,$hmm1) = new_hmm();
mkdir $hmm0;

run("cp '$tmpdir/monophones' '$hmm0/hmmlist'");

run("HCompV32 -C $tmpdir/train_config -f 0.01 -m -S $tmpdir/train.scp -M '$hmm0' $tmpdir/proto");

run("cp '$hmm0/hmmlist' '$hmm1/hmmlist'");

run("$proto2hmmdefs $tmpdir/hmm0/proto $hmm0/hmmlist > $tmpdir/hmm1/hmmdefs");


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;
}

sub current_hmm_dir {
    return "$tmpdir/hmm$current_hmm";
}

sub new_hmm {
    my $indir = current_hmm_dir();
    $current_hmm++;
    my $outdir = current_hmm_dir(); 
    mkdir $outdir;
    return ($indir, $outdir);
}

sub run {
    my $command = shift;
    print "$command\n";
    system($command) == 0 || die "Failed: $?";
}
