package MultimerResultsEmmUploadManager;

use strict;
use warnings;

use DBI;

use lib qw(Core);
use lib qw(Classes);

use Database;

use Configuration;
use LocalConfiguration;

use MultimerResultsEmmManager;

my $resultsupload_manager = undef;

#Regexp definition for parsing:
my $FILE_NAME_FORMAT_EM = "^((.{5,})(TS)([0-9]{3})_[0-9]{1,2}(o(_trm){0,1}){0,1})\.";
my $FILE_NAME_FORMAT_EM2 = "^((.{5,}(o(_trm){0,1}){0,1})\.pdb)"; # for target vs map evaluation


sub new {
    my ($class) = @_;

    return $resultsupload_manager if(defined($resultsupload_manager));

    my $self = {
        _id => undef,
        _database => Database->new($CONFIG->{HOSTNAME}, $CONFIG->{PORT}, $CONFIG->{DATABASE}, $CONFIG->{USERNAME}, $CONFIG->{PASSWORD})
    };

    $resultsupload_manager = bless $self, $class;
    return $resultsupload_manager;
}

sub parce_filename {
    my ($self, $file_name, %model) = @_;
    # The format file name should be
    print "FILE " . $file_name ."\n";
    if ($file_name=~/$FILE_NAME_FORMAT_EM/) {
	$model{MODEL_NAME} = $1;
        $model{TARGET} = $2;
        $model{PFRMAT} = $3;
        $model{CODE} = $4;
	my $o = $5;
	if (defined($o)){
		$model{TARGET} .= $o;
	}
    } elsif ($file_name=~/$FILE_NAME_FORMAT_EM2/) {
	$model{MODEL_NAME} = $1;
	$model{TARGET} = $2;
	$model{PFRMAT} = '';
	$model{CODE} = -1;
    }
    return %model;
}

sub upload_TemPy{
    my ($self, $file_name, $dir) = @_;
    my $results_manager = new MultimerResultsEmmManager();
    my %model = $results_manager->get_new_model();
    %model = $self->parce_filename($file_name, %model);
    my $file = sprintf("%s/%s", $dir, $file_name);
    if (open F, "< $file"){
      my $flag = 0;
      my $ccc_per_chain = '';
      my %ccc_per_chain_hash;
      while( my $l = <F> ){
	if ($l =~ m/^resol/) {
	   $flag = 1; next;
	}
	if ($flag == 1) {
	  #targetmap resol ENV MI LAP CCC
	  my ($targetmap, $resol, $env, $mi, $lap, $ccc) =  split(/\s+/, $l);
	  #$model{map_emd_no} = $self->parce_emd_no($targetmap);
	  $model{resol} = sprintf("%.1f", $resol);
	  $model{env} = $env;
	  $model{mi} = $mi;
	  $model{lap} = $lap;
          $model{ccc} = $ccc;
	  $flag = 0;
        }
	if ($l =~ m/^Per\s+chain/){
	   $flag = 2;
	   next;
	}
        # ** Mean SMOC for T0984o.pdb is 0.76972046595
        if ($l =~ m/^\*\*\s+Mean\s+SMOC\s+for\s+\S+\s+is\s+(\S+)/) {
            $model{smoc} = $1;
        }
	if ($flag == 2) {
	   my $model_name = $model{MODEL_NAME};
	   if ( $l =~ m/$model_name\s+(\S+)\s+avg\s+(\S+)/ ) {
		my $chain = $1; my $score = $2;
		$ccc_per_chain .= "$chain:$score ";
		$ccc_per_chain_hash{$chain} = $score;
	   } elsif ( $l =~ m/$model_name\s+avg\s+(\S+)/ ) {
                my $chain = '-'; my $score = $1;
                $ccc_per_chain .= "$chain:$score ";
                $ccc_per_chain_hash{$chain} = $score;
           }
	}
	if ( $l =~ m/^Per\s+residue/ ) {
		$model{ccc_per_chain} = $ccc_per_chain;
		last;
	}
      }
      close F;
      my $id = $results_manager->exist_by_parameters(%model);
      if (defined($id) && $id > 0){
	    $model{id} = $id;
	    $results_manager->update_results(%model);
      } else {
	    $model{id} = $results_manager->add(%model);
      }
      # add alignment
      my %hash_alignment = $self->parse_tempy_alignment($file);
      foreach my $chain (sort keys %hash_alignment) {
                $results_manager->add_alignment($model{id}, $chain, $hash_alignment{$chain}, 'tempy', $ccc_per_chain_hash{$chain});
      }
    } else {
	print "Failed upload results for TemPy: the file doesn't exist\n$file\n";
    }
}

