#!/usr/bin/perl

# This is the main program that should be run first to
# 1. Upload QA predictions to the DB 
# 2. Perform correlation analysis separately for QA models 1 and 2
# 3. Calculate z-scores on correlation for QA1 (global analysis)

use strict;
use warnings;

use Digest::MD5 qw(md5 md5_hex md5_base64);
#use MIME::Parser;
#use MIME::Entity;
#use MIME::Body;
use Getopt::Long;


use lib qw(Core);
use lib qw(Classes);
use ImagesManager;
use ResultsManager;
use ResultsTargetManager;
use ResultsUploadManager;

use Logger;

my $SCRIPTNAME = 'qa_MAIN_parce_upload.pl';

my $logger = new Logger();

my $directory = "";
my @FILES_LIST = ();
my $count_files = 0;


my $results_manager = new ResultsManager();
my $results_target_manager = new ResultsTargetManager();
my $resultsupload_manager = new ResultsUploadManager();

my $TARGET = "";
my $target_list = 'conf/QA_all';
my $isparams = GetOptions(
	"list|l=s"         => \$target_list	
);

open (TL, $target_list) || die "Cannot open input file $target_list: $!";
while(my $TARGET = <TL>) {
	if ($TARGET =~ /^#/){next;}
        $TARGET=~s/\s+$//;

	##############QA PREDICTIONS
	$directory = "/data/CASP13/predictions/qa_predictions_cleaned/$TARGET";

	$logger->info($SCRIPTNAME, sprintf("Start to upload TARGET!: %s", $TARGET));

	##############QA PREDICTIONS PARCE
	@FILES_LIST = ();
	if(open(FILE_list_of_results, "/bin/ls " . $directory. "/* |")) {
		@FILES_LIST = <FILE_list_of_results>;
		close (FILE_list_of_results);
	}
	$count_files = 0;

	foreach my $line (@FILES_LIST) {
		$count_files ++;	
		$line =~ /$directory\/(.*)/;
		my $file_name = $1;
		$resultsupload_manager->upload_qa_load_to_DB($file_name, $directory);
		print "File #" . $count_files . "\n";
	}

	##############QA PREDICTIONS PARCE
	$logger->info($SCRIPTNAME, sprintf("Analyze TARGET!: %s", $TARGET));
	$resultsupload_manager->upload_qa_analysis($TARGET,2);
	$resultsupload_manager->upload_qa_analysis($TARGET,1);

	##############QA PREDICTIONS PARCE
	$logger->info($SCRIPTNAME, sprintf("QA2 analyze TARGET!: %s", $TARGET));
	$resultsupload_manager->upload_qa2_pearson_analysis($TARGET,2);
	$resultsupload_manager->upload_qa2_pearson_analysis($TARGET,1);

####END
	$logger->info($SCRIPTNAME, sprintf("END TARGET!: %s", $TARGET));


}


exit(0);
