#!/usr/local/bin/perl

###############################################################################
# Perl script
# Author C.Mathe 02/10/98, modified 16/02/99 to keep Genscan Frame (and recalculate it in strand -) 
# this script extract data from a Genscan output file and write them in a standard file format
# file of results : dataset_genscanST
###############################################################################

($dir,$name_script)= ($0 =~/(.+\/)*(.+\.pl)$/);
$need=$dir."util.pl";
require "$need";

#require "/home/camat/BIOCOMP/Perl/util.pl";


sub calcRF{ #calculation of the frame in the special case of Genscan.
    local($provF,$GS_f,$strand);
    $GS_f=$_[0];
    $strand=$_[1];
 if ($strand eq '-'){
	$provF=4+($Ltot%3)-$GS_f;
	if ($provF==5){$F=2;}
	else {if ($provF==4) {$F=1;}
	      else {if ($provF==6) {$F=3;}
		    else {$F=$provF;}}
	  }
    }
    else {$F=$GS_f+1;}
    $F=abs($F);
    return $F;
}


sub readGS{
    open(GS,"< @_") || die "Unable to open @_.\n";
                                    #open each Genscan output, one after the other
    
	while(<GS>){
	    $type=$str=$Lend=$Rend=$lg=$ph=$F=$A=$D=$proba="";
	    @ligne=split;           #read each ligne
	    if (($ligne[1] eq 'Init')||($ligne[1] eq 'Intr')||($ligne[1] eq 'Term')||($ligne[1] eq 'Sngl'))   
                                    #read only when Initial, Internal, Terminal or Single exon
	    {
		$str=$ligne[2];
		$type=$ligne[1];
		$proba=$ligne[11];
		$F=&calcRF($ligne[6],$str);
		
		# inverse Begin and End in case of reverse strand
		if ($str eq '-') {$Lend=$ligne[4];$Rend=$ligne[3];}
		else {$Lend=$ligne[3];$Rend=$ligne[4]};
		($lg,$A,$D)=&calcAD($Lend,$Rend,$str);
		if (($type eq 'Init')||($type eq 'Sngl')) {$A="";}
		if (($type eq 'Term') ||($type eq 'Sngl')){$D="";}
		&EcrireST($seq,$type,$str,$Lend,$Rend,$lg,$ph,$F,$A,$D,$proba);
	    }
	}
    close GS;
}

sub readLS{
open(LS,"< $liste") || die "Unable to open $liste.\n";
$ST=&openST("genscan");

while(<LS>)
#read the file containing all the Genscan output files
{
    $count++;
    ($seq,$Ltot)=split;   # read each sequence name and each sequence length
    if (($seq eq "")||($Ltot eq "")) #check if the list is correctly formatted
    {
	&usage("Genscan");
	die "!!! Incorrect input list at line $count!!!\n";}
    $file=$seq . "gs.txt";
    &readGS($file);
    print ST "\n";
}
close LS;
}

sub main{
@data=&Start("Genscan");
if ($data[1]==0) { 
    $liste=$data[0];
    &readLS;
    print "output file: $standart\n";
}
else 
{
    $Ltot=$data[1];
    $file=$data[0];
    @tmp=split('gs',$file);
    $seq=$tmp[0];
    $file2 =$file . "ST";
    open(ST,">$file2");
    print ST "Contig\tType\tStrand\tLend\tRend\tlength\tPhase\tFrame\tAcceptor\tDonor\tProba\n";
    &readGS($file);
    print "output file : $file2\n";
}
close ST;


}

&main;








