#!/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    = "Remove duplicate sequence records in a multifasta data-stream.\n";
$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_delimiter = ":";

## 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 $concat               = undef;
my $delimiter            = $def_delimiter;
my $description_match    = undef;
my $id_match             = undef;

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,

	   'concat|c'                    => \$concat,
	   'delimiter|d=s'               => \$delimiter,
     'description|D'               => \$description_match,
     'id|I'                        => \$id_match,
     'fastq|q'                     => sub { $format = 'fastq'; },

	  ) 
  or pod2usage(2);
		  
pod2usage(1) if $help;
pod2usage(-verbose => 2) if $man;

if (!(-t STDIN) and (@ARGV != 0)) {
  pod2usage("$0: Requires exactly zero arguments when taking input from STDIN. Try $NAME -h for help."); 
}
elsif ((-t STDIN) and (@ARGV != 1)) {
  pod2usage("$0: Requires exactly one argument unless taking input from STDIN. Try $NAME -h for help.");
}
&FAST::log($logname, $DATE, $COMMAND, $comment) if ($log); 

my $match = 'seq';
if ($description_match){$match = 'desc';}
if ($id_match){$match = 'id';}

my $OUT = FAST::Bio::SeqIO->newFh('-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);
    }
}

while ($IN or @ARGV) {
  if (@ARGV) {
    my $file = shift (@ARGV);
    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);
    }
  }
  if ($IN) { 
    my $lastseq = undef;
    my $repeat = undef;
    my @ids = ();
    my $seq;
    while ($seq = $IN->next_seq()) {
      if (not defined $lastseq){
	# handle first sequence
	$lastseq = $seq;
	next;
      }
      else { #not first sequence
	my $seqseq = $seq->$match;
	my $lastseqseq = $lastseq->$match;

	if ($seqseq ne $lastseqseq) { #no repeat, or repeat is over

	  if ($concat and $repeat) { # repeat is over

	    $lastseq->id(join $delimiter,@ids);
	    undef @ids;

	  }

	  undef $repeat;
	  print $OUT $lastseq;
	  $lastseq = $seq;
	}
	else { # repeat

	  if ($concat) {
	    my $seqid = $seq->id;
	    if ($repeat) { # continuing repeat
	      push @ids, $seqid;
	    }
	    else { #new repeat
	      my $lastseqid = $lastseq->id;
	      push @ids, $lastseqid, $seqid;
	    }
	  }
	  
	  $repeat = 1;

	}

      }
    }
    # handle last sequence
    if ($repeat){
      if ($concat) { # repeat is over
	$lastseq->id(join $delimiter,@ids);
      }
      print $OUT $lastseq;
    }
    else {
      print $OUT $lastseq;
    }
    undef $IN;
  }
}



__END__

=head1 NAME

B<fasuniq> - Remove duplicate sequence records in a
multifasta file or datastream.

=head1 SYNOPSIS

B<fasuniq> [options] [MULTIFASTA-FILE]

[MULTIFASTA-DATA-ON-STDIN] | B<fasuniq> [options]

=head1 DESCRIPTION

B<fasuniq> removes duplicate sequence records in a
multifasta file or datastream. The sequences should be sorted 
such as output from B<fassort -s>. Only the sequence data itself must be
identical, not identifiers or descriptions. By default, the first
matching sequence record in a series of matches (including identifier
and description) is the one printed. IDs of adjacent duplicate sequence records 
can be concatenated to the printed sequence using the -c, --concat option.

Options specific to fasuniq:
  B<-c>, B<--concat>               concatenate identifiers 
  B<-d>, B<--delimiter>=<string>   use <string> between identifers [:] 
  B<-D>, B<--description>          match on description
  B<-I>, B<--id>                   match on identifiers

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<fasuniq> 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 file or on STDIN. Output
occurs to STDOUT. The FAST utility B<fasconvert> can reformat other
formats to and from multifasta.

=head1 OPTIONS

=over 8

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

Concatenate identifiers of repeated sequences in output 

=item B<-d [string]>,
      B<--delim=[string]>

Use delimiter [string] to concatenate identifiers. Default is ":"

=item B<-D>
      B<--description>

Removes duplicate sequences by matching on descriptions.

=item B<-I>
      B<--id>

Removes duplicate sequences by matching on identifiers.

=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 "fasconvert" 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

Remove duplicate sequences and append concatnated IDs of duplicate sequences to printed sequence:

=over 8

B<fassort -s> data1.fas | B<fasuniq -c>

=back


=head1 SEE ALSO

=over 8

=item C<man perlre>

=item C<perldoc perlre>

Documentation on perl regular expressions.

=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.> and Bioperl I<Stajich et al.>. 

=cut