sub upload_TemPy_OV_scores{
    my ($self, $file_name, $dir) = @_;
    my $results_manager = new MultimerResultsEmmManager();
    my %model = $results_manager->get_new_model();
    %model = $self->parce_filename($file_name, %model);
    my $file = sprintf("%s/%s", $dir, $file_name);
    if (open F, "< $file"){
      my $l = <F>; # skip header
      $l = <F>;
      if ($l =~ m/^(\S+),(\S+),(\S+)$/ ) {
	my $ccc_ov = $2; my $mi_ov = $3;
	$model{ccc_ov} = $ccc_ov;
	$model{mi_ov} = $mi_ov;
      }
      close F;
      my $id = $results_manager->exist_by_parameters(%model);
      if (defined($id) && $id > 0){
            $model{id} = $id;
            $results_manager->update_results(%model);
      } else {
            #$model{id} = $results_manager->add(%model);
      }
    } else {
        print "Failed upload results for TemPy: the file doesn't exist\n$file\n";
    }
}

sub upload_TemPy_ccc_mask {
    my ($self, $file_name, $dir) = @_;
    my $results_manager = new MultimerResultsEmmManager();
    my %model = $results_manager->get_new_model();
    %model = $self->parce_filename($file_name, %model);
    my $file = sprintf("%s/%s", $dir, $file_name);
    if (open F, "< $file") {
      my $l = <F>; 
      if ($l =~ m/^(\S+)$/) {
        my $ccc_mask = $1;
        $model{ccc_mask} = $ccc_mask;
      }
      close F;
      my $id = $results_manager->exist_by_parameters(%model);
      if (defined($id) && $id > 0) {
            $model{id} = $id;
            $results_manager->update_results(%model);
      } else {
            #$model{id} = $results_manager->add(%model);
      }
    } else {
        print "Failed upload results for TemPy: the file doesn't exist\n$file\n";
    }
}

sub upload_TemPy_smoc{
    my ($self, $file_name, $dir) = @_;
    my $results_manager = new MultimerResultsEmmManager();
    my %model = $results_manager->get_new_model();
    %model = $self->parce_filename($file_name, %model);
    my $file = sprintf("%s/%s", $dir, $file_name);
    if (open F, "< $file"){
      my $flag = 0;
      my $smoc_d_per_chain = '';
      my %smoc_d_per_chain_hash;
      while( my $l = <F> ){
        if ($l =~ m/^Per\s+chain/) {
           $flag = 2;
           next;
        }
        if ($flag == 2) {
           my $model_name = $model{MODEL_NAME};
           if ( $l =~ m/$model_name\s+(\S+)\s+avg\s+(\S+)/ ) {
                my $chain = $1; my $score = $2;
                $smoc_d_per_chain .= "$chain:$score ";
                $smoc_d_per_chain_hash{$chain} = $score;
           } elsif ( $l =~ m/$model_name\s+avg\s+(\S+)/ ) {
                my $chain = '-'; my $score = $1;
                $smoc_d_per_chain .= "$chain:$score ";
                $smoc_d_per_chain_hash{$chain} = $score;
           }
	   # ** Mean SMOC for T0984o.pdb is 0.76972046595
	   if ($l =~ m/^\*\*\s+Mean\s+SMOC\s+for\s+\S+\s+is\s+(\S+)/) {
		$model{smoc_d} = $1;
	   }
        }
        if ( $l =~ m/^Per\s+residue/ ) {
                $model{smoc_d_per_chain} = $smoc_d_per_chain;
                last;
        }
      }
      close F;
      my $id = $results_manager->exist_by_parameters(%model);
      if (defined($id) && $id > 0){
            $model{id} = $id;
            $results_manager->update_results(%model);
      } else {
            $model{id} = $results_manager->add(%model);
      }
      # add alignment
      my %hash_alignment = $self->parse_tempy_alignment($file);
      foreach my $chain (sort keys %hash_alignment) {
         $results_manager->add_alignment($model{id}, $chain, $hash_alignment{$chain}, 'smoc_d', $smoc_d_per_chain_hash{$chain});
      }
    } else {
        print "Failed upload results for TemPy: the file doesn't exist\n$file\n";
    }
}


