#!/usr/bin/perl
# usage:  sorthb.pl infile dynoutfrq
# infile is the xxx-hbond.out file generated by hbond.inp/contact.inp
#  from charmm.  It should contain some sort of identifier.  Example:
#   CE8K12-aa1-hbond.out (aa1 replica of a CE8K12 peptide)
#  dynoutfrq must be known/found from the aarex job file (defaults to 100)
#
#
#
#
$infile = $ARGV[0];
$npoint = $ARGV[1];
$outfile = $infile;
substr($outfile, -4, 4) = ""; # drop that suffix
open(INFILE, $ARGV[0]) or die "Cannot open $ARGV[0]\nYou must specify a file to fix!!\n\n";
open(OUTFILE, ">$outfile-TS.dat") or die "cannot open $outfile for writing\n";
flock(OUTFILE, 2);
print OUTFILE "#  Timestep   2       3-10    Alpha     Pi        6        7       total\n";
my $x = 0;
my $y = 0;
my $time = 0;
my $span = 0;
my $infile = 0;
my @count = 0;
# Initialize array
# this should really be a whileloop!
for $x (0 .. $npoint) { #
    $sum[$x] = 0;
    for $y (0 .. 7) { # five cols of data?
	$count[$x][$y] = 0;
    }
}
foreach $line (<INFILE>)
{
    ($junk1,$resnoi,$residi,$atomi,$dash1,$junk2,$resnoj,$residj,$atomj,$lifetime,$time) = split(' ', $line);
    $span=abs($resnoi - $resnoj);
    if ($span > 1) {
#	$time = int($time/5 - 2); # time is counted by 5ps (though we should have it
	# figure this out from the SKIP value
	# "-2" to start at zero (first) element
	$count[$time*10][$span] += 1;
	$sum[$time*10] += 1;
    }
    next;
}

format OUTFILE =
@####.## @>>>>>>  @>>>>>>  @>>>>>>  @>>>>>>  @>>>>>>  @>>>>>>  @>>>>>>
$time,$count[$x][2],$count[$x][3],$count[$x][4],$count[$x][5],$count[$x][6],$count[$x][7],$sum[$x]
.
for $x (0 .. $npoint) { # 
    #    $time = (2 + $x)*5;
    $time = $x/10;
    write (OUTFILE);
    #    print OUTFILE "$time    $count[$x][2]   $count[$x][3]   $count[$x][4]   $count[$x][5]   $count[$x][6]   $count[$x][7]    $sum[$x] \n";
}

close(OUTFILE);

