#!/usr/bin/perl -w
use strict;

my $s; #scaffold
my $start; #first nucleotide
my $final; #last nucleotide
my $length; #hit lenght
my $q; #query
my $k; #the content of the file ending with .p.fa
my $runagain; #the answer to the question about if we want to run the program again

#First of all the program asks for the protein we are working with

print "Enter the query name: ";
$q = <STDIN>;
chomp ($q);

print "Enter the scaffold: ";
$s = <STDIN>;
chomp ($s);

print "First nucleotide: ";
$start = <STDIN>;
chomp ($start);

print "Final nucleotide: ";
$final = <STDIN>;
chomp ($final);

#The program makes a directory named after the protein and the scaffold, in which every file will be saved

system ("mkdir $q.$s");

system ("fastafetch /cursos/20428/BI/genomes/2017/Pogona_vitticeps/genome.fa  /cursos/20428/BI/genomes/2017/Pogona_vitticeps/genome.index '$s' > $s.fa");

print "Fastafetch done!:)\n";

system ("fastalength $s.fa");

print "Enter the scaffold length:";
my $fastalength=<STDIN>;
chomp ($fastalength);

#The program extends the sequence 100000 nucleotides on both ends

$start=$start-100000;

if ($start<0){
    $start=0;
}
print "$start\n";

$length=($final+100000)-$start;

if ($fastalength<$start+$length){
    $length=$fastalength-$start-1;
}

print "$length\n";

system ("fastasubseq $s.fa $start $length > $q.$s.genomic.fa"); 

print "Fastasubseq done!!\n";

system ("exonerate --exhaustive yes -m p2g --showtargetgff -q $q -t $q.$s.genomic.fa | egrep -w exon > $q.$s.exonerate.gff");

print "Exonerate done!\n";

system ("fastaseqfromGFF.pl $q.$s.genomic.fa $q.$s.exonerate.gff > $q.$s.nt.fa");

print "FastaseqfromGFF done!\n";

system ("fastatranslate -f $q.$s.nt.fa -F 1 > $q.$s.p.fa");

print "Fastatranslate done!\n";


#Now the program changes the * for X in the file ending with .p.fa and saves this new content in a new file ending with .pX.fa

open(INPUT, "$q.$s.p.fa");
undef $/;
$k = <INPUT>;
close INPUT;
$/ ="\n";

$k =~ s/\*/X/g;

open(my $fh, '>', "previous");
print $fh $k;
close $fh;

system ("mv previous $q.$s.pX.fa");

print "Running T-Coffee…\n";

system ("t_coffee $q $q.$s.pX.fa > $q.$s.tcoffe");

system ("more $q.$s.tcoffe");

system ("genewise -pep -pretty -cdna -gff -trev $q $q.$s.genomic.fa > $q.$s.genewise.fa");


#Finally all files are moved to the new directory


system ("mv $s.fa $q.$s");
system ("mv $q.$s.genomic.fa $q.$s");
system ("mv $q.$s.exonerate.gff $q.$s");
system ("mv $q.$s.nt.fa $q.$s");
system ("mv $q.$s.p.fa $q.$s");
system ("mv $q.blast $q.$s");
system ("mv $q.$s.pX.fa $q.$s"); 
system ("mv $q.$s.tcoffe $q.$s");
system ("mv $q.aln $q.$s");
system ("mv $q.html $q.$s"); 
system ("mv $q.$s.genewise.fa $q.$s");

print "THE END!\n";

#The program asks us if we want to analyze another scaffold

print "Do you want to analyze another scaffold?";

$runagain=<STDIN>;
chomp ($runagain);

if ($runagain eq "yes") {
    system ("perl blast.pl");
}

else {
    print "Okay!\n";
}
