#!/usr/bin/env perl
use strict;
use warnings;

# This code is part of the MOCAT analysis pipeline
# Code is (c) Copyright EMBL and BGI, 2012-2013
# This code is released under GNU GPL v3.

$|++;
my $prev_insert = "0";
my %fw;
my %rev;

while (<STDIN>) {
	next if ( $_ =~ /^\@/ || $_ =~ /^$/ );
	my @line = split "\t", $_;
	chomp $_;
	$line[0] =~ m/(.+)\/([12])/;
	my $insert    = $1;
	my $direction = $2;
	my $ref_id    = $line[2];
	if ( $insert ne $prev_insert ) {
		my %common = ();

		#put ref_ids that have been seen by both fw and rev into %common
		foreach my $k ( keys %fw ) {
			$common{$k}++ if exists $rev{$k};
		}
		if ( scalar( keys %common ) > 0 ) {
			foreach my $key ( keys %common ) {
				print $fw{$key};
			}
			foreach my $key ( keys %common ) {
				print $rev{$key};
			}
		}
        else {
			foreach my $key ( keys %fw ) {
				print $fw{$key};
			}
			foreach my $key ( keys %rev ) {
				print $rev{$key};
			}
		}
		%fw   = ();
		%rev  = ();
	}
	if ( $direction == 1 ) {    #a fw read has seen this ref_id
		$fw{$ref_id} .= $_ . "\n";
	}
	elsif ( $direction == 2 ) {    #a rev read has seen this ref_id
		$rev{$ref_id} .= $_ . "\n";
	}
	$prev_insert = $insert;
}

my %common = ();
foreach my $k ( keys %fw ) {
	$common{$k}++ if exists $rev{$k};
}
if ( scalar( keys %common ) > 0 ) {
	foreach my $key ( keys %common ) {
		print $fw{$key};
	}
	foreach my $key ( keys %common ) {
		print $rev{$key};
	}
}
		elsif ( scalar( keys %common ) == 0 ) {
			foreach my $key ( keys %fw ) {
				print $fw{$key};
			}
			foreach my $key ( keys %rev ) {
				print $rev{$key};
			}
		}

exit 0;