# upload model statistics 
# from phenix output
sub upload_model_stat {
    my ($self, $file_name, $dir) = @_;
    my $results_manager = new MultimerResultsEmmManager();
    my %model = $results_manager->get_new_model();
    %model = $self->parce_filename($file_name, %model);
#    $model{map_emd_no} = $self->parce_emd_no($file_name);
    my $file = sprintf("%s/%s", $dir, $file_name);
    if (open F, "< $file"){
	my $flag = 0; # trigger-indicator
	my $tmp_bonds = "";
	my $tmp_angles = "";
	my $tmp_dists = "";
	my $tmp_adps = "";
	while(my $l = <F>){
	   if ($l =~ m/^\s*bond\s+:\s+(\S+)\s+(\S+)\s+(\d+)/i){
		$model{bond_rmsd} = $1;
		$model{bond_max} = $2;
		$model{bond_count} = $3;
		next;
	   }
	   if ($l =~ m/^\s*angle\s+:\s+(\S+)\s+(\S+)\s+(\d+)/i){
                $model{angle_rmsd} = $1;
                $model{angle_max} = $2;
                $model{angle_count} = $3;
                next;
           }
	   if ($l =~ m/^\s*chirality\s+:\s+(\S+)\s+(\S+)\s+(\d+)/i){
                $model{chiral_rmsd} = $1;
                $model{chiral_max} = $2;
                $model{chiral_count} = $3;
                next;
           }
	   if ($l =~ m/^\s*planarity\s+:\s+(\S+)\s+(\S+)\s+(\d+)/i){
                $model{planar_rmsd} = $1;
                $model{planar_max} = $2;
                $model{planar_count} = $3;
                next;
           }
	   if ($l =~ m/^\s*dihedral\s+:\s+(\S+)\s+(\S+)\s+(\d+)/i){
                $model{dihedr_rmsd} = $1;
                $model{dihedr_max} = $2;
                $model{dihedr_count} = $3;
                next;
           }
	   if ($l =~ m/^\s*all-atom\s+clashscore\s+:\s+(\S+)/i){
                $model{mp_clash} = $1;
                next;
           }
	   if ($l =~ m/^\s*ramachandran\s+plot\s*:/i) {
		$flag = 1;
		next;
	   }
	   if ($flag == 1 ){
		if ($l =~ m/^\s*outliers\s+:\s+(\S+)/i) {
		   $model{mp_ram_out} = $1;
		} elsif ($l =~ m/^\s*favored\s+:\s+(\S+)/i) {
		   $model{mp_ram_fv} = $1;
		   $flag = 0;
		   next;
		}
	   }
	   if ($l =~ m/^\s*rotamer\s+outliers\s+:\s+(\S+)/i) {
		$model{mp_rot_out} = $1;
		next;
	   }
	   if ($l =~ m/^\s+Histogram\s+.*bond\s+lengths/i){
		$flag = 2;
		next;
	   }
	   if ($flag == 2) {
		my $tmp = "";
		if ($l =~ m/^\s*[0-9]+\.[0-9]+\s+-\s+([0-9]+\.[0-9]+)\s+:\s+(\d+)/) {
			$tmp = sprintf ("%s:%d", $1, $2);
			$tmp_bonds .= "$tmp ";
		}
	   }
	   if ($l =~ m/^\s+Histogram\s+bond\s+angle\s+.*ideal/i){
                $flag = 3;
                next;
           }
           if ($flag == 3) {
                my $tmp = "";
                if ($l =~ m/^\s*[0-9]+\.[0-9]+\s+-\s+([0-9]+\.[0-9]+)\s+:\s+(\d+)/) {
                        $tmp = sprintf ("%s:%d", $1, $2);
                        $tmp_angles .= "$tmp ";
                }
           }
	   if ($l =~ m/^\s+Histogram\s+.*nonbonded\s+.*distances/i){
                $flag = 4;
                next;
           }
           if ($flag == 4) {
                my $tmp = "";
                if ($l =~ m/^\s*[0-9]+\.[0-9]+\s+-\s+([0-9]+\.[0-9]+)\s+:\s+(\d+)/) {
                        $tmp = sprintf ("%s:%d", $1, $2);
                        $tmp_dists .= "$tmp ";
                }
           }
	   if ($l =~ m/^\s*-{1,}Histogram\s+.*ADPs/i){
                $flag = 5;
                next;
           }
           if ($flag == 5) {
                my $tmp = "";
                if ($l =~ m/^\s*[0-9]+\.[0-9]+\s+-\s+([0-9]+\.[0-9]+)\s+:\s+(\d+)/) {
                        $tmp = sprintf ("%s:%d", $1, $2);
                        $tmp_adps .= "$tmp ";
                }
		if ($l =~ m/^-+$/){
		   last;
		}
           }
	}
	close F;
	$tmp_bonds =~ s/\s+$//; $model{dev_bonds} = $tmp_bonds;
	$tmp_angles =~ s/\s+$//; $model{dev_angles} = $tmp_angles;
	$tmp_dists =~ s/\s+$//; $model{dev_dists} = $tmp_dists;
	$tmp_adps =~ s/\s+$//; $model{dev_adps} = $tmp_adps;
	my $id = $results_manager->exist_by_parameters(%model);
            if (defined($id) && $id > 0){
                $model{id} = $id;
                $results_manager->update_results(%model);
            } else {
                $results_manager->add(%model);
            }

    }
}

