#!/usr/bin/perl
#input heavy atoms to arp/warp pdb file


open(HEAVYOUT,">${ARGV[0]}_") || die "Problem opening HEAVYOUT file in treat_heavy.";
open(ARPIN,$ARGV[1]) || die "Problem opening ARPIN file in treat_heavy.";

$num=0;
while ( $line=<ARPIN> ) 
{
#!!!!!!!!!!add better identification here!
  if ( $line =~ /^(ATOM..|HETATM).{5}\s*$ARGV[2]/ ) { $num++; syswrite(HEAVYOUT,$line); }
}
close(HEAVYOUT);

print("Number of found heavy atoms in arpin is:  $num\n");

if ($num > 0)
{
  system("cp -f ${ARGV[0]}_ $ARGV[0]");
}
else
{
  system("rm -f ${ARGV[0]}_");
  close(ARPIN);
  open(ARPIN,$ARGV[1]) || die "Problem opening ARPIN file in treat_heavy.";
  open(ARPOUT,">_$ARGV[1]") || die "Problem opening ARPOUT file in treat_heavy.";
  open(HEAVY,$ARGV[0]) || die "Problem opening HEAVY file in treat_heavy.";
  while ( $line=<ARPIN> ) 
  {
	syswrite(ARPOUT,$line);
  }
  while ( $line=<HEAVY> ) 
  {
	if ( $line =~ /^ATOM|HETATM/ ) { syswrite(ARPOUT,$line); }
  }
  close(ARPOUT);
  system("cp -f $ARGV[1] __$ARGV[1]");
  system("cp -f _$ARGV[1] $ARGV[1]");
}
