#!/usr/bin/perl -w

use lib "/homes/bierdepot/steffi/Diplom/snoBoard_dipl/";
use warnings;
use strict;
use Getopt::Long; 
#use database;
use Snoopy;
use Plexy;


my ( $opt_h, $opt_f, $opt_w, $opt_e, $opt_v, $opt_p , $opt_C) = ( "", "", "", "", "", "", "", "" );

my ( $tmp, $ps );
my ( @tmp, @lst );


my $usage = << "END";

  usage:    perl $0 -f|fasta STRING -w|out STRING 
 
  purpose:  This script runs a target prediction for all sequences that
            are contained in the given multifasta file.
            Output files are stored in the given output directory.
            Target sequences, profiles and target alignments

  options:

            -h|help        Prints this help message.
    
            -f|fasta       Input multifasta file containing all sequences
                           that shall be used for a target prediction.
                           [REQUIRED]

            -w|out         Output directory, that is used for temporary files
                           and final prediction files.
                           [REQUIRED]

            -p|postscript  Enable postscript pictures of target interaction
                           between HACA snoRNAs and their target.
                           [OPTIONAL]

            -e|exp         evaluate HACA interactions after mfe instead of SVM-score

            -v|verbose     Suppress output.
                           [OPTIONAL]
    
            -C|constraint  constrained HACA stem folding

END

GetOptions(
    "h|help"        => \$opt_h,
    "f|fasta=s"     => \$opt_f,
    "w|out=s"       => \$opt_w,
    "e|exp"         => \$opt_e,
    "p|postscript"  => \$opt_p,
    "v|verbose"     => \$opt_v,
    "C|constraint"  => \$opt_C,
);


####################################################################################################
## START
####################################################################################################

