#!/usr/bin/perl -w
use strict;
# A simple perl script to find residues that are missing backbone atoms
# To use call the script with a PDB file, eg. ./find_miss_bb.pl 2eng.pdb
# would return: 
# HEADER    HYDROLASE (ENDOGLUCANASE)               29-JUN-95   2ENG              
# Residue GLY  112 is missing backbone atoms

my @residue= qw{ ALA CYS ASP GLU PHE GLY HIS ILE LYS LEU MET ASN PRO GLN ARG SER THR VAL TRP TYR };
my $i;
my @word;
my @resok;
my @nitr;
my @carb;
my @cara;
my @oxyg;
my $resid;

open (my $file,"$ARGV[0]");
my @ARRAY=<$file>;
close ($file);

foreach (@ARRAY) {
	chomp;
      @word  = (split(" "));
      if ($word[0] eq "HEADER" ){
              print "$_\n";
      }
      for ($i=0; $i<=19; $i++){
              if (substr($_,17,3) eq $residue[$i]) {
                      if (substr($_,0,4) eq "ATOM") {
	      	            $resid = substr($_,22,4);
                              $resok[$resid] = 0;
                              $nitr[$resid]=0;
                              $carb[$resid]=0;
                              $cara[$resid]=0;
                              $oxyg[$resid]=0;
                      }
              }
      }
     
}
foreach (@ARRAY) {
      chomp;
      @word  = (split(" "));
      for ($i=0; $i<=19; $i++){
              if (substr($_,17,3) eq $residue[$i]) {
                      if (substr($_,0,4) eq "ATOM") {
	                        $resid = substr($_,22,4);
                              @word  = (split(" "));
                              $nitr[$resid] = 1 if ($word[2] eq "N");
                              $carb[$resid] = 1 if ($word[2] eq "C");
                              $cara[$resid] = 1 if ($word[2] eq "CA");
                              $oxyg[$resid] = 1 if ($word[2] eq "O");
                              if ($nitr[$resid] == 1 and $carb[$resid] == 1
                                      and $carb[$resid] == 1 and $carb[$resid] == 1) {
                                      $resok[$resid] = 1;
                              }
                      }
              }
      }
}

foreach (@ARRAY) {
      chomp;
      @word  = (split(" "));
      for ($i=0; $i<=19; $i++){
              if (substr($_,17,3) eq $residue[$i]) {
                      if (substr($_,0,4) eq "ATOM") {
	                        $resid = substr($_,22,4);
                              if ($resok[$resid] == 0) {
                                       print "Residue $word[3] $resid is missing backbone atoms\n";
                              }
                      }
              }
      }
}
