#! @PERL@
#
# sample usage: index_trans.pl input_trans.text output_trans.text 
#
# this script indexes the states 
#

# define constants
#
$NUM_ARGS = 1;
$TRANS_FLAG = "\~t";
$TRANS_NUM_TRANS_STR = "num_transitions =";
$DEF_NUM_TRANS = 2;
$DEF_TRANSITION = 0.0;

# define local variables
#
# trans_ind starts with 1 because transitions index for S! and !S are set to
# 0 by default in the  decoder
#
$trans_ind = 0;
$num_trans = 1;

# check for correct number of arguments
#
($#ARGV == ($NUM_ARGS)) || 
    die "Usage: index_trans.pl <input transitions> <output transitions>\n";

$in_trans = $ARGV[0];
$out_trans = $ARGV[1];

# open files
# 
open (in_trans_file, "$in_trans") || die "Cannot open file $in_trans: $!\n";
open (out_trans_file, ">$out_trans") || die "Cannot open file $out_trans: $!\n";


# read the input states file and find the number of states
#
while (<in_trans_file>) {
    
    chop;
    $line = $_;
    
    if ($line =~ $TRANS_FLAG) {
	
	@trans = split (/\s+/, $line);
	if (!defined($transitions{$trans[1]})) {
	    $transitions{$trans[1]} = $num_trans;
	    $num_trans++;
	}
    }
}
close (in_trans_file);
open (in_trans_file, "$in_trans") || die "Cannot open file $in_trans: $!\n";

# write the dummy trans used as start and stop states in models
#
print out_trans_file "$TRANS_NUM_TRANS_STR $num_trans\n\n";
print out_trans_file "$trans_ind\. $DEF_NUM_TRANS\n";
print out_trans_file " $DEF_TRANSITION $DEF_TRANSITION\n";
print out_trans_file " $DEF_TRANSITION $DEF_TRANSITION\n\n";


# read the transitions file and index the transitions
#
while (!eof(in_trans_file)) {

    $line = <in_trans_file>;
    
    if ($line =~ $TRANS_FLAG) {
	
	# get the index of the transition corresponding to its name
	#
	@trans = split (/\s+/, $line);
	$trans_ind = $transitions{$trans[1]};
	
	$line = <in_trans_file>;

    	@num_trans = split (/\s+/, $line);
	
        # write to the transitions file
	#
	print out_trans_file "\n$trans_ind\. $num_trans[1]\n";
	
	# print one the transition matrix
	#
	for ($i = 0; $i < $num_trans[1]; $i++) {
	    $line = <in_trans_file>;
	    print out_trans_file "$line";
	}
    }
}

# close file handles
#
close(in_trans_file);
close(out_trans_file);

# 
# end of script



