##### getBarcode.pl 
##### Julie Zhu
##### June 17th 2015

#!usr/bin/perl
use strict;

if ($#ARGV <1) {
	print "usage: perl getBarcode.pl sequenceDir barcodeLength\n";
	print "example: perl getBarcode.pl fastq 16\n";
	exit(0);
}

my $seqdir = $ARGV[0];
my $barcodeLen = $ARGV[1];
my @seqfiles = <$seqdir/*>;
foreach my $file (sort@seqfiles) {
       getBarcode($file);
}

sub getBarcode 
{
	my $seqfile = shift;
	open(INFILE, "$seqfile") || die("Cannot open file $seqfile  $!\n");
	my @temp = split(/\//, $seqfile);	
	my $index1 = scalar(@temp) - 1;       
	my $outfile = $temp[$index1];
	my $outfile1 = "barcode-" . $outfile;
	my ($line, @line, $barcode);
	open(OUTFILE1, ">$outfile1") || die("Cannot open file $outfile1 $!\n");
	my $i =0;
	while (<INFILE>)
	{
		$line = $_;
		chomp $line;
		$i++;
		if ($i % 4 ==1)
		{
		      @line = split(" ", $line);	
		      @temp = split(":", $line[1]);
		      $barcode = substr($temp[scalar @temp - 1],0, $barcodeLen);
		      print OUTFILE1 "$line\n$barcode\n";

		}
		elsif ($i % 4 ==3 )
		{
		      print OUTFILE1 "$line\n";
		}
		elsif ($i % 4 == 0)
		{
		      print OUTFILE1 substr($line, 0, $barcodeLen) . "\n";
		}
	}
	close(INFILE);
	close(OUTFILE1);
}
