#!/usr/bin/perl
use strict;
use warnings;

my $start = $ARGV[0];
my $end = $ARGV[1];
my $SCAFFOLD = $ARGV[2];
my $query = $ARGV[3];

my $genome = "/mnt/NFS_UPF/soft/genomes/2019/Laticauda_laticaudata/genome.fa";
my $genomeindex = "/mnt/NFS_UPF/soft/genomes/2019/Laticauda_laticaudata/genome.index"; 

my $scaffold_file = "$SCAFFOLD.fa";

my $cmd = "fastafetch -f $genome -i $genomeindex -q $SCAFFOLD > $scaffold_file";
my $exit_code = system($cmd);
if($exit_code!=0){ die("exit code $exit_code failed to run $cmd "); }


my $scaffold_length = "$SCAFFOLD.length.fa";

$cmd = "fastalength $scaffold_file > $scaffold_length";
$exit_code = system($cmd);
if($exit_code!=0){ die("exit code $exit_code failed to run $cmd "); }

my $length;

open (FILE, '<', "$scaffold_length");

while (<FILE>){
my @taula = split(/ /,$_);
$length = $taula[0];
}
close (FILE);

print "$length\n";

$start = $start - 50000; 
if ($start < 0){
    $start = 0;
}
$end = $end + 50000;
if ($end > $length) {
   $end = $length;
}

print "$start\n";
print "$end\n";

my $long = $end - $start;

print "$long\n";

my $scaffold_subseq = "$SCAFFOLD.subseq.fa";

$cmd = "fastasubseq -f $scaffold_file -s $start -l $long > $scaffold_subseq";
$exit_code = system($cmd);
if($exit_code!=0){ die("exit code $exit_code failed to run $cmd"); }

print "Performing exonerate\n";

my $scaffold_exonerate = "$SCAFFOLD.exonerate.fa";
 
$cmd = "exonerate -m p2g --showtargetgff -n 1 -q $query -t $scaffold_subseq > $scaffold_exonerate";
$exit_code = system($cmd);
if($exit_code!=0){ die("exit code $exit_code failed to run $cmd "); }

my $scaffold_genes_exonerate = "$SCAFFOLD.genes.exonerate.gff";

$cmd = "egrep -w gene $scaffold_exonerate > $scaffold_genes_exonerate";
$exit_code = system($cmd);
if($exit_code!=0){ die("exit code $exit_code failed to run $cmd "); }


my $scaffold_all_exonerate = "$SCAFFOLD.all.exonerate.gff";

$cmd = "egrep -w exon $scaffold_exonerate > $scaffold_all_exonerate";
$exit_code = system($cmd);
if($exit_code!=0){ die("exit code $exit_code failed to run $cmd "); }


my $scaffold_prednuc = "$SCAFFOLD.prednuc.fa";

$cmd = "fastaseqfromGFF.pl $scaffold_subseq $scaffold_all_exonerate > $scaffold_prednuc";
$exit_code = system($cmd);
if($exit_code!=0){ die("exit code $exit_code failed to run $cmd "); }


my $scaffold_aa = "$SCAFFOLD.aa.gff";

$cmd = "fastatranslate -f $scaffold_prednuc -F 1 > $scaffold_aa";
$exit_code = system($cmd);
if($exit_code!=0){ die("exit code $exit_code failed to run $cmd "); }

my $prediction_aa = "$SCAFFOLD.prediction.txt";

$cmd = "sed -i 's/*/X/g' $scaffold_aa > $prediction_aa";
$exit_code = system($cmd);
if($exit_code!=0){ die("exit code $exit_code failed to run $cmd "); }


my $scaffold_tcoffee = "$SCAFFOLD.tcoffee";

$cmd = "t_coffee $query $scaffold_aa > $scaffold_tcoffee ";
$exit_code = system($cmd);
if($exit_code!=0){ die("exit code $exit_code failed to run $cmd "); }






