#!/usr/bin/perl -w
#
# munge_refseqs.pl
#
# Companion script to "mung_barcoded_reads.pl" to attach 6nt barcodes
# to amplicons and endoreduplicate to create pseudoref sequences.
#
# Adapted to attach barcodes to each end of raw ref, suitable for alignment
# with the munged PE reads
#
# Martin.Trick@bbsrc.ac.uk, 29/3/2011
#
# Need to attach reverse complemented barcodes to distal ends
# Martin.Trick@bbsrc.ac.uk, 13/4/2011
#

unless (@ARGV == 3){
  print "Usage: mung_refs.pl <barcode lookup> <targets fasta file> <output fasta file>\n";
  exit;
}

my %barcodes = ();
my %targets = ();

my $barcode_length = 6;
my $duplicate = 4; # endoreduplication level for barcodes

# The anchor primer sequence
my $m13 = 'TGTAAAACGACGGCCAGT';

open (BARCODES, "<$ARGV[0]") or die "Couldn't open input (barcodes) file ($!)\n";
open (TARGETS, "<$ARGV[1]") or die "Couldn't open input (targets) file ($!)\n";
open (FASTA, ">$ARGV[2]") or die "Couldn't open output file ($!)\n";

while (<BARCODES>) {
  chomp;
  s/\r//g;
  my @cols = split;
  # The barcode is not separated from the M13 primer in the file
  $cols[1] = substr($cols[1],0,$barcode_length);
  # Key on barcode name, not sequence
  $barcodes{$cols[0]} = $cols[1];
  # Mung it now
  $barcodes{$cols[0]} x= $duplicate;
}
close BARCODES;

while (<TARGETS>) {
  s/\r//g;
 if (/^>([\w\_]+)\n/) {
    $id = $1;
    next;
  }
  $targets{$id} .= $_;
}
close TARGETS;


# Generate the pseudo-refs
foreach my $target(sort keys %targets) {
  chop $targets{$target};
  foreach my $barcode(sort keys %barcodes) {
    my $revcom = reverse($barcodes{$barcode});
    $revcom =~ tr/ACGT/TGCA/;
    print FASTA ">$barcode-$target\n";
    print FASTA "$barcodes{$barcode}" . "$targets{$target}" . "$revcom" . "\n";
  }
}

close FASTA;
