#!/usr/bin/perl
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 LocalConfiguration;

use StatusManager;
use TargetsManager;
use Logger;
use SplitByParent;

my $SCRIPTNAME = 'create_qa_predictions.pl';

#my $logger = new Logger();

my $targets_manager = new TargetsManager();
my $status_manager = new StatusManager();
my $predictions_manager = new PredictionsManager();
my $groups_manager = new GroupsManager();

my $split_by_parent = new SplitByParent();

my $tmp_QA_directory = "/data/CASP13/tmp_QA/"; #where correspondence files for stage1 resides (e.g., T0758.code_server_corr.txt)
my %serv_corr;

my @group_list = $status_manager->info_group_list();
my @target_list = $status_manager->info_public_target_list();

@group_list = $status_manager->info_all_group_list();
for(my $t_count = 0; $t_count < scalar(@target_list); $t_count++) {

##############
# if($target_list[$t_count]->{NAME} !~ /T064[4-6]/) {next};

 if($targets_manager->is_expired($target_list[$t_count]->{ID}, "human")) {
  my @predictions = $predictions_manager->tarballs_predictions_selected($target_list[$t_count]->{NAME}, '', 'QA');
        
  my $new_dir = sprintf("%s/%s", $LOCAL_CONFIG->{DATA_QA_MODELS_DIR}, $target_list[$t_count]->{NAME});
  my $old_dir = sprintf("%s/%s", $LOCAL_CONFIG->{CLEAN_PREDICTIONS_DIR}, $target_list[$t_count]->{NAME});
  if(!(-e $new_dir)) {
     system(sprintf("mkdir %s", $new_dir));
     system(sprintf("chmod 775 %s", $new_dir));                
  }
  for(my $p_count = 0; $p_count < scalar(@predictions); $p_count++) {            

    my $new_file = sprintf("%s/%s%s%s_%s", $new_dir, $predictions[$p_count]->{TARGET}, $predictions[$p_count]->{PFRMAT}, $predictions[$p_count]->{GROUP_CODE}, $predictions[$p_count]->{MODEL});
    my $old_file = sprintf("%s/%s%s%s_%s", $old_dir, $predictions[$p_count]->{TARGET}, $predictions[$p_count]->{PFRMAT}, $predictions[$p_count]->{GROUP_CODE}, $predictions[$p_count]->{MODEL});

    my $flag = 1;
    if(open(FILE, $old_file)) {
	if(-e $new_file) { system(sprintf("rm -f %s", $new_file));}	
	open(NEW_FILE ,">>$new_file");
	print "$new_file\n";

	if ($predictions[$p_count]->{MODEL} == 1) { #read correspondence for serverxx from auxiliary file
		%serv_corr=();
		my $corr_file=$tmp_QA_directory.$predictions[$p_count]->{TARGET}.".code_server_corr.txt";
		open (CORR, $corr_file) || die "Could not open file to read: $!";
		while(<CORR>) {
		    	chomp;
		      	my ($f1,$f2,$f3) = split/\s+/; 
			$serv_corr{$f3}=$f1;	
		}
		close (CORR);
	}

	while(<FILE>) {
	    my $line = $_;		
		#COMA_TS4 X X
		#rehtnap_TS3 0.26522
	    if ($line =~ /^(\S+)_(.{2})(\d+)\s+(X.*)/ || $line =~ /^(\S+)_(.{2})(\d+)\.pdb\s+(X.*)/) {
		#print "\n $line \n";
		$flag = 0;
	    }elsif($line =~ /^(server\d\d_TS1)\s+(.*)$/ || $line =~ /^(server\d\d_TS1)\.pdb\s+(\S+)/) {
			print NEW_FILE  "$serv_corr{$1} $2\n";
	    }elsif($line =~ /^(\S+)_(.{2})(\d+)\s+(\d+.*)/ || $line =~ /^(\S+)_(.{2})(\d+)\.pdb\s+(\d+.*)/) { #need to add X value 
		$flag=1;
		my $group = $1;
		my $pfrmat = $2;
		my $model = $3;
		#$model =~ s/.pdb//;
		my $other = $4;
		my $code = $groups_manager->get_code_by_name($group);
			
		if($code == 0 ) {
			open(OUT_FILE ,">>error.log");
			print OUT_FILE sprintf("Can not associate %s with DB \n", $group);
			print OUT_FILE sprintf("File: %s \n", $old_file);
			print OUT_FILE sprintf("Line: %s \n", $line);
		} else {			
			$code = sprintf('%03d', $code);
			print NEW_FILE  sprintf("%s%s%s_%s %s\n", $predictions[$p_count]->{TARGET}, $pfrmat, $code, $model, $other);
			#print sprintf("ooo- %s%s%s_%s %s\n", $predictions[$p_count]->{TARGET}, $pfrmat, $code, $model, $other);
		}
	    }elsif($flag || $line =~ /^END\s*/ ) {
			print NEW_FILE sprintf("%s", $line);
	    }
	}
	close(NEW_FILE);
	system(sprintf("chmod a+r %s", $new_file));
	close(FILE);
    } else {
	print sprintf("ERROR: Can't open file %s", $old_file);
	open(OUT_FILE ,">>error1.log");
	print OUT_FILE sprintf("ERROR: Can't open file %s", $old_file);	
    }
		#system(sprintf("cp %s %s", $old_file, $new_file));
                #system(sprintf("chmod a+r %s", $new_file));
  }
 }
}

