#! /usr/bin/perl 
# delete the INDELs that convered by another one.

# author: X.Gan

use strict;
use Getopt::Std;
use List::Util qw[min max];

my %opts =( S=>undef, t=>10, o=>1);
getopts('St:o:', \%opts);
my $isSam =$opts{S} ;
my $thrsh= $opts{t};
my $sortOrd=$opts{o}-1;

die "Usage: get_rnasta.pl bamfile > out.file\n" if (@ARGV <1); 

my $oldchid;
my $seqstr;

my $k=@ARGV;

my %ct;
for (my $i=0; $i<@ARGV; $i++) {

    my $bamfile = $ARGV[$i];
    if ( $isSam) {
	open(BAM_F, $bamfile) or die "Can't find the file";
    } else {
	my $cmd="samtools view $bamfile | ";
	open(BAM_F, $cmd) or die "Can't find the file";
    }

    my @sticky;
    while ( <BAM_F> ) {
	my $secline = $_;
	my ($contig_id2, $oritNum, $chid2, $startI2, $cig2, $mystrq2);	
	my $rub;
	my $cig;
	($contig_id2, $oritNum, $chid2, $startI2, $rub, $cig2,$rub, $rub, $rub, $mystrq2) = split(/\t/, $secline);
	$ct{$chid2}->[$i]++;
    }
    close(BAM_F);	
}

my @allkeys=keys %ct;
my @gg =reverse sort {  $ct{$a}->[$sortOrd]  <=>  $ct{$b} ->[$sortOrd]   } @allkeys;

my $header=join("\t", @ARGV);
$header =~ s/.bam//g;
print "\t",$header,"\n";
foreach (@gg) {
    my $key=$_;
    for (my $i=0; $i<$k;$i++) {
	$ct{$key} ->[$i] =0 if (!$ct{$key} ->[$i]);
    }
    print join("\t", $key, @{$ct{$key}}), "\n";
}



