#!/usr/bin/perl -w

###
#Description: This perl script is used to extract alignments with one or more than one concordantly alignment from bowtie -a;
#Usage: perl $0 [options] -i in.sam --uniq uniq.sam --multi multi.sam
#Author: Shuo Zhang
#History: 2016-05-04
###

my %count;
die "wrong in and out file number: $!" unless @ARGV==4;
open IN,'<',$ARGV[0] or die "Cannot open the alignment count file: $!";
while (my $line=<IN>){
	chomp $line;
	my ($num) = $line=~ /(\d+) HWI/;
	my ($id) = $line=~ /(HWI.*)/;
	die if $num%2 != 0; #the number of alignment should be mutliple of 2
	$count{$id}=$num;
}
close IN;

open SAM,'<',$ARGV[1] or die "Cannot open the input .sam file";
open UNIQ,'>',$ARGV[2] or die "Cannot open the uniq.sam file";
open MULTI,'>',$ARGV[3] or die "Cannot open the multi.sam file";
while (my $line=<SAM>) {
	chomp $line;
	my $id=(split /\t/,$line)[0];
	if ($count{$id}==2){
		print UNIQ "$line\n";
	}
	else {
		print MULTI "$line\n";
	}
}
close SAM;
close UNIQ;
close MULTI;

	
