#!/usr/local/bin/perl5.6.1
#######################################################################
# This software has been created by Genome Research Limited (GRL).    #
# GRL hereby grants permission to use, copy, modify and distribute    #
# this software and its documentation for non-commercial purposes     #
# without fee at the user's own risk on the basis set out below.      #
# GRL neither undertakes nor accepts any duty whether contractual or  #
# otherwise in connection with the software, its use or the use of    #
# any derivative, and makes no representations or warranties, express #
# or implied, concerning the software, its suitability, fitness for   #
# a particular purpose or non-infringement.                           #
# In no event shall the authors of the software or GRL be responsible #
# or liable for any loss or damage whatsoever arising in any way      #
# directly or indirectly out of the use of this software or its       #
# derivatives, even if advised of the possibility of such damage.     #
# Our software can be freely distributed under the conditions set out #
# above, and must contain this copyright notice.                      #
#######################################################################
# $Id: project_team_assignment.pl,v 1.3 2006/06/27 08:18:33 kva Exp $

use strict;
use WrapDBI;
use OORepository;
use SDTable;
require 'badgerGetOpt.pl';

my $prog = $ENV{'SCRIPT_NAME'};
my($restrict,$file);
#Command-line short cuts
my $opts = {
    "-restrict" => {
        "type" => "text",
        "var"  => \$restrict,
        "help" => "Number of projects to return from SQL query",
    },

    "-output" => {
        "type" => "text",
        "var"  => \$file,
        "help" => "alternative output file",
    }
};
&badgerGetOpt($prog,'',$opts) && die "Quit\n";



my $repos   = new OORepository;

my %PROJ_LIST;
my $project;
my $chromosome;
my $proj;
my $count = 0;

my $db = 'reports';
my $dbh = WrapDBI->connect("$db", {RaiseError => 1});    
$dbh->{autocommit} = 0;

my $output;
if ($file){
    $output = $file;
} else {
    $output = '/tmp/AUTOFIN_PROBLEM_FILE';
}

my @r_cs;
my $table1 = SDTable->new('format' => 'gaudy');
$table1->set('title'=> "PROJECT AUTOFINISHING INFORMATION", 'titles' => ["#","Project","Chr","Difficulty","Contigs","Problems"]);

open(FH, ">$output") || die "Could not create $output\n";

my $statement;
my $stat1 = "SELECT A.PROJ, A.CHR FROM (SELECT PF.PROJECTNAME PROJ, CD.CHROMOSOME CHR FROM PROJECT_FINISHINGPROCESS PF, CLONE_PROJECT CP, CLONE C, CHROMOSOMEDICT CD WHERE PF.PROJECTNAME = CP.PROJECTNAME AND CP.CLONENAME = C.CLONENAME AND C.CHROMOSOME = CD.ID_DICT AND PF.PROCESS_TYPE = 21 AND PF.ISCURRENT = 1 ORDER BY 1)A";

if ($restrict){
    $restrict++;
    my $stat2 = " WHERE ROWNUM < $restrict";
    $statement = $stat1.$stat2;
} else {
    $statement = $stat1;
}

my $sth = $dbh->prepare($statement) || die "ERROR:$DBI::errstr";
$sth->execute() || die "ERROR:$DBI::errstr";
while (($project,$chromosome) = $sth->fetchrow()){
    $PROJ_LIST{$project}=$chromosome;
}
$sth->finish();

foreach my $proj (sort keys %PROJ_LIST){
    $count++;
#    print "PROJECTNAME $count - $proj\n";
    my $project_directory = $repos->get_online_path_from_project($proj);
    &get_no_contigs($proj, $project_directory, 1, $count, $PROJ_LIST{$proj});
}

foreach my $rc (@r_cs){
                    $table1->add(@$rc);
                }
print FH $table1->format();

close(FH);


print "$output has been created.\n";


sub get_no_contigs {
    my ($s_proj, $projpath, $debugging,$p_count,$chr) = @_;
    my @notes;
    
#    print ">>PROJ PATH - $projpath<<\n";
    
## get contents of file
    eval {
        @notes = `/bin/cat \'$projpath/Auto_eval/db_evaluation.1\'`;
    };
    warn $@ if ($@);
    
    my ($contig,$problem,$difficulty);   
## read contents
    if (@notes) {
        my @temp = grep /Total number of contigs.+|PROBLEM TOTAL.+|Difficulty.+/, @notes;
#        print ">>@temp<<\n";
        foreach my $j (@temp) {
            #print ">>J = $j<<\n";
            if ($j =~ /Total number of contigs(.+)/){
                $contig = $1;
                $contig =~ s/\:|\s+//g;
#                print ">>CONTIG - $contig<<\n";
            }
            if ($j =~ /PROBLEM TOTAL(.+)/){
                $problem = $1;
                $problem =~ s/\:|\s+//g;
#                print ">>PROBLEM - $problem<<\n";
            }
            if ($j =~ /Difficulty(.+)/){
                $difficulty = $1;
                $difficulty =~ s/\=|\s+//g;
#                print ">>DIFFICULTY - $difficulty<<\n";
            }
            
        }
    }
#    print FH "#$p_count PROJECT $s_proj CONTIG $contig : PROBLEM $problem : DIFFICULTY $difficulty\n";
    my @cs=("$p_count","$s_proj","$chr","$difficulty","$contig","$problem");
    push (@r_cs, \@cs); 
    
}


END {
    if ($dbh){
        eval {
            $dbh->rollback();
            $dbh->disconnect();
        }
    }
};


__END__


=head1 NAME

 project_team_assignment.pl

=head1 SYNOPSIS

 project_team_assignment.pl [args]

=head1 DESCRIPTION

=head1 AUTHOR

 Karen Ambrose

=head1 HISTORY

 # $Log: project_team_assignment.pl,v $
% Revision 1.3  2006/06/27  08:18:33  kva
% removed unnecessary ssh onto genesis.
%
% Revision 1.2  2006/06/26  16:19:26  kva
% Added options for configuration. Now can specify an outputfile and restrict the amount of data returned. Also added in the chromosome information.
%
% Revision 1.1  2006/06/26  14:36:13  kva
% Initial revision
%

=cut