if( $opt_w && $opt_f){

    $opt_w .= "/" if $opt_w !~ /\/$/;

    my $tmpPath = $opt_w."tmp/";    

    if(!-e $opt_w){
	`mkdir $opt_w`;
    }
    if(!-e $opt_w."tmp"){
	`mkdir $opt_w"tmp"`;
    }

    my @tmp;
    push @tmp, $opt_f;
    push @lst,\@tmp;
    

    #when no multifasta location could be retrieved
    if(scalar(@lst) < 1){print STDERR "ERROR:\nDid not find multifasta!";exit(0)}

    #this foreach loop goes through the list of all snoRNAs which shall be analysed
    foreach(@lst){

	#reference to result-hash
	my $res;  
	my ($mf, $id);

	#name of multifasta
	$mf = $_->[0];   
	if($mf ne ''){
	    #extract path
	    $mf =~ /^.*\/([\w\d\-\_]+).fa$/;
	    #extract snoRNA-name 
	    $id = $1;
	    
	    #declare variables
	    my ($header, $seq);

	    #delete old hairpin-files
	    if(-e $tmpPath.$id."_HP1.fa"){
		$tmp = $tmpPath.$id."_HP1.fa";
		`rm $tmp`;
		$tmp = $tmpPath.$id."_HP2.fa";
		`rm $tmp`;
	    }

	    if( !-e $opt_w."psfiles/"){
		`mkdir $opt_w/psfiles/`;
	    }

	    #analyse sequences already contained in the given multifasta-file

	    open (MF, $mf) or die $!;

	    #go through the input fastafile and extract all necessary information about boxes and queryname
	    while (<MF>){
		chomp $_;
		
		if($_ =~ /^>/){

		    ( $header = $_ ) =~ s/^>//;
		    @tmp = split(/_/, $header);
		    
		} else {

		    $seq = $_;

		    (my $species = $tmp[2]);
		    $tmp[3] =~ s/[\(\)]+//g;
		    
		    #analyse function
		    open(TAR1, ">>".$opt_w.$id."_targets_1");
		    open(TAR2, ">>".$opt_w.$id."_targets_2");

		    $species =~ s/\./_/;

		    if($tmp[0] eq "HACA"){
			#split hairpins
			my ($HP1,$HP2) = &splitHP($seq,$tmp[-3],$tmp[-1],$opt_C);
			open(HP1,">>".$tmpPath.$id."_HP1.fa");
			open(HP2,">>".$tmpPath.$id."_HP2.fa");
			print HP1 ">".$species."_".$id."_HP1\n",$HP1,"\n";
			print HP2 ">".$species."_".$id."_HP2\n",$HP2,"\n";
			close(HP1);
			close(HP2);
			
			#predict HACA target 
			my ($targets1,$targets2);
			if(!(defined($opt_e))){
			    $targets1 = &singlesnoop($HP1,$species,$tmpPath);
			    $targets2 = &singlesnoop($HP2,$species,$tmpPath);
			}else{
			    #print "SVM\n";exit(0);
			    $targets1 = &singlesnoop($HP1,$species,$tmpPath,$opt_e);
			    $targets2 = &singlesnoop($HP2,$species,$tmpPath,$opt_e);
			}
			
			my $cnt= 1;
			#print targets to file and make .ps figure
			foreach(@{$targets1}){
			    if($_->{targetRNA} ne "NA"){
				printf TAR1 "%-2s\t%-20s\t%-15s\t%-10s\t%-10s\t%-6s\t%-100s\t%-100s\n",$cnt,$species,$tmp[0]."_".$tmp[1]."-HP1",$_->{targetRNA}."-".$_->{pseudo},$_->{alnPos},$_->{energy},$_->{struc},$_->{seq};
				printf STDOUT "%-2s\t%-20s\t%-15s\t%-10s\t%-10s\t%-6s\t%-100s\t%-100s\n",$cnt,$species,$tmp[0]."_".$tmp[1]."-HP1",$_->{targetRNA}."-".$_->{pseudo},$_->{alnPos},$_->{energy},$_->{struc},$_->{seq} if !$opt_v;
				&makePostscript($_->{snoop},$opt_w."psfiles/") if $opt_p;
				$ps = "TRUE" if $opt_p;
				$cnt++;
			    }
			}
			foreach(@{$targets2}){
			    if($_->{targetRNA} ne "NA"){
				printf TAR2 "%-2s\t%-20s\t%-15s\t%-10s\t%-10s\t%-6s\t%-100s\t%-100s\n",$cnt,$species,$tmp[0]."_".$tmp[1]."-HP2",$_->{targetRNA}."-".$_->{pseudo},$_->{alnPos},$_->{energy},$_->{struc},$_->{seq};
				printf STDOUT "%-2s\t%-20s\t%-15s\t%-10s\t%-10s\t%-6s\t%-100s\t%-100s\n",$cnt,$species,$tmp[0]."_".$tmp[1]."-HP2",$_->{targetRNA}."-".$_->{pseudo},$_->{alnPos},$_->{energy},$_->{struc},$_->{seq} if !$opt_v;
				&makePostscript($_->{snoop},$opt_w."psfiles/") if $opt_p;
				$ps = "TRUE" if $opt_p;
				$cnt++;
			    }
			}
		    }
		    else {
		
			## predict CD targets
			my $targets1 = &computeTargetCD($seq,$species,$tmpPath,$tmp[-1]);
			if(scalar(@{$targets1})>0){
			    my $cnt= 1;
			    foreach(@{$targets1}){
				printf TAR1 "%-2s\t%-20s\t%-15s\t%-10s\t%-10s\t%-6s\t%-45s%-45s\n",$cnt,$species,$tmp[0]."_".$tmp[1]."-D",$_->{targetRNA}."-".$_->{mod},$_->{alnPos},$_->{energy},$_->{structure},$_->{seq2};	
				printf STDOUT "%-2s\t%-20s\t%-15s\t%-10s\t%-10s\t%-6s\t%-45s%-45s\n",$cnt,$species,$tmp[0]."_".$tmp[1]."-D",$_->{targetRNA}."-".$_->{mod},$_->{alnPos},$_->{energy},$_->{structure},$_->{seq2} if !$opt_v;	
				$cnt++;
			    }
			}
			
			if( $tmp[-5] =~ /^\d+$/ && $tmp[-6] =~ /^[A-Z]{4}$/ ){
			    my $targets2 = &computeTargetCD($seq,$species,$tmpPath,$tmp[-5]);
			    if(scalar(@{$targets2})>0){
				my $cnt= 1;
				foreach(@{$targets2}){
				    printf TAR2 "%-2s\t%-20s\t%-15s\t%-10s\t%-10s\t%-6s\t%-45s%-45s\n",$cnt,$species,$tmp[0]."_".$tmp[1]."-Dprime",$_->{targetRNA}."-".$_->{mod},$_->{alnPos},$_->{energy},$_->{structure},$_->{seq2};	
				    printf STDOUT "%-2s\t%-20s\t%-15s\t%-10s\t%-10s\t%-6s\t%-45s%-45s\n",$cnt,$species,$tmp[0]."_".$tmp[1]."-Dprime",$_->{targetRNA}."-".$_->{mod},$_->{alnPos},$_->{energy},$_->{structure},$_->{seq2} if !$opt_v;
				    $cnt++
				}
			    }
			}
		    }
		    close TAR1 ;
		    close TAR2 ;
		}
	    }
	    
	}
	close MF;
	
    }	
    
    ## remove all temp files
    #`rm -r $opt_w"/tmp"`;

    ## rempove psfiles directory if no ps output is generated
    # `rm -r $opt_w"/psfiles"` if !$ps;
}
else{
    print $usage;
}



#########################################################################
#sub DBUpdate
##updates database, includes found sequence
#########################################################################
#{
#    my $dbhandle = shift;
#    my $statement = shift;
#    my @handle = split(/,/,$dbhandle);
##   @statements = UPDATE  ##TODO write update statements for tables in DB
#    my $dbh = connect($handle[0],$handle[1],$handle[2]);
#    if(!defined $dbh){print STDERR "ERROR:\nDB-conection-Error"; exit(0);}
#
#    my $dbu = updateDB($statement);#get list of  multifastas
#    if(!defined $dbu){print STDERR "ERROR:\nDB-query-Error"; exit(0);}
#
#    my $dbd = disconnect();
#    if($dbd != 1){print STDERR "ERROR:\nWAS not able to disconnect"}
#}
#
#
#########################################################################
#sub DBRequest
##gets multifasta-file from snoBoard
########################################################################    
#{
#    my $dbhandle = shift;
#    my $statement = shift;
#    my @handle = split(/,/,$dbhandle);
#    my $dbh = connect($handle[0],$handle[1],$handle[2]);
#    if(!defined $dbh){print STDERR "ERROR:\n DB-conection-Error"; exit(0);}
#
#    my $dbs = queryDB($statement);#get list of  multifastas
#    if(!defined $dbs){print STDERR "ERROR:\nDB-query-Error"; exit(0);}
#
#    my $dbd = disconnect();
#    if($dbd != 1){print STDERR "ERROR:\nWAS not able to disconnect"}
#
#    return $dbs;
#}

