#!/usr/sbin/perl
# program to average pdb coordinates in the STAR format
#
#  D.E. Volk 3/22/2002 UTMB Galveston volk@nmr.utmb.edu
#
#  usage: average_starpdb.pl infile outfile numatoms
#
#        OPEN INPUT PEAK AND ASSIGNMENT FILES		
#
if (( @ARGV < 3) or ($ARGV[0] =~ /^-h/))
  {
  print "\n";
  print "\n";
  print "Usage ./average_starpdb.pl infile.pdb outfile.pdb largest_atom_number(in first model)\n";
  print "\n";
  print "\n";
  exit(1);
  }
#
$infile = shift(@ARGV);
$outfile =  shift(@ARGV);
$largest_atom = shift(@ARGV);
#
open(MYINFILE, "$infile") || die "Cannot open file $infile\n";
#
#        REMOVE OLD OUTPUT FILES IF THEY EXIST
#
	if (-e "$outfile") {unlink("$outfile");}
#
open(OUT,">>$outfile") || die "Cannot open file $outfile";
#
#
#CREATE initial hashes for all atom numbers <= $largest_atom
#
while(<MYINFILE>)
  {
   chomp;
   s/^\s+//;  #remove leading white spaces
   ($v1,$v2,$v3,$v4,$v5,$v6,$v7,$v8,$v9,$v10,$v11)=split(/\s+/,$_);
   if (($v1 =~ /^ATOM/) || ($v1 =~ /^HETATM/))
   {
     if ($v2 <= $largest_atom)
     {
       $LABEL{$v2} = $v1;
       $ATOM{$v2} = $v3;
       $BASE{$v2} = $v4;
       $STRAND{$v2} = $v5;
       $RESNUM{$v2} = $v6;
       $XVAL{$v2} = 0.0;
       $YVAL{$v2} = 0.0;
       $ZVAL{$v2} = 0.0;
     }
   }
  }
close(MYINFILE);
#
#      ADD X,Y, AND Z VALUES TO THE HASH FOR AVERAGING	
#
open(MYINFILE, "$infile") || die "Cannot open file $infile\n";
while(<MYINFILE>)
  {
   chomp;
   s/^\s+//;  #remove leading white spaces
   ($v1,$v2,$v3,$v4,$v5,$v6,$v7,$v8,$v9,$v10,$v11)=split(/\s+/,$_);
   if (($v1 =~ /^ATOM/) || ($v1 =~ /^HETATM/))
   {
     while ($v2 >= $largest_atom + 1) 
      {
       print "v2 is $v2\n";
       $v2 = $v2 - $largest_atom;}
       print "final v2 is $v2\n";
     $XVAL{$v2} = $XVAL{$v2} + $v7;
     $YVAL{$v2} = $YVAL{$v2} + $v8;
     $ZVAL{$v2} = $ZVAL{$v2} + $v9;
   }
  }
close(MYINFILE);
#
#
foreach $atnum (sort{$a<=>$b} keys %ATOM)
  {
  $label = $LABEL{$atnum};
  $atom = $ATOM{$atnum};
  $base = $BASE{$atnum};
  $strand = $STRAND{$atnum};
  $resnum = $RESNUM{$atnum};
  $x = $XVAL{$atnum} / 6;
  $y = $YVAL{$atnum} / 6;
  $z = $ZVAL{$atnum} / 6;
  write OUT
  }
#
format OUT =
@<<<<< @### @>>>  @> @ @##@#######.###@###.###@###.###  0.00  0.00 
$label,$atnum,$atom,$base,$strand,$resnum,$x,$y,$z
.
# That's all folks
