#!/usr/bin/env perl
# This tool is used to extract SGA lines

use constant USAGE => "Usage: fetch_sga.pl <filename> <feature:begin-end>";

use Getopt::Std;

my %opts;
getopts('h');

if ($opt_h) {
  # Requested by user -> not an error -> STDOUT, exit 0
  print USAGE . "\n";
  exit 0;
}

if (2 != scalar @ARGV) {
    # Error -> STDERR, exit != 0
    die USAGE;
}


# [TJ] I'm assuming this means "filename" and refers to an SGA file. Note that
# $ARGV[0] is the _first argument_, contrary to C where argv[0] is the program's
# name as passed to exec().
$fn = $ARGV[0];
# [TJ] The second argument specifies, I suppose, a chromosome, start position, and
# end position, all in one word. Could be three separate arguments, but heck,
# when we have Perl regexp at our fingertips...
if ( $ARGV[1] =~ m/(\S+):(\d+)\-(\d+)/ ) {
    $sq = $1;
    $b  = $2;
    $e  = $3;
}

# [TJ] As I understand (I didn't write the code...), the search() sub does a binary
# search for lines with the correct chromosome and first position not smaller
# than the begin position passed as argument _minus 1000_ (not sure why). Once
# (well, if...) this is found, the SGA lines are printed as long as they match
# the arguments.
#
search();
while (<SGA>) {
    if (/(\S+)\s+\S+\s+(\S+)/) {
        if    ( $1 gt $sq ) { last }
        elsif ( $2 > $e )   { last }
        elsif ( $2 >= $b )  { print }
    }
}
exit; # This doesn't seem quite necessary.

sub search {

    # file initialization

    $size = -s $fn;
    open( SGA, "<$fn" );

    # dichotomy search

    $low  = 0;
    $high = $size;

    for ( $i = 0 ; $i < 20 ; $i++ ) {
        $n = $low + int( ( $high - $low ) / 2 );
        seek SGA, $n, 0;
        <SGA>;
        $line = <SGA>;

        #print $line;
        # [TJ] note that this is space-separated, not TAB-separated.
        if ( $line =~ m/(\S+)\s+\S+\s+(\S+)/ ) {
            if    ( $1 lt $sq )      { $low  = $n }
            elsif ( $1 gt $sq )      { $high = $n }
            elsif ( $2 < $b - 1000 ) { $low  = $n }
            elsif ( $2 > $b )        { $high = $n }
            else                     { last }
        }
        else { last }
    }
}

sub usage {
  print USAGE . "\n";
  exit 0;
}
