#!/usr/bin/perl -w
use POSIX;
use Getopt::Long qw(:config bundling require_order auto_version);
use Pod::Usage;
use FAST;
use FAST::Bio::SeqIO;
use strict;

use vars qw($VERSION $DESC $NAME $COMMAND $DATE);
$VERSION = $FAST::VERSION; 
$DESC    = "tally sequences and sequence characters";
$NAME    = $0;
$NAME    =~ s/^.*\///;
$COMMAND = join " ",$NAME,@ARGV;
$DATE = POSIX::strftime("%c",localtime());

use constant { true => 1, false => 0 };

## DEFAULT OPTION VALUES
my $def_format  = $FAST::DEF_FORMAT;  #7/1/13 "fasta";
my $def_logname = $FAST::DEF_LOGNAME; #7/1/13 "FAST.log.txt";
my $def_join_string = "";

## OPTION VARIABLES
my $man                  = undef;  # --man
my $help                 = undef;  # -h
my $moltype              = undef;  # -m, in case bioperl can't tell
my $format               = $def_format;  # --format
my $log                  = undef;        # -l
my $logname              = $def_logname; # -L
my $comment              = undef;        # -C
my $sequences_only       = undef;        # -s
my $characters_only      = undef;        # -c 
my $join                 = $def_join_string; # -j

GetOptions('help|h'         		 => \$help, 
	   'man'            		 => \$man,
	   'moltype|m=s'                 => sub{  my (undef,$val) = @_; 
						  die "$NAME: --moltype or -m option argument must be \"dna\", \"rna\" or \"protein\"" 
						    unless $val =~ /dna|rna|protein/i; 
						  $moltype = $val;
						},
	   'format=s'                    => \$format,
	   'log|l'                       => \$log,
	   'logname|L=s'                 => \$logname,
	   'comment|C=s'                 => \$comment,
	   'sequences|s'                 => \$sequences_only,
	   'characters|c'                => \$characters_only,
           'fastq|q'                     => sub { $format = 'fastq'; },
	  ) 
  or exit(1);
		  
$format = lc ($format);

pod2usage(-verbose => 1) if $help;
pod2usage(-verbose => 2) if $man;
my $fromSTDIN = ((-t STDIN) ? false : true);
pod2usage("$NAME: Requires at least one argument FILE [FILE2…FILEN] unless input is from STDIN.\n") if ((-t STDIN) && (@ARGV == 0));
pod2usage("$NAME: Requires exactly zero arguments if input is from STDIN. Try $NAME -h for help.\n")      if (!(-t STDIN) && (@ARGV != 0));

&FAST::log($logname, $DATE, $COMMAND, $comment, $fromSTDIN) if ($log);

my $OUT = FAST::Bio::SeqIO->newFh(-fh => *STDOUT{IO}, '-format' => $format);
my $IN;
unless (@ARGV) {
    if ($moltype) {
	$IN = FAST::Bio::SeqIO->new(-fh => *STDIN{IO}, '-format' => $format, '-alphabet' => $moltype);
    }
    else {
	$IN = FAST::Bio::SeqIO->new(-fh => *STDIN{IO}, '-format' => $format);
    }
}

my $numseqs;
my $numchars;
my $file;
my $numseqsfile;
my $numcharsfile;
while ($IN or @ARGV) {
  if (@ARGV) {
    $file = shift (@ARGV);
    $numseqsfile = $numcharsfile = 0;
    unless (-e $file) {
      warn "$NAME: Could not find file $file. Skipping.\n";
      next;
    }
    elsif ($moltype) {
      $IN = FAST::Bio::SeqIO->new(-file => $file, '-format' => $format, '-alphabet' => $moltype);
    }
    else {
      $IN = FAST::Bio::SeqIO->new(-file => $file, '-format' => $format);
    }
  }
  else {
    undef $file;
  }
  if ($IN) { 
    while (my $seq = $IN->next_seq()) {
      my $length;
      unless ($characters_only) {
	$numseqs++;
	$numseqsfile++;
      }
      unless ($sequences_only) {
	$length = $seq->length();
	$numchars += $length;
	$numcharsfile += $length;
      }
    }
    if ($file) {
      print join $join,
	( (!$characters_only) ? sprintf("%10d",$numseqsfile) : ""),
	  ( (!$sequences_only ) ? sprintf("%10d",$numcharsfile) : ""),
	    " $file\n";
    }
    undef $IN;
  }
}

