#!/usr/bin/perl -w

use strict;

my $genewise = $ARGV[0];
my $exonerate = $ARGV[1];
my $secis = $ARGV[2];
my $nom = $ARGV[3];
#+ és forward i - és reverse
my $strand = "+";
my $sbp = 0;
my $ebp = 0;

open(EXONERATE, "< $exonerate");
while(<EXONERATE>) {
	chomp;
	if ($_ !~ m/Target range/) {
		next;
	}
	my @columna = split (/ /,$_);
	$sbp = $columna[4];
	$ebp = $columna[6];
	if ($columna[6] < $columna[4]) {
		$strand = "-";
		$sbp = $columna[6];
		$ebp = $columna[4];
	}
	print $nom, "\t", $strand, "\t", $sbp, "\t", $ebp, "\t";
	
}
close(EXONERATE);

my $i;
my $j;
my $gsbp;
my $gebp;

open (GENEWISE, "< $genewise");
while (<GENEWISE>) {
	chomp;
	next if ($_ !~ m/.sp/);
	my $f = index($_,"[");
	my $g = index($_,"]");
	my $h = substr $_,($f+1),($g-$f-1);
	($i, $j) = split(/:/,$h);
	next if ($strand eq "-" && $i < $j);
	next if ($strand eq "+" && $i > $j);
	if ($j > $i) {
		$gsbp = $j;
		$gebp = $i;
		print $gsbp, "\t", $gebp, "\t";
	}
	else {
		$gsbp = $i;
		$gebp = $j;
		print $gsbp, "\t", $gebp, "\t";
	}
}
close (GENEWISE);

my $free;
my @v;
my @w;
my $ssbp;
my $sebp;

open (SECIS, "< $secis");
while (<SECIS>) {
	chomp;
	next if ($_ !~ m/subseq/);
	if ($strand eq "-") {
		next if ($_ !~ m/complementary/);
		my $a = index($_,"[");
		my $b = index($_,"]");
		my $c = substr $_,($a+1),($b-$a-1);
		my ($x, $y) = split(/,/,$c);
		@v = split(/ /,$_);
		my $length = (scalar(@v)-1);
		$free = $v[$length];
		next if ($y > $ebp);
		$ssbp = $y;
		$sebp = $x;
		print $ssbp, "\t", $sebp, "\t", $free, "\t";
	}
	else {
		next if ($_ =~ m/complementary/);
		my $a = index($_,"[");
		my $b = index($_,"]");
		my $c = substr $_,($a+1),($b-$a-1);
		my ($x, $y) = split(/,/,$c);
		@w = split(/ /,$_);
		my $length = (scalar(@w)-1);
		$free = $w[$length];
		next if ($x < $ebp);
		$ssbp = $x;
		$sebp = $y;
		print $ssbp, "\t", $sebp, "\t", $free, "\t";
	}
}
close(SECIS);
print "\n";
	