sub upload_phenix {
    my ($self, $file_name, $dir) = @_;
    my $results_manager = new MultimerResultsEmmManager();
    my %model = $results_manager->get_new_model();
    %model = $self->parce_filename($file_name, %model);
#    $model{map_emd_no} = $self->parce_emd_no($file_name);
    my $file = sprintf("%s/%s", $dir, $file_name);
    if (open F, "< $file"){
	my $resol_flag = 0; # flag-triger for resolution
	my $fsc_flag = 0;
	my $box_cc_flag = 0;
	my $fsc_bin = "";
	my $box_cc_per_chain = "";
        my %box_cc_per_chain_hash;
	my %done_chains ;
        while (defined(my $l = <F>)){
	    # resolution
	    if ($l =~ m/^Map\s+resolution/){
		$resol_flag = 1;
		next;
	    }
	    if ($resol_flag == 1 && $l =~ m/d_min:\s+(\S+)/){
		my $resol = $1;
		$model{resol} = sprintf("%.1f", $resol);
		$resol_flag = 0;
		next;
	    }
	    # fsc
	    if ($l =~ m/(^Model-map\s+FSC|^Map-model\s+FSC)/){
		$fsc_flag = 1;
		next;
	    }
	    if ($fsc_flag == 1 && $l =~ m/OVERALL.*:\s+(\S+)/i){
		my $fsc = $1;
		$model{fsc} = $fsc;
		next;
	    }
	    if ($fsc_flag == 1 && $l =~ m/BIN/i){
		$fsc_flag = 2;
		next;
	    }
	    if ($fsc_flag == 2) {
		# BIN# RESOLUTION (A)     CC
		#  0: 256.800-71.224   0.8900
		if ($l =~ m/\S+\s+[0-9]+\.[0-9]+-([0-9]+\.[0-9]+)\s+(\S+)/){
			$fsc_bin .= "$1:$2 ";
		}
	    }
	    if ($fsc_flag == 2 && $l =~ m/^------------/) {
		$fsc_bin =~ s/\s+$//;
		$model{fsc_bins} = $fsc_bin;
		$model{resol_fsc05} = $self->calc_resol_fsc05($fsc_bin);
		$fsc_flag = 0;
		next;
	    }
	    # box_cc
	    if ($l =~ m/Map-model\s+CC\s+\(overall\)/){
		$box_cc_flag = 1;
		next;
	    }
	    if ($box_cc_flag == 1 && $l =~ m/CC_mask.*:\s+(\S+)/){
                my $box_cc = $1;
                $model{cc_mask} = $box_cc;
                #$box_cc_flag = 2;
                next;
            }
	    if ($box_cc_flag == 1 && $l =~ m/CC_volume.*:\s+(\S+)/){
		my $box_cc = $1;
		$model{cc_volume} = $box_cc;
		#$box_cc_flag = 2;
		next;
	    }
	    if ($box_cc_flag == 1 && $l =~ m/CC_peak.*:\s+(\S+)/){
                my $box_cc = $1;
                $model{cc_peak} = $box_cc;
                #$box_cc_flag = 2;
                next;
            }
	    if ($box_cc_flag == 1 && $l =~ m/Per\s+chain:\s*$/){
		$box_cc_flag = 2;
		next;
	    }
	    if ($box_cc_flag == 2 && $l =~ m/\s*chain\s+(\S+):\s+(\S+)/){
		my $chain = $1; my $score = $2;
		if (!exists $done_chains{$chain}){
			$box_cc_per_chain .= "$chain:$score ";
			$done_chains{$chain} = 1;
			$box_cc_per_chain_hash{$chain} = $score;
		}
	    } elsif ($box_cc_flag == 2 && $l =~ m/\s*chain\s+:\s+(\S+)/){
                my $chain = '-'; my $score = $1;
                if (!exists $done_chains{$chain}){
                        $box_cc_per_chain .= "$chain:$score ";
                        $done_chains{$chain} = 1;
                        $box_cc_per_chain_hash{$chain} = $score;
                }
            }
	    if ($box_cc_flag == 2 && $l =~ m/Per\s+residue\s+\(histogram\)/){
		$box_cc_per_chain =~ s/\s+$//;
		$model{box_cc_per_chain} = $box_cc_per_chain;
		$box_cc_flag = 0;
		last;
	    }
	    if ($l =~ m/Per\s+residue\s+\(histogram\)/){
		$box_cc_flag = 0;
		last;
	    }
        }
	close F;
	my $id = $results_manager->exist_by_parameters(%model);
            if (defined($id) && $id > 0){
                $model{id} = $id;
                $results_manager->update_results(%model);
            } else {
                $results_manager->add(%model);
            }
        # add alignment
	my %hash_alignment = $self->parse_phenix_alignment($file);
	foreach my $chain (sort keys %hash_alignment) {
		$results_manager->add_alignment($model{id}, $chain, $hash_alignment{$chain}, 'phenix', $box_cc_per_chain_hash{$chain});
	}
    } else {
        print "Failed upload results for PHENIX: the file doesn't exist\n$file\n";
    }
}

