#! /usr/bin/env python
#
#     Copyright (C) 2005 Ronan Keegan
#
#     This code is distributed under the terms and conditions of the
#     CCP4 Program Suite Licence Agreement as a CCP4 Application.
#     A copy of the CCP4 licence can be obtained by writing to the
#     CCP4 Secretary, Daresbury Laboratory, Warrington WA4 4AD, UK.
#
# Short scna the output PDB file from a MR job
# Gathers info on:
#   1. Number of molecules found
#
# Ronan Keegan 18/08/06
#

import os, sys 


class Get_PDB_Details:
 
   def __init__(self):
      self.molrep_mol_count = 1
      self.phaser_mol_count = 0
      self.mol_count = 1
      self.PDB_filename = ""
      self.LOG_filename = ""

   def get_details(self, filename):
      """ Parse the PDB file to extract any relevant details. """
       
      self.PDB_filename = filename

      if os.path.isfile(self.PDB_filename) == False:
         sys.stdout.write("PDB file details log: PDB file %s not found\n" % self.PDB_filename)
         sys.stdout.write("\n")
         sys.exit()

      f=open(self.PDB_filename,"r")

      line=f.readline()
      while line:
         if "#MOLECULE" in line:
            self.molrep_mol_count=self.molrep_mol_count + 1
         if "REMARK" in line and "ENSEMBLE" in line:
            self.phaser_mol_count=self.phaser_mol_count + 1
         line=f.readline()
   
      f.close()

      if self.molrep_mol_count > 1:
         self.mol_count = self.molrep_mol_count
      if self.phaser_mol_count > 0:
         self.mol_count = self.phaser_mol_count
   
   def write_details(self, filename):
      """ Write out the PDB details. """
     
      self.LOG_filename = filename

      o=open(self.LOG_filename,"w")

      o.write("Number of molecules found: %d" % self.mol_count)

      o.close()
      

if __name__ == "__main__":

   if len(sys.argv) != 2:
      print "Usage: mrbump_get_pdb_details <PDB file name>"
      sys.exit(1)

   gpd=Get_PDB_Details()
   gpd.get_details(sys.argv[1])

   print("Number of molecules found: %d" % gpd.mol_count)

 #  gpd.write_details(sys.argv[2])
      



