#!/usr/bin/perl
# coded by Holger Schmidtchen (group 2)
# generates data table from Bioprospector output
# creates "pregion.data" files
# ! There should be no "pregion.data" files in the directory before !
# ! execution                                                       !

use strict;
die "useage: $0 bioprospect_output\n" unless @ARGV>=1;

my $file=@ARGV[0];

my $line=100;

my $sense; 
my $name;
my $width;
my $startpos;
my $endpos;
my $motifscore;
my $motifno;
my $strang;
my $seq;


open(FILE,"< ".$file) or die "Fehler beim Oeffnen der Datei: $!\n";
while(<FILE>)
{
  $line++;
  my $oriLine=$_;
  if ($oriLine =~ /^Motif \#/){ 
      my @curLine=split(/\#/, $oriLine);
      $motifno=int($curLine[1]);
    #  print "Motif no: ".$motifno."\n";
  }
  if ($oriLine =~ /^Width \(/){ 
      my @curLine=split(/\s/, $oriLine);
      $motifscore=$curLine[7];
      $motifscore =~ s/\;//;
      print "Motif score: ".$motifscore."\n";
      my @curLine=split(/\(/, $oriLine);
      $width=int($curLine[1]);
     # print "Motif width: ".$width."\n";
  }

  if ($oriLine =~ /^>/){
      my @curLine=split(/\s/, $oriLine);
      $name=substr($curLine[0], 1, length($oriLine) - 1);
      $strang=$curLine[5];
      if ($strang eq "f"){
	  $sense=1;
      }
      else{
	  $sense=0;
      }
      $startpos=$curLine[6];
      $endpos=$startpos+$width;
      $line = 0;
  }

  if ($line == 1){
      my @curLine=split(/\s/, $oriLine);
      $seq=$curLine[0];
	open(OUTFILE,">>".$name.".biop.data");
      print OUTFILE $startpos."\t".$endpos."\t".$motifscore."\t".$motifno;
      print OUTFILE "\t".$seq."\tbiop\t".$sense."\t".$name."\n";
      close(OUTFILE);
  }
}
