#!/usr/bin/perl -w
#
#   Usage: ./mrsclustal -h
#
#   martin.senger@gmail.com
#   February 2010
#-----------------------------------------------------------------------------

use strict;
use warnings;
use FindBin;
use lib "$FindBin::Bin/../lib";
use lib "$FindBin::Bin/../lib/perl5";
use MRS::Client;

sub say { print @_, "\n"; }

sub get_usage {
    return <<"END_OF_USAGE";
Usage:
   mrsclustal [options] -i <multiple_fasta_file>

where
   "multiple_fasta_file" is a file with two or more protein
      sequences in FASTA format that will be aligned

where 'options' are:
   -e <endpoint>  URL of the MRS clustal service
   -S <name>      service name of the MRS clustal service
   -H <hostname>  endpoint host (with standard ports)
   -E             show what endpoint and service name are used

   -a <cost>      gap opening cost (positive integer)
   -z <cost>      gap extension cost (float)

   -d             show only diagnostics

   -h             this help
   -v             show version

END_OF_USAGE
}

# be prepare for command-line options/arguments
my @all_args = @ARGV;
use Getopt::Std;

use vars qw/ $opt_h $opt_v /;               # general
use vars qw/ $opt_e $opt_S $opt_H $opt_E /; # endpoints
use vars qw/ $opt_i $opt_a $opt_z /;        # clustal run
use vars qw/ $opt_d /;                      # results
my $switches = 'aeHiSz';   # switches taking an argument
getopt ($switches);

# help wanted?
if ($opt_h or @all_args == 0) {
    print get_usage;
    exit 0;
}

# print version and exit
if ($opt_v) {
    print "$0 using MRS::Client version $MRS::Client::VERSION\n";
    exit 0;
}

# use UTF8 for output
binmode STDOUT, ":utf8";

# create the main worker
my @args = ();
push (@args, clustal_url => $opt_e) if defined $opt_e;
push (@args, host => $opt_H) if defined $opt_H;
push (@args, clustal_service => $opt_S) if defined $opt_S;
our $client = MRS::Client->new (@args);

# print environment (where to find server, etc.)
if (defined $opt_E) {
    say 'Clustal URL:            ' . $client->clustal_url       if $client->clustal_url;;
    say 'Clustal service name:   ' . $client->clustal_service   if $client->clustal_service;
    say 'Clustal WSDL:           ' . $client->clustal_wsdl      if $client->clustal_wsdl;
}

# collect parameters for a clustal run
my @run_args = ();
push (@run_args, open_cost => $opt_a) if defined $opt_a;
push (@run_args, extend_cost => $opt_z) if defined $opt_z;
push (@run_args, fasta_file => $opt_i) if $opt_i;

# run Clustal
my $result = $client->clustal->run (@run_args);
say "ERROR: " . $result->failed if $result->failed;
if ($opt_d) {
    say $result->diagnostics;
} else {
    print $result;
}

__END__
