#!/usr/bin/perl

# 02/08/2013 - Wrapper dans le cadre du projet Phylofish (Contact : Jerome Monfort)
# Copyright (C) 2013 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 warnings;
use File::Basename;

if ( scalar(@ARGV) < 2 )
{
	print STDERR "Usage : perl sm_matrice_phylofish.pl <output_matrix> <x files>\n";
	exit(1);
}

my $output = shift @ARGV ;
my @INPUT_FILES = @ARGV;
my ($matrix_filename, $matrix_path, $matrix_suffix) = fileparse($output);
my $id = 0 ;

my ($f2, $p2, $s2) = fileparse($0);
my @files = glob ( $p2 . '/galaxy_dataset_*.dat');
if ( scalar(@files) > 0 )
{
    ($id) = ( $files[0] =~ /galaxy_dataset_(\d+)\.\S+$/ );
}
else
{
    # no dataset file, take the current date
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); 
    $id =  $mday."-".($mon+1)."_".$hour."h".$min."mn".$sec."phylofish"; 
}
my $matrix = join( '/', $matrix_path, $matrix_filename . '_' . $id . '.' .  $matrix_suffix) ;

# Call script
# ===========
my $script = '/usr/local/bioinfo/src/galaxy-dev/galaxy-dist/tools/sm_phylofish/extractCol.pl';
`perl $script $matrix @INPUT_FILES` ;

####################################################################################
#									                                               #			
#		GALAXY OUTPUT         						                               #
#                                                                                  #
####################################################################################
# Recuperation du fichier sortant de statistiques
if (! -e $matrix )
{
    print STDERR "Echec lors de la creation de la matrice.\n";
}
else
{
    `mv  $matrix $output`;
}
