#!/usr/bin/perl -s
use strict;
use File::Basename;
use IO::Dir;
use IO::File;
use GenePropAxes;
use UserScriptParams;
require 'MBGD_common.pl';

###############################################################################
#
sub setup_params {
    my($key, $default, $require, $explain, $example);

    my($param) = UserScriptParams->new();

    #
    $param->set_description("Get aa sequences for cluster");

    #
    $key     = "TABID";
    $default = "";
    $require = "T"; # "T"rue or else(='optional').
    $explain = "Cluster table ID";
    $example = "tabid";
    $param->add_param($key, $default, $require, $explain, $example);

    #
    $key     = "CLUSTID";
    $default = "";
    $require = "T"; # "T"rue or else(='optional').
    $explain = "Cluster ID";
    $example = "clustid";
    $param->add_param($key, $default, $require, $explain, $example);

    return $param;
}

###############################################################################
#
sub mafft {
    my($tabid) = shift;
    my($clustid) = shift;

    #
    my($align_name) = 'sequence';
    my($path_sequence) = GenePropAxes::make_align_path($tabid, $align_name);

    #
    my($align_name) = 'mafft';
    my($path_mafft) = GenePropAxes::make_align_path($tabid, $align_name);

    #
    my($file_in)  = "$path_sequence/$clustid.fas";
    if ((!-e "$file_in") || (-z "$file_in")) {
        my($align_cmd) = '000sequence';
        my($cmd) = GenePropAxes::get_align_cmd_path($align_cmd);
        if (!$cmd) {
            print STDERR "ERROR :: Can not found sequence file.($file_in)\n";
            return;
        }
        system("$cmd -TABID='$tabid' $clustid");
    }

    #
    my($file_fas)    = "$path_mafft/$clustid.fas";
    my($file_stdout) = "$path_mafft/$clustid.stdout";

    if (!-e $file_fas || -z $file_fas) {
        my($cmd) = "$main::CMD_mafft $file_in | $main::CMD_tee $file_fas";
        system("$cmd");
    }
    else {
        my($cmd) = "$main::CMD_cat $file_fas";
        system("$cmd");
    }

    return;
}

###############################################################################
if ($0 eq __FILE__) {
    my($param_ref) = setup_params();

    if ($main::h) {
        $param_ref->print_usage();
        exit(0);
    }

    my($tabid) = 'default';
    if ($main::TABID) {
        $tabid = $main::TABID
    }

    #
    my(@clustid_list) = @ARGV;
    if ($main::ALL) {
        @clustid_list = GenePropAxes::get_clustid_list($tabid);
    }

    #
    foreach my$clustid ($main::CLUSTID, @clustid_list) {
        next if (!$clustid);

        mafft($tabid, $clustid);
    }
}

###############################################################################
1;#
###############################################################################
