#!/usr/local/bin/perl
#
# $Id: label_confuse,v 1.1 1993/08/31 20:41:33 johans Exp $
#
#  mlabel - perl script to relabel the confusion matrix that
#	    noptest produces.
#
#  usage: mlabel [-l file] [-f file] [label1 label2 ...]
#
#  The labels have to be given either by '-l' option
#  or listed after the input file.
#
#

@Labels;
$MatrixFile;


sub PrintUsage {
	print STDERR "usage: mlabel [-l file] [-f file] [label1 label2 ...]\n";
}

sub ReadLabels {
	local( $file ) = @_;

	open( LABEL, $file ) || die "mlabel: $file: $!";

	while( $_ = <LABEL> ) {

		chop;
		if( $_ ne "" ) {
			push( @Labels, $_ );
		}
	}
}

sub Relabel {
	local( @tmp );

	while( $_ = <MATRIX> ) {

		if( /label/ ) {
			last;
		}

		print $_;
	}

	chop;
	@tmp = split;

	shift( @tmp );	# remove label string

	if( $#Labels != $#tmp ) {
		print STDERR "mlabel: number of labels does not match number of columns in confustion matrix\n";
		exit( 1 );
	}

	print "label";

	foreach $k ( @tmp ) {
		printf( " %4s", $Labels[$k-1] );
	}

	print "\n-----";

	foreach $k ( @tmp ) {
		print " ----";
	}

	print "\n";

	$_ = <MATRIX>;	# move past '----- ---- ...' line


	$lc = 0;
	while( $_ = <MATRIX> ) {

		chop;
		@tmp = split( /:/, $_ );
		@val = split(' ', $tmp[1]);
                $tot = 0;
		for($i = 0; $i <= $#val; $i++) {
		 $tot += $val[$i];
		}
                $pc = $val[$lc] * 100.0/$tot;
		printf( "%4s:%s  %2.1f%%\n", $Labels[$tmp[0]-1], $tmp[1], $pc );
	        $lc++;
	}

}

#
# Main Loop
#

while( @ARGV ) {

	if( $ARGV[0] !~ /^-/ ) {
		last;
	}

	$arg = shift( @ARGV );

	if( $arg eq "-l" ) {

		$tmp = shift( @ARGV );
		do ReadLabels( $tmp );

	} elsif( $arg eq "-f" ) {

		$MatrixFile = shift( @ARGV );

	} else {
		print STDERR "mlabel: bad arugment \'$arg\'\n";
		do PrintUsage();
		exit( 1 );
	}


}

if( $#ARGV >= 0 ) {
	if( !defined( @Labels ) ) {

		foreach $k ( @ARGV ) {
			@tmp = split( /\s/, $k ); # work with old style args
			push( @Labels, @tmp );
		}

	} else {

		print STDERR "mlabel: labels given twice\n";
		do PrintUsage();
		exit( 1 );
	}
}

if( !defined( @Labels ) ) {
	print STDERR "mlabel: no labels given\n";
	do PrintUsage();
	exit( 1 );
}

if( defined( $MatrixFile ) ) {

	open( MATRIX, $MatrixFile ) || die "mlabel: $MatrixFile: $!";

} else {
	open( MATRIX, "<&STDIN" ) || die "mlabel: could not dup STDIN: $!";
}

do Relabel();

close( MATRIX );

exit( 0 );
