#!/usr/bin/perl
##################################################
#                                                #
#    00_cat_fastq_files_a.pl                     #
#    Time-stamp: <13/03/18 17:42:09 Shingo>      #
#                                                #
#                                                #
############################ Shingo Kikugawa #####

#================== POD description =============#

=head1 NAME

00_cat_fastq_files_a.pl - Concatenates paired-end FASTQ files in a specified directory
                         to unique files and move them to 'original_fastq' directory.

=head2 USAGE

00_cat_fastq_files_a.pl [Directory in which there are FASTQ files (must be *.fastq)]

for examples:
  00_cat_fastq_files_a.pl fastq_dir
  00_cat_fastq_files_a.pl . (for current directory)

=cut

#================================================#

#
# Start
#

#================== Libraries ===================#
use lib 'lib';
use strict;
use warnings;

# This program doesn't need 'Setting.pm' now.
# use Setting;


#================== Initial Settings ============#
# Directories for original FASTQ files.
# my $original_fq_dir = $Setting::original_fq_dir;
my $original_fq_dir = 'original_fastq';


#================== Global Variables ============#
# Command.
my $command = '';


#================== Main Routine ================#
if (!defined $ARGV[0]) {
  warn "Usage: $0 [Directory in which there are FASTQ files (must be *.fastq)]\n";
  exit;
}

# Make directories for original FASTQ files.
make_dirs();

# Get a "sorted" list of FASTQ files.
my @file_paths =  `find $ARGV[0] -type f -name '*.fastq' | sort`;
chomp @file_paths;
my $file_cnt = @file_paths;
# print map {"$_\n"} @file_paths;
# exit;


print STDERR "$file_cnt fastq files are found.\n";
print STDERR "Concatenate paired-end FASTQ files to unique files:\n";
my $mate_no_pre = 'R1';
foreach my $file_path (@file_paths) {
  my $file_name = (split(/\//, $file_path))[-1];

  if ($file_name =~ /^(\d+)(\w+)_(R1|R2).fastq$/) {
    my $index   = $1;
    my $sample  = $2;
    my $mate_no = $3;

    if ($mate_no_pre ne $mate_no) {
      $mate_no_pre = $mate_no;
      print STDERR "\n";
    }

    $command = "cat $file_path >> $sample\_$mate_no.fastq";
    print STDERR "$command\n";
    `$command`;

  } else {
    die "[Error] Invalid name of FASTQ file: $file_path!";
  }
}

# Move the original FASTQ files to $original_fq_dir.
$command = "mv *.fastq $original_fq_dir";
print STDERR "$command\n";
`$command`;


#==== Make directories for original FASTQ files ====#
sub make_dirs
{
  mkdir $original_fq_dir, 0755 or die "Can't make $original_fq_dir! $!" if !-d $original_fq_dir;
}


__END__
