#!/usr/bin/perl -w

# usage : perl bed to fasta
# Sarah Maman and Olivier Rue- 04/10/2012
# Copyright (C) 2012 INRA
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#


use strict;
use File::Basename; 


#fichier entrant fasta (apres mirdeep2core)
my $input_bed = $ARGV[0];
#fichier entrant reference genome
my $input_ref = $ARGV[1];
#fichiers sortants output3 = fasta
my $output_fasta = $ARGV[2];
my $cmd = '';

my ($nb) = ($output_fasta=~/galaxy_dataset_(\d+)\.\S+$/);
my $dirresults= "/galaxydata/database/files/workspace/".$nb;
`mkdir $dirresults;`;


#creation d'un lien symbolique
`ln -s $input_ref $dirresults/ref.fasta`;
print STDOUT "ln -s $input_ref $dirresults/ref.fasta \n\n";
my $ref ="$dirresults/ref.fasta";

#Extraire le fichier fasta à partir du fichier bed obtenu par mirdeep2core
my @line;
open FILE,$input_bed;
open FASTA,">${nb}_pred_mir.fasta";
while(<FILE>){
	chomp;
	@line=split(/\t/,$_);
	my $scaffold=$line[0];
	my $start=$line[1];
	my $end=$line[2];
	my @seq = `samtools faidx $ref $scaffold:$start-$end 2>/dev/null`;
	print FASTA @seq;
}
close FILE;
close FASTA;

#Recuperer le fasta dans Galaxy
if (! -e "${nb}_pred_mir.fasta"){print STDERR "Pas de fichier fasta produit \n";}
else {$cmd = "(cp -a \"${nb}_pred_mir.fasta\" $output_fasta) >& ./cp_bed_to_fasta.log 2>&1";
system $cmd;}
