#!/usr/local/bin/perl -w
#
# Author: Ben Tubby (bt1)
#


#BEGIN {
#    unshift(@INC, "/usr/local/badger/bin");
#    unshift(@INC, ".");
#    $ENV{'PATH'} = "/usr/bin"; 
#}

BEGIN {
    $ENV{'PATH'} .= ":/usr/sbin/";
    unshift(@INC, "$ENV{'BADGER'}/bin");
    unshift(@INC, "."); 
}


#use strict;

use Cwd;
use gapio;
use GNUtils;
use Caftools;   
use OORepository;


#############################################################################

sub evaluate_db{
    my ($project, $version, $number, $dbeval_file, $use_repos, $AUTOFIN_DIR) = @_;
    
    print "o Evaluating $project.$version (writing '$dbeval_file.$number')...\n";
    
    #    
    # OLD evaluation 
    #
    my $evaluation_path = "/usr/local/badger/bin/gapdb_evaluate";
    my $cmd;
    if ($use_repos){
        $cmd = "$evaluation_path -project $project -version $version -output $dbeval_file.$number -use_repos";
    }else{
        $cmd = "$evaluation_path -project $project -version $version -output $dbeval_file.$number -nouse_repos";
    }
    print "o Writing evaluation output to $dbeval_file.$number...\n";
    system ("$cmd");
    
    #
    # NEW evaluation
    # disabled bt1 04/08/03 as results are currently unused!

    my $new_eval_file = "$AUTOFIN_DIR/db_eval.$number";
    #&newstyle_evaluate($project, $version, $number, $AUTOFIN_DIR, $new_eval_file, $use_repos);
}

#############################################################################

sub newstyle_evaluate{
    #
    # new sytle evaluation (gapNav)
    #
    my ($project, $version, $number, $finish_dir, $output_file, $use_repos) = @_;
    
    my ($full_path, $project_directory, $l_project);
    my $upper_project = uc($project);

    if ($use_repos){
        my $repos = new OORepository;
        $project_directory = $repos->get_online_path_from_project($project);
        
        if (!$project_directory){
            $l_project = $project;
            substr ($l_project, 0, 1) = lc (substr ($l_project, 0, 1));
            $project_directory = $repos->get_online_path_from_project($l_project);
        }
        $full_path = "$project_directory/$project.$version";
        
    } else {
        $project_directory = cwd();
        print "CURRENT WORKING DIR (assuming this is PROJECTNAME): $project_directory\n";
        $project_directory =~ s#/tmp_mnt##;
        $l_project = lcfirst($project);
        $full_path = "$project_directory/$project.$version";
    }
    chdir($project_directory);

    die "\nERROR: Failed to find $upper_project.$version...\n\n" unless (-e "$project_directory/$upper_project.$version");

    my $caffile = "auto-eval.$number.caf";

    print "\no Running gap2caf.... ";
    my $caf_return = &build_caffile($upper_project, $version, $caffile);
    if ($caf_return){
        print "DONE\n";
    }else{
        print "FAILED!\n";
    }

    my $problems_aref;
    if (-e "$caffile"){
        print "\nCaffile '$caffile' created ok..."; 
        my $caf = Caftools->new();                                                                                                   
        
        $caf->readCafFile($caffile);                                                                                                    
        my $gnav = GNUtils->new($caf);                                                                                               
        

        #
        # this selection will effect the number of problem regions returned...
        #
       
        #$problems_aref = $gnav->find_problem_regions('ST', 'QUAL+30');
        #my $probs_string = "Consensus quality <30 and Single template regions";

        $problems_aref = $gnav->find_problem_regions('all');
        my $probs_string = "all available";

#my $problems_aref = $gnav->find_problem_regions(all);
        
        my ($contigs, $problems) = $gnav->Visualize($problems_aref,"$finish_dir/db_eval.$number.gif");

        my $date = localtime();
        open (OUTPUT, ">$output_file") || die "Failed to open $output_file for writing $!";
        
        print OUTPUT "Database evaluation of $full_path ($date)\nSearching for: $probs_string\n\n";
        foreach (@{$problems_aref}){
            print OUTPUT "$_";
        }
        print OUTPUT "\n\nContigs:$contigs PROBLEMS:$problems\n\n";
        close OUTPUT || die "Failed to close filehandle $!";
        
    }else{
        die "\nFailed to create caffile '$caffile'";
    }
    return $problems_aref;
}