# method calculates the cooresponding resolution 
# at the value of the fsc score = 0.5
# the method uses linear interpolation
sub calc_resol_fsc05{
    my ($self, $fsc_bin) = @_;
    my $res = undef;
    my $x1 = undef; my $y1 = undef; my $x2 = undef; my $y2 = undef;
    my $resol = undef; my $fsc = undef;
    foreach my $pair (split(/\s+/, $fsc_bin)){
	if ($pair =~ m/(-{0,1}\d+\.\d+):(-{0,1}\d+\.\d+)/){
		$resol = $1;  $fsc = $2;
		if ( !defined($x1) && !defined($y1) ){
			if ($fsc < 0.5) {
				$res = sprintf("> %.3f", $resol);
			} elsif ($fsc > 0.5) {
				$res = sprintf("< %.3f", $resol);
			}
			$x1 = $fsc; $y1 = $resol;
			next;
		}
		$x2 = $x1; $y2 = $y1;
		$x1 = $fsc; $y1 = $resol;
		if (($x1 - 0.5)*($x2 - 0.5) <= 0) {
			$res = sprintf("%.3f", $y2 + (0.5-$x2)*($y1-$y2)/($x1-$x2));
			last;
		}
	}
    }
    if ($res =~ m/^</ && defined($resol)) {
	$res = sprintf("< %.3f", $resol);
    }
    return $res;
}

# the method parses the emd_id from word
# the emd_id can be encoded in file name or in first word of a line in the file
sub parce_emd_no{
    my ($self, $word) = @_;
    if ($word =~ m/(emd[_-]\d{4,4})/i){
	return lc($1);
    }
    return undef;
}

