#!/usr/local/bin/perl
# This tool is used to extract SGA lines
#
$fn = $ARGV[0];
if($ARGV[1] =~ m/(\S+):(\d+)\-(\d+)/) {
   $sq=$1; $b=$2; $e=$3}

search();
while(<SGA>) {
   if(/(\S+)\s+\S+\s+(\S+)/) {
      if   ($1 gt $sq) {last}
      elsif($2 >  $e)  {last}
      elsif($2 >= $b)  {print}
      } 
   }
exit;

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;
   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}
   }
}