#############################################################################

sub build_caffile{
    my ($project, $version, $caffile) = @_;
    
    my $gap2caf = "/usr/local/badger/bin/gap2caf";
    my $cafcmd = "$gap2caf -bayesian -staden -project $project -version $version -cutoff 30 -ace ./$caffile 2>&1";
    print "\n$cafcmd\n";# if ($debug);
    my $cafreturn = `$cafcmd`;
    
    die "ERROR: Failed to create caf file for $project.$version" if (-z $caffile);
    
    my $caflimit = "/usr/local/badger/bin/caf_limit";
    `$caflimit -caf $caffile -minsize 2000`;

    return $cafreturn;
}

#############################################################################

sub read_config_file{
    my ($string) = @_;
    
    my $config_file = '/usr/local/badger/bin/autofinishing.config';
    unless (open (CONFIG, $config_file)){
        print "\nPanic! Failed to open autofinishing config file, $config_file!\n";
        die "\nPanic! Failed to open autofinishing config file, $config_file!\n";
    }
    my ($return) = map{(split /\s\:\s/,($_))[1]}grep/$string/, <CONFIG>;
    close CONFIG || die "Failed to close autofinishing config file, $config_file! $!";
    chomp $return;
    return ($return);
}

#############################################################################

sub consed_tags_2_gap{
    my ($project, $version, $consed_oligo_file, $tag_type, $tag_description, $debug) = @_;

    #
    # Routine to identify the custom primer sequences in a consed autofinish 
    # output file, and to add a tag to each incarnation of each sequence
    # in the specified gap database. 
    #
    
    my $tmpfile = "/tmp/consedtags_to_gap";
    open (FILE, "$consed_oligo_file") || die "Failed to open file >$consed_oligo_file< $!";
    my @consed_oligos;
    print "\no Found the following primers in the consed output file '$consed_oligo_file';\n\n";
    my $primer_count = 0;
    while (<FILE>){
        if ($_ =~ /^([atcg]+),\d+,\S+.\d+,(->|<-),\S+/){
            $primer_count++;
            my $direction;
            $direction = "Forward primer ---->" if ($2 eq "->");
            $direction = "Reverse primer <----" if ($2 eq "<-");
            
            print "($primer_count) Primer = $1 ($direction)\n";
            # push an uppercase version of the oligo sequence onto an array...
            my $primer = uc($1);
            push (@consed_oligos, $primer."_".$direction);
        }
    }
    print "\n";
    close FILE || die "Failed to CLOSE filehandle $!\n";
    my ($tag_string) = &create_tag_file($project, $version, \@consed_oligos, $tag_type, $tag_description, $debug);
    
    print "\no Writing tags to tmp file ($tmpfile)";
    open (OUTPUT, ">$tmpfile") || die "Failed to open $tmpfile for writing! $!\n";
    print OUTPUT $tag_string;
    close OUTPUT;
    
    if (-e "$tmpfile"){
        print         "\no Writing tags to gap database...\n";
        &write_tags($project, $version, $tmpfile, $debug); 
    }else{
        print "\nERROR: $tmpfile does not exist!\n";
    }
}
    
#############################################################################

sub get_consed_oligo_file{
    my ($path) = @_;
    
    # get the consed oligo file that was created with consed autofinish ran...
    #
    #
    my $cmd = "/bin/ls -1 $path/*customPrimers";
    print ">$cmd<";
    my $file = `$cmd`;
    #chomp $file;
    return ($file);
}

#############################################################################

sub  get_full_path_from_repos{
    my ($project) = @_;
    
    #
    # Get full path...
    #
    my $l_project;
    my $repos = new OORepository;
    my $project_directory = $repos->get_online_path_from_project($project);
    if (!$project_directory){
        $l_project = $project;
        substr ($l_project, 0, 1) = lc (substr ($l_project, 0, 1));
        $project_directory = $repos->get_online_path_from_project($l_project);
    }
    return ($project_directory, $l_project);
}

#############################################################################

