#!/usr/bin/perl

# you have to make a directory called "tmp" for this to work

use warnings;
use strict;

my $key = $ARGV[0];
my $lanes = $ARGV[1];
my $newdir = $ARGV[2];

open IN, $lanes;

while (<IN>){
	chomp;
	my @a = split (/\t/,$_);
	my $dir = $a[0];
	my $read1 = $a[1];
	my $FC = $a[2];
	my $lane = $a[3];
	my $read2 = $read1;
	my $CMD;

	#name of the new file
	my $Tricked = $newdir."/$FC"."_$lane"."_fastq.txt";	

	#name of read2
	$read2 =~ s/R1/R2/;
		
	#Copy the fastq files to a tmp dir
	$CMD = "cp $dir/$read1 tmp/r1.gz\n";
	system $CMD;
	$CMD = "cp $dir/$read2 tmp/r2.gz\n";
	system $CMD;

	# unzip them
	$CMD = "gunzip tmp/r1.gz\n";
	system $CMD;
	$CMD = "gunzip tmp/r2.gz\n";
	system $CMD;

	#get the right lines from the key file
	$CMD = 'awk \'$1 eq '."$FC".'\''." $key | awk ".'\'$2 == '."$lane".'\''."> TMPKEY.txt\n";
	system $CMD;
	
	#run the deplexing script
	$CMD = "perl bin/GBS_Fastq_BarcodeAdder_2Enzyme_v2.pl TMPKEY.txt tmp/r1 tmp/r2 >> $Tricked\n";
	system $CMD;

	#remove the tmp files.
        $CMD = "rm tmp/r1\n";
        system $CMD;
        $CMD = "rm tmp/r2\n";
        system $CMD;

	#print some helpful info. 
	print "\n\ndone $read1\n\n";
	
}
