#!/usr/bin/perl

 if ($ARGV[0] eq '') {
        print "USAGE: pot_energy.pl Chimera_reply_log_file  >output_file \nReturns: angles and energies (kJ/mol) from dihedral potential energy scan\n";
        exit;
 }
# change $delta_angle if a different increment is used
$delta_angle=30;

#read in Chimera_reply_log_file
unless (open(FILE,"<$ARGV[0]")){
       die("energy file not found");
}

@file=<FILE>;
$len=@file;
close(FILE);

#extract dihedral angle and associated energy from saved Chimera_reply_log file
$count=0;
$min_energy=10000;
for ($i=0;$i<$len;$i++) {
	if ($file[$i] =~ 'Dihedral') {
		chomp($file[$i]);
		@array=split(/ +/,$file[$i]);
		$ang=$array[5];
		}
	if ($file[$i] =~ 'Potential energy') {
		@array=split(/ +/,$file[$i]);
		$energy = $array[2];
		$energy=~s/,//g;
#find minimum energy
		if ($energy<$min_energy) {
			$min_energy=$energy;
		}
	}
#create hash of angle => energy
	if ($file[$i] =~ '100 of 100 conjugate gradient') {
		$points{$ang}=$energy;
	}

}

#subtract minimum energy from all angle/energy pairs
foreach my $key ( keys %points )
{
   $diff = $points{$key} - $min_energy;
	$points{$key}=$diff;
}

#sort angle/energy pairs with respect to angle
foreach (sort { $a <=> $b } keys(%points) )
{
    print "$_ $points{$_}\n"
}

