#!/usr/local/bin/perl

###############################################################################
# Perl script
# Author C.Mathe 11/10/98, modified 21/10/98
# this script extract data from a BCM-SPL output file 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 readSPLD{ #read SPL output on direct strand input.
open(SPLD,"<$_[0]") ||die "Unable to open $_[0]";
while(<SPLD>)
{
$str="+";
$lg=$F=$type=$ph=$Rend=$Lend=$D=$A=$proba="";
if (/^Number of Donor/) {
    @word=split;
    $nd=$word[4];
    $etat=1;
    $i=0;}
if(($etat==1)&&($i<=$nd)&&($i!=0)){
    {
	($nb,$D,$proba)=split;
	($Rend,$Lend,$A)=&calcEnd($D,$str);
	&EcrireST;
    }}
if (/^Number of Acceptor/) {
    @word=split;
    $na=$word[4];
    $etat=2;
    $i=0;}
if(($etat==2)&&($i<=$na)&&($i!=0)){
    {
	($nb,$A,$probs)=split;
	($Rend,$Lend,$D)=&calcBeg($A,$str);
	&EcrireST;
 }}
$i++;
}
close(SPLD);
}

sub readSPLR{ #read SPL output on reverse strand input.
open(SPLR,"<$_[0]") ||die "Unable to open $_[0]";
while(<SPLR>)
{
$str="-";
$lg=$F=$type=$ph=$Rend=$Lend=$D=$A=$proba="";
if (/^Number of Donor/) {
    @word=split;
    $nd=$word[4];
    $etat=1;
    $i=0;}
if(($etat==1)&&($i<=$nd)&&($i!=0)){
    {
	($nb,$D,$proba)=split;
	$D=&reverse($D);
	($Rend,$Lend,$A)=&calcEnd($D,$str);
	&EcrireST($seq,$type,$str,$Lend,$Rend,$lg,$ph,$F,$A,$D,$proba);	
    }}
if (/^Number of Acceptor/) {
    @word=split;
    $na=$word[4];
    $etat=2;
    $i=0;}
if(($etat==2)&&($i<=$na)&&($i!=0)){
    {
	($nb,$A,$proba)=split;
	$A=&reverse($A);
	($Rend,$Lend,$D)=&calcBeg($A,$str);
	&EcrireST($seq,$type,$str,$Lend,$Rend,$lg,$ph,$F,$A,$D,$proba);
 }}
$i++;
}
close(SPLR);
}

sub readLS{
    open(LS,"< $liste") || die "Unable to open $liste.\n";
    $ST=&openST("spl");
    while(<LS>){
	$count++;
	($seq,$Ltot)=split;              # read each file name and each corresponding sequence length
	if (($seq eq "")||($Ltot eq "")) #check if the list is correctly formatted
	{
	    &usage("BCM-SPL");
	    die "!!! Incorrect input list at line $count!!!\n";}
	$fileD=$seq . "spl1.txt";
	$fileR=$seq . "spl2.txt";
	&readSPLD($fileD); 
	&readSPLR($fileR);
	print ST "\n";}
close LS;	
}

sub createST{
     @data=&Start("BCM-SPL");
     if ($data[1]==0) { 
	 $liste=$data[0];
	 &readLS;
	 print "output file: $standart\n";
     }
     else 
     {
	 $Ltot=$data[1];
	 $fileD=$data[0];
	 @tmp=split('spl1',$fileD);
	 $fileR=$tmp[0] . "spl2.txt";
	 print "Take $fileR as output name on reverse strand.\n";
	 $seq=$tmp[0];
	 $file2 =$tmp[0] . "spl12.txtST";
	 open(ST,">$file2");
	 print ST "Contig\tType\tStrand\tLend\tRend\tlength\tPhase\tFrame\tAcceptor\tDonor\tScore\n";
	 &readSPLD($fileD);
	 &readSPLR($fileR);
	 print "output file: $file2\n";
     }
     close ST;
}

&createST;













