#!/usr/bin/perl

use strict;
use warnings;

my $RESDIR = "/local/CASP13/RESULTS/RAND/LGA/SDA/DATA/";
my @TARGETS;

my $RES_FILE = "/local/CASP13/tmp_Grishin/Summary_RandomModels.gdt_ts.csv";

my $DEBUG = 0;

if (!defined ($ARGV[0])){
   &readTargets();
   if (-e $RES_FILE){
	unlink($RES_FILE);
   }
} else {
   my $target = $ARGV[0];
   if (! -d "$RESDIR/$target"){
	&usage();
   }
   @TARGETS = ();
   push @TARGETS, $target ;
}

open OUT, ">> $RES_FILE";
foreach my $t (@TARGETS){
#   print $t."\n";
   printf OUT "%-10s  %5.3f\n", $t, &process($t);
}

close OUT;
exit;

sub process{
    my $target = shift;
    my $count = 0;
    my $comb_gdt_ts = 0;
    my $resdir = "$RESDIR/$target";
    opendir D, "$resdir";
    while(defined (my $f = readdir(D))){
	next unless $f =~ m/^$target/;
	open F , "grep -E 'SUMMARY\\(GDT\\)' $resdir/$f | ";
	   my $line = <F>;
	   $line =~ s/^\s+//;
	   $line =~ s/\s+$//;
	   if ($line =~ m/^SUMMARY/){
		my @tokens = split(/\s+/, $line);
		$comb_gdt_ts += $tokens[6];
		if ($DEBUG) {print "$f\t".$tokens[6]."\n";}
		$count++;
	   }
	close F;
    }
    close D;
    if ($count != 0){
	return ($comb_gdt_ts/$count);
    } else {
	return 0.0;
    }
}




sub usage{
   print "USAGE: $0 [<TARGET>]\n";
   print "Script generates summary of the results lga run over all random model.\n";
   print "The script checks if the result files are present:
        at directory $RESDIR/<TARGET>";
   print "The pipeline consists of three blocks:\n
        Grishin_genRandomModels.pl - generate random models;
        Grishin_evalRandomModels.pl - send random models for evaluation;
        Grishin_genSumaryRandomModels.pl - this script;\n";
   exit;
}

sub readTargets {
    opendir D, $RESDIR;
    while(defined(my $d = readdir(D))){
	if (-d "$RESDIR/$d" && $d =~ m/^T0/){
		push @TARGETS, $d;
	}
    }
    closedir D;
    @TARGETS = sort @TARGETS;
} 
