#! /usr/bin/perl -w

# Script scores2bestZ.pl reads table of raw scores for targets vs  models and calculates Z-scores based on the input score population.
# For multiple NMR structures of the same target (marked as <target>.<n>), only best raw score is chosen. 

my $fin = $ARGV[0];
my $fout = $ARGV[1];

open(FIN, $fin) || die "Cannot open input file $fin : $!\n"; 
my %raw = ();
while(<FIN>) {
	my @fs = split;
	if($#fs != 2) { 
		warn "Weird input line in $fin:\n$_";
		next;
	}
	my $targ=$fs[0];
	my $mod=$fs[1];
	my $score=$fs[2];

	if($targ =~ /\.\d+$/) { # one of several NMR model for the same target

		$targ =~ s/\.\d+$//;
		if( ! defined $raw{$targ}{$mod} || $score > $raw{$targ}{$mod} ) {
			$raw{$targ}{$mod} = $score;
		}

	} else {
		$raw{$targ}{$mod} = $score;
	}
}
close(FIN);



my $sum = 0.0;
my $ntot=0;
for $t(keys %raw) {
	for $m( keys %{$raw{$t}} ) {
		$sum += $raw{$t}{$m};
		$ntot++;
	}
}
my $av = $sum/$ntot;

my $sumdev = 0.0;
for $t(keys %raw) {
	for $m( keys %{$raw{$t}} ) {
		my $d = $raw{$t}{$m} - $av;
		$sumdev += $d*$d;
	}
}
my $sigma = sqrt( $sumdev/$ntot );


# exclude lower than -2 sigma; re-calculate av and sigma
my $score_bar = $av - 2.0*$sigma;
my $sum1 = 0.0;
my $ntot1=0;
for $t(keys %raw) {
	for $m( keys %{$raw{$t}} ) {
		next if $raw{$t}{$m} < $score_bar;
		$sum1 += $raw{$t}{$m};
		$ntot1++;
	}
}
my $av1 = $sum1/$ntot1;

my $sumdev1 = 0.0;
for $t(keys %raw) {
	for $m( keys %{$raw{$t}} ) {
		next if $raw{$t}{$m} < $score_bar;
		my $d1 = $raw{$t}{$m} - $av1;
		$sumdev1 += $d1*$d1;
	}
}
my $sigma1 = sqrt( $sumdev1/$ntot1 );




open(FOUT, "> $fout") || die "Cannot open output $fout\n"; 
for $t(sort keys %raw) {
	for $m(sort keys %{$raw{$t}} ) {
		my $z = ($raw{$t}{$m} - $av1) * (1.0/$sigma1);
		print FOUT "$t\t$m\t";
		printf FOUT "%.3f\t%.3f\n", $raw{$t}{$m}, $z;
	}
}
close(FOUT);
