#!/usr/bin/env perl

# check BED file : check whether tag mapping on chromosomes is correct
# usage: ./check_bed.pl <-a species>] <file.bed>

use strict;
use Getopt::Std;
use Storable qw (retrieve nstore);         # package to store persistently variables in files [http://search.cpan.org/author/AMS/Storable-2.07/Storable.pm]

my %opts;
getopt('as', \%opts);  # -a takes arg. Value in %opts, Hash keys will be the switch names
&Usage() unless $opts{'a'} || $opts{'s'};
if (exists $opts{'s'}) {
    print STDERR "WARNING: option -s is deprecated. Please use option -s instead.\n";
    $opts{'a'} = $opts{'s'};
}

# TODO: shouldn't there be -i/--db as in the orther Perl scripts?
my $DB = './';
my $chr2SV = retrieve($DB."chro_idx.nstorage");

# open the BED file
open(my $BED, "grep \'\^chr\' $ARGV[0]|") || die "can't open $ARGV[0] : $!";
#open(my $BED, "$opts{'f'}") || die "can't open $opts{'f'} : $!";
# TODO: make the program able to read its input on STDIN. If we only want lines
# that start with 'chr', as the above grep(1) call suggests, this can be done
# from within Perl instead of calling another program.

my $cnt = 0;
my $err_cnt = 0;

while(<$BED>) {
    chomp;
    my @f=split/\t/;
    my $chr_len = $chr2SV->{'length'}->{$chr2SV->{$opts{'a'}}->{$f[0]}};
    $cnt++;
    #print "chrom: $f[0] length: $chr_len\n";
    if ($f[1] > $chr_len or $f[2] > $chr_len) {
        print STDERR "Error line $cnt : position $f[1] exceeds chrom length $chr_len (chrom: $f[0] )!\n";
        $err_cnt++;
    }
}
close($BED);

if ($err_cnt) {
    print STDERR "\n\nWarning : Out of a total of $cnt BED lines, $err_cnt lines could not be mapped to the given genome assembly.\nPlease, check that the assembly you're using is the correct one.\n\n";
} else {
    print STDERR "\ncheck_bed: correct.\nTotal number of BED lines : ($cnt)\n\n";
}


sub Usage {
    print STDERR <<"_USAGE_";

    check_bed.pl -a <species> <BED file>

        Check whether tag positions on chromosomes are correctly mapped (e.g. positions do not exceed cromosome length).

_USAGE_
    exit(1);
}

1;

