#!/usr/bin/env perl

use warnings;
use strict;
 
use Getopt::Long  qw(:config no_ignore_case no_auto_abbrev);
my %opts;
GetOptions( \%opts,
    'results_dir=s'
) || die "Error getting options! $!";

my $results_dir = $opts{ results_dir };
if ( !-e $results_dir ) {
	print STDERR "Please provide a correct --results_dir\n";
	exit(0);
}

open( my $mfh, '<', "$results_dir/matchtable.txt" ) || _die( "Can't read matchtable.txt: $!", __LINE__ );
open( my $rfh, '>', "$results_dir/panoct.result" )  || _die( "Can't write to panoct.result: $!\n", __LINE__ );

while ( <$mfh> ) {

	chomp;
	$_ =~ s/_(BDM|SYN)//g;
	my @f = split( /\t/, $_ );
	my @real_f;

	for my $i ( @f ) {

		next if $i =~ /^\-{2,}/;
		push @real_f, $i;

	}

	print $rfh join("\t", @real_f), "\n";

}

close $mfh;
close $rfh;
print "$results_dir/panoct.result\n";

my $gene_att_file = $results_dir . '/combined.att';

unless ( -s "$gene_att_file.dat" ) {
	create_att_dat_file( $gene_att_file, $results_dir );
}
print "$gene_att_file.dat\n";

########################################################################
sub create_att_dat_file {
# given a path to a att_file, create a .dat from it.

    my ( $att_file, $out_dir ) = @_;

    my $att_dat_file = $att_file . ".dat";
    my @cmd = ( '/home/formation/public_html/M2_Phylogenomique/PanGenomePipeline/PanGenomePipeline-master/pangenome/bin/convert_att_file_to_hsh.pl', $att_file, $out_dir );
    print join(' ', @cmd), "\n";

    #~ _log( "Creating att.dat file:\n" . join( ' ', @cmd ), 1 );
#~ 
    #~ my $lf = "$log_dir/convert_att_file_to_hsh.log";
    #~ my $lh = IO::File->new( $lf, "w+" ) || _die( "Couldn't open $lf for logging: $!", __LINE__ );

	system( @cmd );

    return $att_dat_file;

}
