#!/usr/bin/perl -w
# match-sort-3top (previously: match-counter-3top-new)
# D. Gonze - 18/07/2001
# Revised - 08/04/2003

# ---------------------------------------------------

if(scalar@ARGV==2)
{
  $infilename=$ARGV[0];
  $outfilename=$ARGV[1];
  &counter($infilename,$outfilename);
}
else
{
  print "You have to give 2 arguments: input file, output file\n";
}

# ---------------------------------------------------

sub counter {

  my ($infilename,$outfilename)=@_;
  my $i;
  open INFILE, $infilename or die "Error: can\'t open the file $infilename!\n";
  open OUTFILE, ">$outfilename";

  $top[0]=0;     
  $top[1]=0;
  $top[2]=0;
  $previousgene="aaaa";
  $first=1;

  foreach $line (<INFILE>) {
    chomp $line;
    @line=split /\t/,$line;

       if ($line[0] eq $previousgene){
         if ($line[1] >= $top[2]){
           $top[2]=$line[1];
	       @top= sort {$b <=> $a} @top;
         }
	     $previousgene=$line[0];
       }
	   
       else{
         if ($first==0){
           print OUTFILE "$previousgene\t$top[0]\t$top[1]\t$top[2]\n";
         }
         $first=0;
  	     $top[0]=0;     
  	     $top[1]=0;
         $top[2]=$line[1];
	     @top= sort {$b <=> $a} @top;
 	     $previousgene=$line[0];
       }
   }
}
