#!/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 @group_list = $status_manager->info_group_list();
my @target_list = $status_manager->info_public_target_list();
#


#CREATE ALL (by human expired) TARBALLS

@group_list = $status_manager->info_all_group_list();
for(my $t_count = 0; $t_count < scalar(@target_list); $t_count++) {
    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 $tarball_name = sprintf("%s.tar.gz", $target_list[$t_count]->{NAME});
        
##       my $download_area = sprintf("/data/CASP8/TARBALLS/predictions/%s", $tarball_name);
##        if (!(-e $download_area)) {
            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]->{GROUP}, $predictions[$p_count]->{PFRMAT}, $predictions[$p_count]->{MODEL}, (($predictions[$p_count]->{PFRMAT} eq "AL")?".pdb":""));

    my $flag = 1;
    if(open(FILE, $old_file)) {
	if(-e $new_file) { system(sprintf("rm -f %s", $new_file));}	
	open(NEW_FILE ,">>$new_file");
	while(<FILE>) {
	    my $line = $_;		
		#COMA_TS4 X X
		#rehtnap_TS3 0.26522
		#SAM-T02-server_AL1.pdb 0.27084
	    if ($line =~ /^(\S+)_(.{2})(\d+)\s+(X.*)/ || $line =~ /^(\S+)_(.{2})(\d+)\.pdb\s+(X.*)/) {
		print "\n $line \n";
		$flag = 0;
	    }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);
		}
	    } 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));
                
                
                
                
            }
            
            #system(sprintf("cd %s; tar -czf %s %s", $LOCAL_CONFIG->{TARBALLS_ALL_PREDICTIONS_DIR}, $tarball_name, $target_list[$t_count]->{NAME}));
            
            #system(sprintf("mv %s/%s %s", $LOCAL_CONFIG->{TARBALLS_ALL_PREDICTIONS_DIR}, $tarball_name, $download_area));
        }
        #/www/download_area/CASP8/server_predictions        
 ##   }     
}










#my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);        
#my $date = sprintf("%s\/%s\/%s  %s:%s",($mon+1), $mday, $hour, $min, $sec);
#
#
#print $date."\n";

