# Wrapper for MOSAiCS
# Written by Dongjun Chung, Jan. 15, 2013

#!/usr/bin/env perl;
use warnings;
use strict;
use File::Temp qw/tempfile/;
use File::Temp qw/tempdir/;
use File::Basename;

# parse command arguments
# inactive arguments: useChrfile, chrfile, excludeChr
# meaningless argument: analysisType (for later use)

die "Usage: perl mosaics_wrapper.pl [chip_path] [chip_file_format] [control_path] [control_file_format] [peak_path] [peak_file_format] [analysis_type] [report_summary_path] [report_gof_path] [report_exploratory_path] [PET?] [chromosome-wise?] [fdr_level] [frag_len] [bin_size] [capping] [signal_model] [bg_est_method] [d] [maxgap] [minsize] [thres] [parallel] [n_core]" unless @ARGV == 24;

my ( $chip_path, $chip_file_format, $control_path, $control_file_format, $peak_path, $peak_file_format, $analysis_type, $report_summary_path, $report_gof_path, $report_exploratory_path, $pet, $by_chr, $fdr_level, $frag_len, $bin_size, $capping, $signal_model, $bg_est_method, $d, $maxgap, $minsize, $thres, $parallel, $n_core ) = @ARGV;

# parse options: analysis type

if ( $analysis_type ne "IO" ) {
	print "Only 'IO' is supported for analysis type!\n";
	exit 1;	
}


# parse options: report summary

my $report_summary = "FALSE";
if ( $report_summary_path ne "None" ) {
	$report_summary = "TRUE";
}

# parse options: report GOF

my $report_gof = "FALSE";
if ( $report_gof_path ne "None" ) {
	$report_gof = "TRUE";
}

# parse options: report exploratory analysis

my $report_exploratory = "FALSE";
if ( $report_exploratory_path ne "None" ) {
	$report_exploratory = "TRUE";
}

# write a R scrip to run

my $tempdir_bin = tempdir();

my $cmd = qq|
	suppressPackageStartupMessages(library(mosaics))
	try( suppressPackageStartupMessages(library(parallel)), silent=TRUE )
	
	mosaicsRunAll( 
		chipFile="$chip_path", 
		chipFileFormat="$chip_file_format", 
		controlFile="$control_path", 
		controlFileFormat="$control_file_format",
		binfileDir="$tempdir_bin",
		peakFile="$peak_path", 
		peakFileFormat="$peak_file_format",
		reportSummary=$report_summary, 
		summaryFile="$report_summary_path", 
		reportExploratory=$report_exploratory,
		exploratoryFile="$report_exploratory_path", 
		reportGOF=$report_gof,
		gofFile="$report_gof_path", 
		PET=$pet, 
		byChr=$by_chr, 
		useChrfile=FALSE, 
		chrfile=NULL, 
		excludeChr=NULL, 
		FDR=$fdr_level, 
		fragLen=$frag_len, 
		binSize=$bin_size, 
		capping=$capping, 
		bgEst="$bg_est_method",
		d=$d, 
		signalModel="$signal_model", 
		maxgap=$maxgap, 
		minsize=$minsize, 
		thres=$thres, 
		parallel=$parallel,
		nCore=$n_core )
	
	q()
	|;

# run R

open( FT, "| R --slave --vanilla >& /dev/null" ) or die "Couldn't call R!\n";
print FT $cmd, "\n";
close FT or die "Couldn't finish R!\n";

exit;