sub parse_phenix_alignment {
    my ($self, $file) = @_;
    my %hash;
    if (open F1, "$file"){
        while(defined(my $l = <F1>)){
	  # chain id: N resid  267 : 0.8074
	  if ($l =~ m/chain\s+id:\s+(\S+)\s+resid\s+(\d+)\s+:\s+(-{0,1}[0-9]+\.[0-9]+)/){
		my $chain = $1;
		my $resno = $2;
		my $cc = $3;
	  	if (! exists $hash{$chain}) {
	             $hash{$chain} = "";
	          }
	          $hash{$chain} .= "$resno:$cc ";
	  } elsif ($l =~ m/chain\s+id:\s+resid\s+(\d+)\s+:\s+(-{0,1}[0-9]+\.[0-9]+)/){
                my $chain = '-';
                my $resno = $1;
                my $cc = $2;
                if (! exists $hash{$chain}) {
                     $hash{$chain} = "";
                  }
                  $hash{$chain} .= "$resno:$cc ";
          }
        }
        close(F1);
    }
    return %hash;
}

sub parse_phenix_alignment_old_format {
    my ($self, $file) = @_;
    my %hash;
    if (open F, "$file"){
	my $flag = 0;
	while(defined(my $l = <F>)){
	   if ($l =~ m/^Per\s+residue/){
		$flag = 1;
		next;
	   }
	   if ($flag > 0 && $flag < 3){
		$flag++;
		next;
	   }
	   if ($flag == 3){
		# A,ALA,3  0.274   1.72   3.79  1.699   0.01   2.18 EXCEPTION   VALID   VALID
		if ($l =~ m/^\s*(\S+),(\S+),(\S+)\s+(\S+)/){
		    my $chain = $1; my $res = $2; my $resno = $3; my $cc = $4;
		    if ($res =~ m/HOH/) {next;}
		    if (! exists $hash{$chain})	{
			$hash{$chain} = "";
		    }
		    $hash{$chain} .= "$resno:$cc ";
		}
	   }
	}
	close(F);
    }
    return %hash;
}

sub parse_tempy_alignment {
    my ($self, $file) = @_;
    my %hash;
    if (open F, "$file"){
        my $flag = 0;
        while(defined(my $l = <F>)){
           if ($l =~ m/^Per\s+residue/){
                $flag = 1;
                next;
           }
           if ($flag == 1){
                #Z       1       0.79
                if ($l =~ m/^(\S+)\s+(\S+)\s+(\S+)/){
                    my $chain = $1; my $resno = $2; my $score = $3;
                    if (! exists $hash{$chain}) {
                        $hash{$chain} = "";
                    }
                    $hash{$chain} .= "$resno:$score ";
                } elsif ($l =~ m/^\s+(\S+)\s+(\S+)/) {
		    my $chain = '-'; my $resno = $1; my $score = $2;
                    if (! exists $hash{$chain}) {
                        $hash{$chain} = "";
                    }
		    $hash{$chain} .= "$resno:$score ";
		}
           }
        }
        close(F);
    }
    return %hash;
}

sub upload_emringer {
    my ($self, $file_name, $dir) = @_;
    my $results_manager = new MultimerResultsEmmManager();
    my %model = $results_manager->get_new_model();
    %model = $self->parce_filename($file_name, %model);
    #$model{map_emd_no} = $self->parce_emd_no($file_name);
    my $file = sprintf("%s/%s", $dir, $file_name);
    if (open F, "< $file"){
	while (my $l = <F>) {
		if ($l =~ m/^EMRinger\s+Score:\s+(\S+)/){
			$model{emringer} = $1;
			last;
		}
	}
	close(F);
	my $id = $results_manager->exist_by_parameters(%model);
        if (defined($id) && $id > 0){
            $model{id} = $id;
            $results_manager->update_results(%model);
        } else {
            $results_manager->add(%model);
        }
	# add alignment
	my $plotdir = $file;
	$plotdir =~ s/\.emringer$/_emringer_plots/;
        my %hash_alignment = $self->parse_emringer_alignment($plotdir);
        foreach my $chain (sort keys %hash_alignment) {
                $results_manager->add_alignment($model{id}, $chain, $hash_alignment{$chain}, 'emringer', $model{emringer});
        }

    } else {
	print "Failed upload results for PHENIX: the file doesn't exist\n$file\n";
    }
}

