#!/usr/sbin/perl
#
# AB:
#
# converts CHARMM top file to models.lib format
#

# chargfe cutoff
$cut = 0.3;

# reads current MODELS_LIB entry names
@lines=`cat $ENV{"MODELS_LIB"}`;
@PRES=grep(s/^PRES\s*(\S+)\s*\n$/\1/, @lines);
@RESI=grep(s/^RESI\s*(\S+)\s*\n$/\1/, @lines);
#print scalar(@PRES),  ":", scalar(@RESI),  ":", scalar(@lines), "\n";

#print join(":", @PRES);
#
# read ATOM lines for each RESI or PRES line
#

foreach (<>)
  {
  if (/^(RESI|PRES)\s*(\S+)/)
    {
    ($t, $rname)=/^(RESI|PRES)\s*(\S+)/ ;
    $text{$rname}="*\n$t $rname\n";
    }
  if (/^ATOM\s+\S+\s+(\S+)/)
    {
    ($iupac,$atom,$charge)=/^ATOM\s+(\S+)\s+(\S+)\s+(\S+)/ ;
    $isH = substr($atom, 0, 1) eq 'H';
    $isPolarH = $isH && ($charge>$cut || $charge<-$cut);
# ALLH
    $text{$rname}.=sprintf("ATOM     %-5.5s", $atom);
# POLH 
    if ($isH && !$isPolarH) {$text{$rname}.=sprintf("%-5.5s", "####");}
    else      {$text{$rname}.=sprintf("%-5.5s", $iupac);}
# HEAV 
# MCCB
# MNCH 
# MCWO 
# CA   
# MNSS 
    for($i=0;$i<6;$i++)
      {
      if ($isH) {$text{$rname}.=sprintf("%-5.5s", "####");}
      else      {$text{$rname}.=sprintf("%-5.5s", $atom);}
      }
# CA3H
    $text{$rname}.=sprintf("%-5.5s", "####");  
    $text{$rname}.="\n";
    }
  }


foreach $rname (sort keys %text)
  {
  print $text{$rname} if !grep($rname eq $_, @RESI, @PRES);
  }
