#!/usr/bin/perl -w
# energysortcoord.pl

#   This perl script was written by 
#   Lennie Damrauer at Denver's Childrens' Hospital, January 2005.
#   Its purpose is to extract useful data from RUNTYP=GLOBOP outputs,
#   energies and coordinates, which are tedious to pick through by hand.
#   It was verified to be working as of December 2008!

print "\n\n\nThis program lists the 10 lowest energies in decreasing 
energy order.\n\n";

while(1)
    {
     $passedfilename = getFilename();
     if (-e "$passedfilename.trj")
        {
         print "\nThe name of the file you want to process is 
$passedfilename\.trj\n";
         last;
        }
     else
        {
         print "\nThe file you asked for doesn't exist. The name you 
typed is $passedfilename\.\n";
        }
    }

open(IN,"< $passedfilename.trj") or die "\nThe file 
$passedfilename.trj does not exist in this directory\.\n";

while (<IN>)
    {
     chomp;
     @linecontent = split /\s+/,$_;
     if ($linecontent[0] eq "ENERGY")
        {
          #print "\n$linecontent[2]\t $linecontent[8]\n";
          push @linesort, $linecontent[2]."\t".$linecontent[8];
#    next line skips the blank line after "ENERGY" lines...
          <IN>
        }
    }
@sortedfile = sort @linesort;

print "\n\nThe 10 lowest energies in sorted order are: \n\n";

print "ENERGY\t\tAccepted Global Search Point\n";
print "======\t\t============================\n";


for ($i=0; $i<10; $i++)
    {
     $aline=pop @sortedfile;
     print "$aline\n";
    }

while (1)
    {
     print "\nDo you want coordinates? ";
     $answer = <STDIN>;
     chomp($answer);
     if ($answer =~ m/no/i || $answer =~ m/n/i)
        {
         last;
        }


     print "\nFor which global search point do you want the coordinates? ";
     $searchpt = <STDIN>;
     chomp($searchpt);


     open(IN,"< $passedfilename.trj") or die "\nThe file 
$passedfilename.trj does not exist in this directory\.\n";
     $continue = "yes";
     $foundit = "no";
     while (<IN>)
        {
         chomp($_);
         if ($continue eq "no")
            {
             last;
            }
         if ($_ =~ m/ENERGY/ && $_ =~ $searchpt)
            {
             print "$_";
             $foundit = "yes";
             while (<IN>)
                {
                 if ($_ =~ m/ENERGY/)
                    {
                     $continue = "no";
                     last;
                    }
                 print "$_";
                }
            }
        }
     if ($foundit eq "no")
        {
         print "\nCould not find Global Search Point $searchpt\.\n";
        }

     close(IN);
    }
print "\nEnd of program\.\n";


#subroutines
sub getFilename
{
  print "Please enter the filename without the .trj suffix: ";
  $filename = <STDIN>;
  chomp($filename);

  return $filename;
}
