#!/usr/bin/env perl
# PROJECT: CASAVA
# MODULE:  $RCSfile: export2fastq.pl,v $
# AUTHOR:  Tony Cox
#
# Copyright (c) 2008 Illumina
# This software is covered by the "Illumina Genome Analyzer Software
# License Agreement" and the "Illumina Source Code License Agreement",
# and certain third party copyright/licenses, and any user of this
# source file is bound by the terms therein (see accompanying files
# Illumina_Genome_Analyzer_Software_License_Agreement.pdf and
# Illumina_Source_Code_License_Agreement.pdf and third party
# copyright/license notices).
#
# The script creates a fastq file out of an export file
#

use warnings FATAL => 'all';
use strict;
use POSIX qw(strftime);

use IO::File;
use Sys::Hostname;
use Carp;
use Getopt::Long;

use lib '/home/psgendb/local/pkg/CASAVA_v1.8.2-build/lib/CASAVA-1.8.2/perl';
use Casava::Common::Log;
use Casava::Common::IOLib qw(executeCmd &genId
  readXML writeXML);

use Casava::PostAlignment::Sequencing::Config
  qw(loadConfiguration %chrEnds %CONF_APP %CONF_PROJ %runsConfig
  writeRunsConfigXML createExperiments);
use Casava::PostAlignment::Sequencing::NCBIExport;

$| = 1;

my $runId             = "";
my $setId             = "";
my $lane              = "";

my $numberOfLevels  = 81;
my $contactPerson   = "__CONTACT_PERSON__";
my $contactEmail    = "__CONTACT_EMAIL__";
#my $contactEmail    = "data_submission\@illumina.com";
#my $contactPerson   = "Sean Humphray";
my $instrumentModel = "Illumina Genome Analyzer II";

my $studyAccessionId  = "__STUDY_ACCESSION_ID__";
my $sampleAccessionId = "__SAMPLE_ACCESSION_ID__";
my $submissionId      = "__SUBMISSION_ID__";
my $studyName         = "__STUDY_NAME__";
my $sampleId          = "__SAMPLE_ID__";
my $libraryName       = "__LIBRARY_NAME__";


my $srfDir = "";

my $usage =
    "export2fastq.pl [options]\n"
  . "\t-p, --projectDir   - Project directory\n"
  . "\t-r, --runId        - run id\n"
  . "\t-s, --setId        - set id\n"
  . "\t-l, --lane         - lane id\n";

my $featureStorageDiff;

my $projectDir = "";
my $help       = 0;
my $target     = "";
my $result     = GetOptions(
    "projectDir|p=s" => \$projectDir,
    "runId|r=s"      => \$runId,
    "setId|s=s"      => \$setId,
    "lane|l=s"       => \$lane,
    "target|t=s"          => \$target,
    "srfDir=s"            => \$srfDir,
    "submissionId=s"      => \$submissionId,
    "studyAccessionId=s"  => \$studyAccessionId,
    "sampleAccessionId=s" => \$sampleAccessionId,
    "studyName=s"         => \$studyName,
    "sampleId=s"          => \$sampleId,
    "contactPerson=s"     => \$contactPerson,
    "contactEmail=s"      => \$contactEmail,
    "instrumentModel=s"   => \$instrumentModel,
    "numberOfLevels=s"    => \$numberOfLevels,
    "libraryName=s"       => \$libraryName,
    "help|h"              => \$help
);

if ( $result == 0 ) {
    errorExit "\n\n$usage";
}
errorExit "ERROR: Incorrect number of arguments\n$usage"
  if ( $projectDir eq "" );
loadConfiguration($projectDir);
################################################################################
# Configurationsub readFeatures($;\%)
my $cmd             = "";
my $timeStampFormat = $CONF_APP{formatTimeStamp};
my $hostname        = hostname();
my $argvStr         = join ' ', @ARGV;
my $dirCurrentBuild = $CONF_PROJ{dirBuildParsed};
my $sort_txt_f      = 'sorted.txt';
my @reads           = ();
my $export2FastqCmd = File::Spec->catfile('/home/psgendb/local/pkg/CASAVA_v1.8.2-build/bin', 'CASAVA') .' -a Export2Fastq';
################################################################################
printLog(
    "Running $hostname:[$0 " . $argvStr . "] at "
      . ( strftime $timeStampFormat, localtime ) . "\n",
    5
);
createExperiments(
            $projectDir,
            File::Spec->catfile(
                $projectDir, "/conf/", $CONF_APP{runConfFileName}
            ),
            %runsConfig
        );
if ( $target eq "texp2fastq" ) {
    errorExit "ERROR: Incorrect number of arguments\n$usage"
           if ( $runId eq "" || $setId eq "" || $lane eq "" );
  
    export2fastq( $projectDir, %runsConfig, $runId, $lane, $setId );
    fastq2zip( $projectDir, %runsConfig, $runId, $lane, $setId );
}
elsif ( $target eq "sraXml" ) {

    my %XMLparameters = (
        submissionId      => $submissionId,
        studyAccessionId  => $studyAccessionId,
        sampleAccessionId => $sampleAccessionId,
        contactPerson     => $contactPerson,
        contactEmail      => $contactEmail,
        studyName         => $studyName,
        sampleId          => $sampleId,
        libraryName       => $libraryName,
        instrumentModel   => $instrumentModel,
        numberOfLevels    => $numberOfLevels,
        casavaVersion     => $CONF_PROJ{appVersion}
    );
    my %sraExperiments = ();
    createSraExperiments($projectDir, %runsConfig, %sraExperiments);
    my $reportPath =
                  File::Spec->catfile( $projectDir, "stats", 'sraExperiments.xml' );
    writeRunsConfigXML( %sraExperiments, $reportPath );
    generateSrfXML( $projectDir, %XMLparameters, %sraExperiments );    
}

