#!/usr/bin/env perl

=head1 NAME

=head1 SYNOPSIS

  renameGapPrimers.pl [options] <primerLabel> <primerFile>

  Options:
  -log <file>  Log file (optional; default is createSubProjectPCRPrimerInfo.pl.log)
  -warn <file>  Warnings log file (optional; default is defined in gapRes.config)
  -h           Detailed message (optional)

=head1 DESCRIPTION

=head1 DEPENDENCIES

=head1 VERSION

$Revision: 1.1 $

$Date: 2010-01-06 22:19:57 $

=head1 AUTHOR(S)

Stephan Trong

=head1 HISTORY

=over

=item *

S.Trong 2010/01/06 creation

=back

=cut

use strict;
use warnings;
use Pod::Usage;
use Cwd;
use Cwd qw(abs_path);
use Carp;
use Carp qw(cluck);
use Getopt::Long;
use File::Path;
use File::Copy;
use File::Basename;
use FindBin qw($RealBin);
use lib "$RealBin/../lib";
use PGF::GapResolution::Warnings;
use PGF::Utilities::Logger;
use vars qw( $optHelp $optLogFile $optWarningsFile );

#============================================================================#
# INPUT VALIDATION
#============================================================================#
my $programExecution = abs_path(dirname($0))."/".basename($0)." @ARGV";

if( !GetOptions(
        "log=s"=>\$optLogFile,
        "warn=s"=>\$optWarningsFile,
        "h"=>\$optHelp,
    )
) {
    printhelp(1);
}

printhelp(2) if $optHelp;

if ( @ARGV != 2 ) {
    my $errMsg = "Required input parameters are missing in command line.";
    print STDERR "$errMsg\n";
    printhelp(1);
}

#============================================================================#
# INITIALIZATION
#============================================================================#

my $DEBUG = 0;
my $configFile = defined $ENV{GAPRES_CONFIG} ?
    $ENV{GAPRES_CONFIG} : "$RealBin/../config/gapRes.config";
my $OBJ_LOGGER = PGF::Utilities::Logger->new();
my $outputDir = getcwd;
my $OBJ_WARNINGS = PGF::GapResolution::Warnings->new(
    path=>$outputDir, logger=>$OBJ_LOGGER);
   $OBJ_WARNINGS->setLogFile($optWarningsFile) if $optWarningsFile;
my $logfile = $optLogFile ? $optLogFile : "$outputDir/".basename($0).".log";

my ($primerLabel, $primerFile) = @ARGV;
    
#============================================================================#
# VALIDATE INPUTS
#============================================================================#
my $errMsg = '';

# Set path for logging.
#
setFileForLogging($logfile);

# Log execution into log file.
#
logExecution($programExecution);

#============================================================================#
# MAIN
#============================================================================#

modifyPrimerFile($primerLabel, $primerFile);

# If warning messages present, then save in .warnings.out file.
#
$OBJ_WARNINGS->createFile() if $OBJ_WARNINGS->getNumberOfWarnings;

exit 0;

#============================================================================#
# SUBROUTINES
#============================================================================#
sub modifyPrimerFile {
    
    my $label = shift;
    my $primerFile = shift;
    
    return if !checkForFileExistence($primerFile);

    my $success = 0;
    my $currentDate = getCurrentDate();
    my @newPrimerEntries = ();
    
    unless (open IFILE, "$primerFile" ) {
        my $errMsg = "failed to open file $primerFile: $!\n";
        print STDERR "$errMsg";
        logError($errMsg);
        return $success;
    }
    while (my $primerEntry = <IFILE>) {
        if ( $primerEntry =~ /^name=(.+)\s*$/ ) {
    	    $primerEntry = "name=".modifyPrimerName($1, $label)."\n";
        }
		push @newPrimerEntries, $primerEntry;
    }
    close IFILE;

    unless (open OFILE, ">$primerFile" ) {
        my $errMsg = "failed to create file $primerFile: $!\n";
        print STDERR "$errMsg";
        logError($errMsg);
        return $success;
    }
	print OFILE @newPrimerEntries;
	close OFILE;

    $success = 1;

	return $success;

    
}

#============================================================================#
sub modifyPrimerName {
    my $primerName = shift;
    my $primerLabel = shift;

    my $newPrimerName = '';
    my $currentDate = getCurrentDate();

    foreach my $primerName (split /\s*,\s*/, $primerName) {
        if ( $primerName =~ /^s\d+c\d+c\d+/ ) {
            $newPrimerName .= "$primerLabel.$primerName.$currentDate,";
        }
    }

    $newPrimerName =~ s/,$//;
    $newPrimerName = $primerName if !length $newPrimerName;

    return $newPrimerName;

}

#============================================================================#
sub getCurrentDate {

    my $format = "%04d%02d%02d";
    my ($d,$m,$y) = (localtime)[3..5];
    $m++;
    $y+=1900;

    return sprintf( $format, $y, $m, $d);

}

#============================================================================#
sub checkForFileExistence {
    
    my $file = shift;
    
    my $success = 1;
    
    if ( !-s $file ) {
        my $errMsg = "file $file does not exist or is zero size.\n";
        logError($errMsg, 0);
        $success = 0;
    }
    
    return $success;
    
}

#============================================================================#
sub setFileForLogging {
    
    my $logFile = shift;
    
    $OBJ_LOGGER->setLogOutFileAppend($logFile);
    $OBJ_LOGGER->setLogErrorFileAppend($logFile);
    
}

#============================================================================#
sub logExecution {
    
    my $programExecution = shift;
    
    my $msg = "Command: ".$programExecution."\n".
              "Current directory: ".getcwd;
    logOutput($msg);
}

#============================================================================#
sub logError {
    my $message = shift;
    my $confess = shift || 0;
    
    $OBJ_LOGGER->logError($message);
    $OBJ_WARNINGS->add($message);
    
    if ( $confess ) {
        $OBJ_WARNINGS->createFile() if $OBJ_WARNINGS->getNumberOfWarnings;
        confess $message;
    }
    
}
    
#============================================================================#
sub logOutput {
    my $message = shift;
    my $printMsg = shift || 0;
    
    $OBJ_LOGGER->logOut($message);
    print "$message\n" if $printMsg;
}
    
#============================================================================#
sub logOutputFileCreation {
    
    my $outputFile = shift;
    
    $outputFile = abs_path($outputFile);
    
    my $fileExists = -s $outputFile ? 1:0;
    my $msg = $fileExists ? "Created $outputFile" :
        "failed to create $outputFile";
    logOutput($msg,1);
    
    return $fileExists;
    
}

#============================================================================#
sub printhelp {
    my $verbose = shift || 1;
    pod2usage(-verbose=>$verbose);
    exit 1;
}

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