sub parse_emringer_alignment {
    my ($self, $dir) = @_;
    my %hash;
    my %hash2;
    opendir D, $dir;
    my @chain_files;
    while(defined(my $f = readdir(D))){
	if ($f =~ m/_rolling\.csv/){
	    push @chain_files, $f;
	}
    }
    closedir(D);
    foreach my $f (@chain_files){
	my $chain;
	if ($f =~ m/(\S+)_rolling\.csv$/) {
	   $chain = $1;
	} elsif ($f =~ m/^_rolling\.csv$/) {
           $chain = '-';
        } 
	my $file = sprintf("%s/%s", $dir, $f);
	if (open F1, "< $file") {
	   my $l = <F1>; # skip header
           my $str = ""; my $str2 = "";
	   while (defined($l = <F1>)) {
		if ($l =~ m/(\S+),(\S+),(\S+)/) {
			my $res = $1; my $y = $2; my $y2 = $3;
			$str .= sprintf("%d:%.4f ", $res, $y);
			$str2 .= sprintf("%d:%.4f ", $res, $y2);
		}
	   }
	   close(F1);
	   $hash{$chain} = $str;
	   $hash2{$chain} = $str2;
	}
    }
    return %hash;
}


sub upload_modelmap_match{
    my ($self, $file_name, $dir) = @_;
    my $results_manager = new MultimerResultsEmmManager();
    my %model = $results_manager->get_new_model();
    my $file = sprintf("%s/%s", $dir, $file_name);
    %model = $self->parce_filename($file_name, %model);
#    $model{map_emd_no} = $self->parce_emd_no($file_name);
    if (open F, "< $file"){
        while (my $l = <F>) {
		$l =~ s/^\s+//; $l =~ s/\s+$//;
		if ($l !~ m/$FILE_NAME_FORMAT_EM/) {
			next;
		}
		#               ----ALL RESIDUES----     CLOSE RESIDUES ONLY
		#     MODEL     --CLOSE-    ---FAR--    FORWARD REVERSE MIXED  CA                   SEQ
		#               RMSD   N    RMSD   N       N       N      N   SCORE  SEQ MATCH(%)  SCORE
		#  T0007EM130_4 1.00  867    8.7   85    675      69     123  871.2    32.2        279
		my @tokens = split(/\s+/, $l);
		$model{n_close} = $tokens[2];
		$model{n_far} = $tokens[4];
		$model{ca_score} = $tokens[8];
		$model{seq_match} = $tokens[9];
	        my $id = $results_manager->exist_by_parameters(%model);
	        if (defined($id) && $id > 0){
         		$model{id} = $id;
	                $results_manager->update_results(%model);
	        } else {
	                $results_manager->add(%model);
            	}

        }
        close(F);
    } else {
        print "Failed upload results for PHENIX: the file doesn't exist\n$file\n";
    }
}

sub upload_chain_comparison {
    my ($self, $file_name, $dir) = @_;
    my $results_manager = new MultimerResultsEmmManager();
    my %model = $results_manager->get_new_model();
    my $file = sprintf("%s/%s", $dir, $file_name);
    %model = $self->parce_filename($file_name, %model);
#    $model{map_emd_no} = $self->parce_emd_no($file_name);
    if (open F, "< $file") {
        while (my $l = <F>) {
                $l =~ s/^\s+//; $l =~ s/\s+$//;
                if ($l !~ m/^Unique_target/ && $l !~ m/Entire_target/) { next;}
		#               ----ALL RESIDUES---  CLOSE RESIDUES ONLY    %
		#     MODEL     --CLOSE-    --FAR-- FORWARD REVERSE MIXED FOUND  CA                  SEQ
		#               RMSD   N      N       N       N      N          SCORE  SEQ MATCH(%)  SCORE  MEAN LENGTH
		#
		# Unique_target 1.93  403    921    278      12     113   65.0   0.34    69.2        0.45    9.6
                my @tokens = split(/\s+/, $l);
                $model{n_close} = $tokens[2];
                $model{n_far} = $tokens[3];
                $model{ca_score} = $tokens[8];
                $model{seq_match} = $tokens[9];
                my $id = $results_manager->exist_by_parameters(%model);
                if (defined($id) && $id > 0) {
                        $model{id} = $id;
                        $results_manager->update_results(%model);
                } else {
                        $results_manager->add(%model);
                }
		last;
        }
        close(F);
    } else {
        print "Failed upload results for PHENIX: the file doesn't exist\n$file\n";
    }
}


1;
