#!/usr/local/bin/perl

#  Step #2 in the scoring of Speaker Recognition Evaluations.
#
#          This script takes an output file from Step A
#          (A_separate_orig_sub.sh) and further divides it into
#          Target and Non_target for In and Out of handset training
#          Conditions.
#
#
if ($#ARGV != 1) {
   print "\nusage: B_divide_tar_non_by_hand.sh <sub_file> <key>\n";
   print "                where:  sub_file -> the submission file\n";
   print "                        key ------> male | female KEY\n";
   exit 1;
}

$subfile=$ARGV[0];

# Read in the key
open(KEY,$ARGV[1]) ||
	die("Error, why is it we cannot open the key\n");
@keyinfo=<KEY>;
close(KEY);

    
foreach (@keyinfo) {	
    ($v1, $v2, $v3, $v4, $v5, $v6, $v7, $v8, $v9, $v10, $x) = split;
    $tarray{$v1} = $v5;  # type speaker
    $handray{$v1} = $v10; # handset
    $nsexray{$v1} = $v8; # sex
}

$tarin=join('',$subfile,".tarin");
$tarout=join('',$subfile,".tarout");
$non=join('',$subfile,".non");

open(INFILE,"$subfile") ||
    die("Error: unable to open the submission file '$subfile'\n");
 
open(TARIN,"> $tarin");
open(TAROUT,"> $tarout");
open(NON,"> $non");

while (<INFILE>) { 
 
    ($sex, $trn, $spk, $tst, $seg, $hyp, $scr) = split;
 
#
#   FIRST (IF) TAKES CARE OF TRAINING CONDITION WHERE BOTH CONVERSATIONS
#   ARE USED.  THESE TEST-SEGMENTS ARE FROM THE 2H TEST
    if ($trn eq "2h") {
	if ($tarray{$seg} eq $spk) {
	    if ($handray{$seg} eq "2h:" || $handray{$seg} eq "1h:") {
		print TARIN;
	    } else {
		print TAROUT;
	    }
	} else {
	    print NON;
	}
#
#   THE ELSE TAKES CARE OF THE TRAINING CONDITIONS THAT INVOLVE ONLY
#   ONE CONVERSATION.  THESE TEST-SEGMENTS ARE FROM THE 1H and 1S TEST
    } else {
	if ($tarray{$seg} eq $spk) {
	    if ($handray{$seg} eq "1h:") {
		print TARIN;
	    } else {
		print TAROUT;
	    }
	} else {
	    print NON;
	}
    }
}
close(TARIN);
close(TAROUT);
close(NON);

close(INFILE);
