#!/usr/bin/perl -w

# S1 File. Sampling Perl script.

# sampling.pl
# Perl script for random sampling gene bins

# Input: for each bin a pair of integers indicating
#        the number of genes to select, the number of genes in the bin.
# ---------------------------------------------------------------------
# Bins control of transcript length:
# bin_1: 11,946
# bin_2: 218,3199
# bin_3: 641,3323
# bin_4: 659,2216
# bin_5: 537,1524
# bin_6: 448,890
# bin_7: 310,579
# bin_8: 342,537
# bin_9: 261,407
#
# Bins control of GC-content:
# bin_1: 99,585
# bin_2: 314,1235
# bin_3: 519,1536
# bin_4: 519,1395
# bin_5: 457,1183
# bin_6: 349,1045
# bin_7: 268,884
# bin_8: 206,979
# bin_9: 191,905
# bin_10: 192,937
# bin_11: 215,1490
# bin_12: 98,1447
#
# Bins control of germline gene expression:
# bin_1: 133,435
# bin_2: 385,1648
# bin_3: 486,1860
# bin_4: 410,1727
# bin_5: 257,1124
# bin_6: 96,463
# bin_7: 42,214
#
	
# Output: for each bin a list of 1 and 0 indicating if the corresponding
#         gene was selected or not, respectively.

use strict;

# read bin info

my $inpFile = "";
my @binA = ();  # bin info
my $b = 0;      # bin index

if($#ARGV == 0) {
	$inpFile = $ARGV[0];
}
else {
	print "Use:\n";
	print $0." bins_file.txt\n";
	exit;
}

open(INP,"<$inpFile") || die "cannot open $inpFile file";
while(<INP>)
{
	if ($_ =~ /([0-9]+),([0-9]+)\n/) {
		$binA[$b][0] = $1;
		$binA[$b][1] = $2;
		$b++;
	}
}
close INP;

# do sampling

my $numSamplings = 10;  # number of sampling to do

for(my $i=1; $i<=$numSamplings; $i++) {
	doSampling($i);
}

sub doSampling
{
	my ($sn) = @_;
	
	my $RFile   = "R.txt";
	my $ROFile  = "Rout.txt";
	my $outFile = "sampling_".$sn.".txt";
	my $command = "";
	
	# R code
	open(RF,">$RFile") || die "Error on creating file: $RFile\n";
	print RF "library(sampling)\n";
	print RF "cat(\"# INIT -------\",file=\"".$outFile."\",sep='\t',fill=TRUE)\n";
	for(my $i=0;$i<scalar(@binA);$i++) {
		doBinSampling($i+1,$binA[$i][0],$binA[$i][1],$outFile);
	}
	print RF "cat(\"# END -------\",file=\"".$outFile."\",sep='\t',fill=TRUE,append=TRUE)\n";
	close RF;

	$command = "R --vanilla < $RFile > $ROFile";
	system($command);
}

sub doBinSampling
{
	my ($bn,$sn,$N,$of) = @_;
	
	print RF "cat(\"# Sampling Bin $bn -------\",file=\"".$of."\",sep='\t',fill=TRUE,append=TRUE)\n";
	print RF "s=srswor($sn,$N)\n";
	print RF "for(i in 1:$N) {\n";
	print RF "   cat(s[i],file=\"".$of."\",sep='\n',fill=TRUE,append=TRUE)\n";
	print RF "}\n";
}

# END ------------------------------------------------

