+#
+# uniqcmp: compare two SAM files
+#
+
+sub uniqcmp {
+ my %opts = (q=>10, s=>100);
+ getopts('pq:s:', \%opts);
+ die("Usage: samtools.pl uniqcmp <in1.sam> <in2.sam>\n") if (@ARGV < 2);
+ my ($fh, %a);
+ warn("[uniqcmp] read the first file...\n");
+ &uniqcmp_aux($ARGV[0], \%a, 0);
+ warn("[uniqcmp] read the second file...\n");
+ &uniqcmp_aux($ARGV[1], \%a, 1);
+ warn("[uniqcmp] stats...\n");
+ my @cnt;
+ $cnt[$_] = 0 for (0..9);
+ for my $x (keys %a) {
+ my $p = $a{$x};
+ my $z;
+ if (defined($p->[0]) && defined($p->[1])) {
+ $z = ($p->[0][0] == $p->[1][0] && $p->[0][1] eq $p->[1][1] && abs($p->[0][2] - $p->[1][2]) < $opts{s})? 0 : 1;
+ if ($p->[0][3] >= $opts{q} && $p->[1][3] >= $opts{q}) {
+ ++$cnt[$z*3+0];
+ } elsif ($p->[0][3] >= $opts{q}) {
+ ++$cnt[$z*3+1];
+ } elsif ($p->[1][3] >= $opts{q}) {
+ ++$cnt[$z*3+2];
+ }
+ print STDERR "$x\t$p->[0][1]:$p->[0][2]\t$p->[0][3]\t$p->[0][4]\t$p->[1][1]:$p->[1][2]\t$p->[1][3]\t$p->[1][4]\t",
+ $p->[0][5]-$p->[1][5], "\n" if ($z && defined($opts{p}) && ($p->[0][3] >= $opts{q} || $p->[1][3] >= $opts{q}));
+ } elsif (defined($p->[0])) {
+ ++$cnt[$p->[0][3]>=$opts{q}? 6 : 7];
+ print STDERR "$x\t$p->[0][1]:$p->[0][2]\t$p->[0][3]\t$p->[0][4]\t*\t0\t*\t",
+ $p->[0][5], "\n" if (defined($opts{p}) && $p->[0][3] >= $opts{q});
+ } else {
+ print STDERR "$x\t*\t0\t*\t$p->[1][1]:$p->[1][2]\t$p->[1][3]\t$p->[1][4]\t",
+ -$p->[1][5], "\n" if (defined($opts{p}) && $p->[1][3] >= $opts{q});
+ ++$cnt[$p->[1][3]>=$opts{q}? 8 : 9];
+ }
+ }
+ print "Consistent (high, high): $cnt[0]\n";
+ print "Consistent (high, low ): $cnt[1]\n";
+ print "Consistent (low , high): $cnt[2]\n";
+ print "Inconsistent (high, high): $cnt[3]\n";
+ print "Inconsistent (high, low ): $cnt[4]\n";
+ print "Inconsistent (low , high): $cnt[5]\n";
+ print "Second missing (high): $cnt[6]\n";
+ print "Second missing (low ): $cnt[7]\n";
+ print "First missing (high): $cnt[8]\n";
+ print "First missing (low ): $cnt[9]\n";
+}
+
+sub uniqcmp_aux {
+ my ($fn, $a, $which) = @_;
+ my $fh;
+ $fn = "samtools view $fn |" if ($fn =~ /\.bam/);
+ open($fh, $fn) || die;
+ while (<$fh>) {
+ my @t = split;
+ next if (@t < 11);
+# my $l = ($t[5] =~ /^(\d+)S/)? $1 : 0;
+ my $l = 0;
+ my ($x, $nm) = (0, 0);
+ $nm = $1 if (/NM:i:(\d+)/);
+ $_ = $t[5];
+ s/(\d+)[MI]/$x+=$1/eg;
+ @{$a->{$t[0]}[$which]} = (($t[1]&0x10)? 1 : 0, $t[2], $t[3]-$l, $t[4], "$x:$nm", $x - 4 * $nm);
+ }
+ close($fh);
+}
+