#!/usr/bin/perl

# check BED file : check whether tag mapping on chromosomes is correct 
# usage: ./check_bed.pl <-s species>] -f <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('sf:', \%opts);  # -s, & -f take arg. Values in %opts, Hash keys will be the switch names
my $DB = "/db/genome/";
#my $DB = "/home/local/db/genome/";
my $chr2SV = retrieve($DB."chro_idx.nstorage");

&Usage() unless ($opts{'f'} && $opts{'s'});

# open the BED file
open(my $BED, "grep \'\^chr\' $opts{'f'}|") || die "can't open $opts{'f'} : $!";
#open(my $BED, "$opts{'f'}") || die "can't open $opts{'f'} : $!";

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

while(<$BED>) {
    chomp;
    my @f=split/\t/;
    my $chr_len = $chr2SV->{'length'}->{$chr2SV->{$opts{'s'}}->{$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 -s <species> -f <BED file>

    Check whether tag positions on chromosomes are correctly mapped (e.g. positions do not exceed cromosome length).
    
_USAGE_
    exit(1);
}

1;