print join $join,
  ( (!$characters_only) ? sprintf("%10d",$numseqs) : ""),
  ( (!$sequences_only ) ? sprintf("%10d",$numchars) : ""),
  " total\n";

__END__

=head1 NAME

B<faswc> - tally sequences and sequence characters

=head1 SYNOPSIS

B<faswc> [OPTION]... [MULTIFASTA-FILE...]

=head1 DESCRIPTION

B<faswc> takes sequence or alignment data on input and outputs tallies
of sequences and/or sequence characters directly to STDOUT (in analogy
to B<wc>). If a list of files are given as arguments to B<faswc>,
tallies are calculated by file as well as in total. If input is over
STDIN, only totals are output.

Options specific to B<faswc>:
  -B<s>, B<--sequences>                   tally sequences only
  -B<c>, B<--characters>                  tally characters only

Options general to FAST:
  -B<h>, B<--help>                  	 print a brief help message
  B<--man>             	           print full documentation
  B<--version>                         print version
  B<-l>, B<--log>                         create/append to logfile	
  -B<L>, B<--logname>=<string>            use logfile name <string>
  -B<C>, B<--comment>=<string>            save comment <string> to log
  B<--format>=<format>                 use alternative format for input  
  B<--moltype>=<[dna|rna|protein]>     specify input sequence type
  B<-q>, B<--fastq>                       use fastq format as input and output
=head1 INPUT AND OUTPUT

B<faswc> is part of FAST, the FAST Analysis of Sequences Toolbox, based
on Bioperl. Most core FAST utilities expect input and return output in
multifasta format. Input can occur in one or more files or on
STDIN. Output occurs to STDOUT.  

=head1 OPTIONS

=over 8


=item B<-s>, 
      B<--sequences>

Output tallies of sequences only by file and/or in total.

=item B<-c>, 
      B<--characters>

Output tallies of sequence characters only by file and/or in total.

=item B<-h>,
      B<--help>

Print a brief help message and exit.

=item B<--man>

Print the manual page and exit.

=item B<--version>

Print version information and exit.

=item B<-l>,
      B<--log>

Creates, or appends to, a generic FAST logfile in the current working
directory. The logfile records date/time of execution, full command
with options and arguments, and an optional comment.

=item B<-L [string]>,
      B<--logname=[string]>

Use [string] as the name of the logfile. Default is "FAST.log.txt".

=item B<-C [string]>,
      B<--comment=[string]>

Include comment [string] in logfile. No comment is saved by default.

=item B<--format=[format]> 		  

Use alternative format for input. See man page for "faslen" for
allowed formats. This is for convenience; the FAST tools are designed
to exchange data in Fasta format, and "fasta" is the default format
for this tool.

=item B<-m [dna|rna|protein]>,
      B<--moltype=[dna|rna|protein]> 		  

Specify the type of sequence on input (should not be needed in most
cases, but sometimes Bioperl cannot guess and complains when
processing data).

=item B<-q>
      B<--fastq>

Use fastq format as input and output.

=back

=head1 EXAMPLES

Count the number of sequences in data1.fas and data2.fas and the total:

=over 8  

B<faswc> -s data1.fas data2.fas

=back

=head1 SEE ALSO

=over 8

=item C<man FAST>

=item C<perldoc FAST>

Introduction and cookbook for FAST

=item L<The FAST Home Page|http://compbio.ucmerced.edu/ardell/FAST>"

=back 

=head1 CITING

If you use FAST, please cite I<Lawrence et al. (2015). FAST: FAST Analysis of
Sequences Toolbox. Bioinformatics> and Bioperl I<Stajich et al.>.

=cut
