#!/usr/bin/perl -w

# 11/02/2016

# Read number of queries
# The working directory should be set to the folder where all the queries (saved in a FASTA format) and the program are located.
use strict;
use Cwd qw();
my $path = Cwd::cwd();

opendir(DIR,$path);

#select all the queries (files inside the folder saved in a FASTA format)

my @files = grep {/.fa$/} readdir(DIR);

my $num = scalar @files;
print " $num files in this folder \n";



my $db = "/cursos/20428/BI/genomes/2016/Rousettus_aegyptiacus/genome.fa";
my $db_index= "/cursos/20428/BI/genomes/2016/Rousettus_aegyptiacus/genome.index";


#start analysis for all the FASTA files inside the folder
my $query;
for (my $i=0; $i<$num; $i=$i+1){
        
        $query = $files[$i];
	print "$query\n";

        system("tblastn -query $query -db $db -evalue 0.05 -out $query.blast");

system("emacs $query.blast");

#$query.blast will be opened. Select the desired scaffold and the starting position

print "nom scaffold: ";
	my $nomscaffold = <STDIN>;
	chomp($nomscaffold);
system("fastafetch $db $db_index $nomscaffold > $nomscaffold.fa");

	print "start position for fastasubseq: ";
	my $start = <STDIN> - 50000;
	chomp($start);
	my  $diff= 200000;

system("fastasubseq $nomscaffold.fa $start $diff > $nomscaffold.seq");

#exonerate
	system("exonerate -m p2g --showtargetgff -q $query -t $nomscaffold.seq | egrep -w exon > $query.exonerate.gff");
system ("fastaseqfromGFF.pl $nomscaffold.seq $query.exonerate.gff > $query.cdna");
system ("fastatranslate $query.cdna > $query.prot");
#An emacs file will be opened. Select the best prediction. Close the emacs file.
system("emacs $query.prot");
#Another emacs will be opened. Paste the prediction there. It will be saved as a file
system("emacs $query.pred.prot");

#A t-coffee analysis will be made with the prediction
system("t_coffee $query $query.pred.prot > $query.t_coffee");

#The analysis is now completed. Select if you want to continue the analysis with the next query.
print "continue with the analysis? yes/no \n";
my $answer=<STDIN>;
chomp($answer);
if ($answer eq "no"){
    exit;
}
}