sub backup_and_comment_db{
    my ($project_directory, $project, $version, $backup_db_suffix, $comment) = @_;
    
    #print ">>>>BACKING UP DATABASE<<<<\n";
    # Remove old backup, as cpdb can't handle it being there already!
    #cprint "Searching for $project_directory/$project.$backup_db_suffix...\n";
    if (-e "$project_directory/$project.$backup_db_suffix"){
        print "- Removing old project.$backup_db_suffix\n";
        system ("/usr/local/badger/bin/rmdb $project $backup_db_suffix  > /dev/null");
    }
    print "- Backing up $project.$version to $project.$backup_db_suffix\n";
    !system ("/usr/local/badger/bin/cpdb $project $version $project $backup_db_suffix 2>&1") or warn "ERROR: failed to backup database! ($!)\n";
    print "- Commenting $project.$backup_db_suffix (with '$comment')\n";
    !system ("/usr/local/badger/bin/commentdb $project.$backup_db_suffix '$comment' > /dev/null")
        or warn "ERROR: failed to comment database! ($!)\n";
}
#

#############################################################################

sub Mail{
    my ($subject, $message, $who_to_mail) = @_;

    print "ERROR: Error opening pipe to sendmail\n\n" unless open (SENDMAIL, "| sendmail -t -n");
    print SENDMAIL <<EOM;
To: $who_to_mail
Cc: 
Subject: $subject

$message

EOM
    close(SENDMAIL);
}
#############################################################################

1;

__END__

# $Id: Autofin_utils.pm,v 1.29 2005/03/10 12:28:16 jkb Exp $
#
# $Log: Autofin_utils.pm,v $
# Revision 1.29  2005/03/10  12:28:16  jkb
# Changed PATH hacks to append /usr/sbin instead of overwrite!
#
# Revision 1.28  2005/03/08  14:03:45  mdf
# *** empty log message ***
#
# Revision 1.27  2005/03/08  13:23:12  mdf
# *** empty log message ***
#
# Revision 1.26  2005/03/08  12:48:35  mdf
# added $ENV{'PATH'} = "/usr/bin"; to path
#
# Revision 1.25  2003/09/22  08:47:27  jkb
# Removed dead code in get_full_path_from_repos()
#
# Revision 1.24  2003/08/04  11:11:16  bt1
# disabled new style evaluation.
#
# Revision 1.23  2002/08/27 13:36:49  bt1
# *** empty log message ***
#
# Revision 1.22  2002/05/02  14:38:53  bt1
# Added Mail routine
#
# Revision 1.21  2001/09/11  14:58:34  bt1
# *** empty log message ***
#
# Revision 1.20  2001/09/11  14:57:40  bt1
# *** empty log message ***
#
# Revision 1.19  2001/09/11  14:56:22  bt1
# *** empty log message ***
#
# Revision 1.18  2001/09/11  14:49:37  bt1
# *** empty log message ***
#
# Revision 1.17  2001/08/01  14:40:45  bt1
# Added call to caf_limit to remove contigs from caffile that are under 2kb
#
# Revision 1.16  2001/08/01  13:40:01  bt1
# *** empty log message ***
#
# Revision 1.15  2001/07/26  13:52:46  bt1
# *** empty log message ***
#
# Revision 1.14  2001/07/26  13:51:49  bt1
# *** empty log message ***
#
# Revision 1.13  2001/07/26  13:49:23  bt1
# *** empty log message ***
#
# Revision 1.12  2001/07/26  13:48:03  bt1
# *** empty log message ***
#
# Revision 1.11  2001/07/26  13:46:09  bt1
# *** empty log message ***
#
# Revision 1.10  2001/07/26  13:24:02  bt1
# *** empty log message ***
#
# Revision 1.9  2001/07/24  09:54:36  bt1
# *** empty log message ***
#
# Revision 1.8  2001/07/24  09:16:24  bt1
# *** empty log message ***
#
# Revision 1.7  2001/06/27  11:22:30  bt1
# *** empty log message ***
#
# Revision 1.6  2001/06/27  11:21:41  bt1
# *** empty log message ***
#
# Revision 1.5  2001/06/27  11:12:05  bt1
# *** empty log message ***
#
# Revision 1.4  2001/06/26  13:19:02  bt1
# *** empty log message ***
#
# Revision 1.3  2001/06/26  13:10:57  bt1
# Added &evaluate routine to call new gapNav-style evaluation
#
# Revision 1.2  2001/06/26  09:11:42  bt1
# Added &evaluate routine...
#
# Revision 1.1  2001/06/26  09:09:27  bt1
# Initial revision
#
# Revision 1.1  2001/05/02  08:54:41  bt1
# Initial revision
#
#
