#!/usr/local/bin/perl


###############################################################################
# Perl script
# Author C.Mathe 21/10/98, last modified 19/02/99 to read Grail frame.
# Grail frame is exact. just change:F=GF+1 on both strand.
# this script extract data from a grail output file (or list) and write them 
# in a standard file format
###############################################################################

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

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


sub readGrail{
    open(G,"< @_") || die "Unable to open @_.\n";
                                    #open each Grail output, one after the other
    
    while(<G>){
	
	if (/Shadow Exons/) {return;}
	
	$type=$str=$Lend=$Rend=$lg=$ph=$F=$A=$D=$proba="";
	@ligne=split;
	if (($ligne[8] eq 'good')||($ligne[8] eq 'excellent')||($ligne[8] eq 'marginal'))
	{
	    $proba=$ligne[7]/100;
	    if ($ligne[1] eq 'f'){
		$str="+";
		$F=$ligne[2] +1;
		$Lend=$ligne[3];
		$Rend=$ligne[4];
		($lg,$A,$D)=&calcAD($Lend,$Rend,$str);
		&EcrireST($seq,$type,$str,$Lend,$Rend,$lg,$ph,$F,$A,$D,$proba);
	    }
	    else {
		if ($ligne[1] eq 'r'){
		    $str="-"; 
		    $F=$ligne[2] +1;
		    $Lend=&reverse($ligne[4]);
		    $Rend=&reverse($ligne[3]);
		    ($lg,$A,$D)=&calcAD($Lend,$Rend,$str);
		    &EcrireST($seq,$type,$str,$Lend,$Rend,$lg,$ph,$F,$A,$D,$proba);
		}}
	}
    }
    close(G);
}

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

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

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

&createST;


