#!/usr/bin/perl -w
# Combine Illumina lanes by adding up read depth at each base position

use strict;

print ("This script will add together the number of insert sites present at each base\n");

print ("Please enter the first .plot file to be processed:\n");
my $infile = <STDIN>;
chomp $infile;

print ("Please enter the second .plot file to be processed:\n");
my $infile2 = <STDIN>;
chomp $infile2;

print ("Please enter a prefix for the output file:\n");
my $tag = <STDIN>;
chomp $tag;

print ("Do these plot files specify direction (i.e. 2 column)?: (y/n)\n");
my $ans = <STDIN>;
chomp $ans;


# For 2 coloumn plot files
if ($ans =~ m/y/i){	
	# If the plot file is zipped
	if ($infile =~ m/\.gz$/){
		open (INFILE, "gunzip -c $infile |") or die ("Couldn't open pipe to $infile:$!");
	} else {
		open (INFILE, "<$infile") or die ("Couldn't open $infile:$!\n");
	}  
   
   # initialise arrays for holding numbers for forward/reverse strand
   my @fwd = ();
   my @rev = ();
   while (<INFILE>){
   chomp;	
     
      # extract the number for each strand
      my ($a, $b) = split(/\s+/, $_); #print ("$a\t$b"); <STDIN>;
      
      # store them in the relevant array
      push(@fwd, $a);
      push(@rev, $b); 
   } close INFILE;
   
   my $outfile = "$tag\.plot";
	open (OUTFILE, ">$outfile") or die ("Couldn't open $outfile:$!\n");

	my $i = 0;
	
   # If the second plot file is zipped
	if ($infile2 =~ m/\.gz$/){
		open (INFILETWO, "gunzip -c $infile2 |") or die ("Couldn't open pipe to $infile2:$!");
	} else {
		open (INFILETWO, "<$infile2") or die ("Couldn't open $infile2:$!\n");
	}
  
	while (<INFILETWO>){
	chomp; 
   
   	# extract the number for each strand
      my ($c, $d) = split(/\s+/, $_); #print ("$c\t$d"); <STDIN>;
      
      # add right strands together for combined file
      my $ftot = $c + $fwd[$i];
      my $rtot = $d + $rev[$i];
      
      print (OUTFILE "$ftot\t$rtot\n"); #<STDIN>;
      
      # increment to move along arrays with this plot file
      $i++;
	}
close INFILETWO;close OUTFILE;
}

# For 1 column plot files
elsif ($ans =~ m/n/i){
	
   # If the plot file is zipped
	if ($infile =~ m/\.gz$/){
		open (INFILE, "gunzip -c $infile |") or die ("Couldn't open pipe to $infile:$!");
	} else {
		open (INFILE, "<$infile") or die ("Couldn't open $infile:$!\n");
	}

	my @array = <INFILE>;
	close INFILE;

	my $outfile = "$tag\.plot";
	open (OUTFILE, ">$outfile") or die ("Couldn't open $outfile:$!\n");

	my $i = 0;

	open (INFILETWO, "<$infile2") or die ("Couldn't open $infile2:$!\n");
	while (<INFILETWO>){
	chomp;

		my $total = $_ + $array[$i]; #print ("$_ + $array[$i]"); <STDIN>;
  		print (OUTFILE "$total\n"); #<STDIN>;
   
   	$i++;
	}
	close INFILETWO;close OUTFILE;

print ("Finished combining files. Saved as $outfile\n");
}else{
print ("Couldn't determine plot file structure\n");
}

