/*
FILE:     connect_util.C
*/
/*
VERSION:  1.600
*/
/*
DATE:     2/3/2005
*/
/*
  Comments and Questions to: sw-help@rcsb.rutgers.edu
*/
/*
COPYRIGHT 1999-2005 Rutgers - The State University of New Jersey

This software is provided WITHOUT WARRANTY OF MERCHANTABILITY OR
FITNESS FOR A PARTICULAR PURPOSE OR ANY OTHER WARRANTY, EXPRESS OR
IMPLIED.  RUTGERS MAKE NO REPRESENTATION OR WARRANTY THAT THE
SOFTWARE WILL NOT INFRINGE ANY PATENT, COPYRIGHT OR OTHER
PROPRIETARY RIGHT.

The user of this software shall indemnify, hold harmless and defend
Rutgers, its governors, trustees, officers, employees, students,
agents and the authors against any and all claims, suits,
losses, liabilities, damages, costs, fees, and expenses including
reasonable attorneys' fees resulting from or arising out of the
use of this software.  This indemnification shall include, but is
not limited to, any and all claims alleging products liability.
*/
/*
               PDB SOFTWARE LICENSE AGREEMENT

BY CLICKING THE ACCEPTANCE BUTTON OR INSTALLING OR USING 
THIS "SOFTWARE, THE INDIVIDUAL OR ENTITY LICENSING THE  
SOFTWARE ("LICENSEE") IS CONSENTING TO BE BOUND BY AND IS 
BECOMING A PARTY TO THIS AGREEMENT.  IF LICENSEE DOES NOT 
AGREE TO ALL OF THE TERMS OF THIS AGREEMENT
THE LICENSEE MUST NOT INSTALL OR USE THE SOFTWARE.

1. LICENSE AGREEMENT

This is a license between you ("Licensee") and the Protein Data Bank (PDB) 
at Rutgers, The State University of New Jersey (hereafter referred to 
as "RUTGERS").   The software is owned by RUTGERS and protected by 
copyright laws, and some elements are protected by laws governing 
trademarks, trade dress and trade secrets, and may be protected by 
patent laws. 

2. LICENSE GRANT

RUTGERS grants you, and you hereby accept, non-exclusive, royalty-free 
perpetual license to install, use, modify, prepare derivative works, 
incorporate into other computer software, and distribute in binary 
and source code format, or any derivative work thereof, together with 
any associated media, printed materials, and on-line or electronic 
documentation (if any) provided by RUTGERS (collectively, the "SOFTWARE"), 
subject to the following terms and conditions: (i) any distribution 
of the SOFTWARE shall bind the receiver to the terms and conditions 
of this Agreement; (ii) any distribution of the SOFTWARE in modified 
form shall clearly state that the SOFTWARE has been modified from 
the version originally obtained from RUTGERS.  

2. COPYRIGHT; RETENTION OF RIGHTS.  

The above license grant is conditioned on the following: (i) you must 
reproduce all copyright notices and other proprietary notices on any 
copies of the SOFTWARE and you must not remove such notices; (ii) in 
the event you compile the SOFTWARE, you will include the copyright 
notice with the binary in such a manner as to allow it to be easily 
viewable; (iii) if you incorporate the SOFTWARE into other code, you 
must provide notice that the code contains the SOFTWARE and include 
a copy of the copyright notices and other proprietary notices.  All 
copies of the SOFTWARE shall be subject to the terms of this Agreement.  

3. NO MAINTENANCE OR SUPPORT; TREATMENT OF ENHANCEMENTS 

RUTGERS is under no obligation whatsoever to: (i) provide maintenance 
or support for the SOFTWARE; or (ii) to notify you of bug fixes, patches, 
or upgrades to the features, functionality or performance of the 
SOFTWARE ("Enhancements") (if any), whether developed by RUTGERS 
or third parties.  If, in its sole discretion, RUTGERS makes an 
Enhancement available to you and RUTGERS does not separately enter 
into a written license agreement with you relating to such bug fix, 
patch or upgrade, then it shall be deemed incorporated into the SOFTWARE 
and subject to this Agreement. You are under no obligation whatsoever 
to provide any Enhancements to RUTGERS or the public that you may 
develop over time; however, if you choose to provide your Enhancements 
to RUTGERS, or if you choose to otherwise publish or distribute your 
Enhancements, in source code form without contemporaneously requiring 
end users or RUTGERS to enter into a separate written license agreement 
for such Enhancements, then you hereby grant RUTGERS a non-exclusive,
royalty-free perpetual license to install, use, modify, prepare
derivative works, incorporate into the SOFTWARE or other computer
software, distribute, and sublicense your Enhancements or derivative
works thereof, in binary and source code form.

4. FEES.  There is no license fee for the SOFTWARE.  If Licensee
wishes to receive the SOFTWARE on media, there may be a small charge
for the media and for shipping and handling.  Licensee is
responsible for any and all taxes.

5. TERMINATION.  Without prejudice to any other rights, Licensor
may terminate this Agreement if Licensee breaches any of its terms
and conditions.  Upon termination, Licensee shall destroy all
copies of the SOFTWARE.

6. PROPRIETARY RIGHTS.  Title, ownership rights, and intellectual
property rights in the Product shall remain with RUTGERS.  Licensee 
acknowledges such ownership and intellectual property rights and will 
not take any action to jeopardize, limit or interfere in any manner 
with RUTGERS' ownership of or rights with respect to the SOFTWARE.  
The SOFTWARE is protected by copyright and other intellectual 
property laws and by international treaties.  Title and related 
rights in the content accessed through the SOFTWARE is the property 
of the applicable content owner and is protected by applicable law.  
The license granted under this Agreement gives Licensee no rights to such
content.

7. DISCLAIMER OF WARRANTY.  THE SOFTWARE IS PROVIDED FREE OF 
CHARGE, AND, THEREFORE, ON AN "AS IS" BASIS, WITHOUT WARRANTY OF 
ANY KIND, INCLUDING WITHOUT LIMITATION THE WARRANTIES THAT IT 
IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE 
OR NON-INFRINGING.  THE ENTIRE RISK AS TO THE QUALITY AND 
PERFORMANCE OF THE SOFTWARE IS BORNE BY LICENSEE.  SHOULD THE 
SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, THE LICENSEE AND NOT 
LICENSOR ASSUMES THE ENTIRE COST OF ANY SERVICE AND REPAIR.  
THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF 
THIS AGREEMENT.  NO USE OF THE PRODUCT IS AUTHORIZED HEREUNDER 
EXCEPT UNDER THIS DISCLAIMER.

8. LIMITATION OF LIABILITY.  TO THE MAXIMUM EXTENT PERMITTED BY
APPLICABLE LAW,  IN NO EVENT WILL LICENSOR BE LIABLE FOR ANY 
INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 
OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, INCLUDING, 
WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK 
STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL 
OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF ADVISED OF THE
POSSIBILITY THEREOF. 
*/
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

#include "connect_check.h"
#include "connect_iolib.h"
#include "connect_util.h"
#include "connect2graph.h"
#include "erf_util.h"
#include "ndb_misclib.h"

static void waiting_for_continue();
static char *Get_words(char *string, char *buffer, const char begin, const char end);
static void Write_PDB_Conect_File(FILE *fp, ConnectFormat *drug);
static void print_atom_atomName_field(char *temp_line, const char *atomName, const int align);
static char *get_max_length_word(char *string, char *words, const int max_length);

void Add_Classification(Connect_Adm *Dictionary, const char *filename)
{
       FILE *fp = fopen(filename, "r");
       if (fp == NULL) {
            printf("Can't open file %s\n", filename);
            return;
       }

       char line[1000], id[5], class_1[200], class_2[200], date[20], *p = NULL;
       ConnectFormat *drug = NULL;
       while (!feof(fp)) {
            fgets(line, 999, fp);
            if (feof(fp)) break;
            p = Get_words(line, id, '\'', '\'');
            p = Get_words(p, class_1, '\'', '\'');
            p = Get_words(p, class_2, '\'', '\'');
            ndb_clean_string(id);
            ndb_set_string_to_upper(id);
            ndb_clean_string(class_1);
            ndb_set_string_to_upper(class_1);
            ndb_clean_string(class_2);
            ndb_set_string_to_upper(class_2);
            drug = Dictionary->find_drug(id);
            if (drug == NULL) continue;
            get_date(date);
            drug->set_class_1(class_1);
            drug->set_class_2(class_2);
            drug->set_modified_date(date);
       }
       fclose (fp);
       Dictionary->WriteNdbConnect("conect_new.cif");
       Dictionary->WriteChemComp("component_new.cif", 0, "");
}

void Add_Component_to_Dictionary(Connect_Adm *Dictionary)
{
       int num = 0, n, i, ret, n_list, found;
       char filename[80], date[30], value[10], *diags = NULL, **blockName = NULL;
       BTreeObj<_SSIndex> Index;
       CifFileObj *fobjR = NULL;
       CifString string, string1;
       ConnectFormat **drug = NULL, *drug_tmp = NULL;
       DiGraph *graph = NULL, *graph1 = NULL;
       _MATCH_LIST *list = NULL;
       _SSIndex _ssidx;
       struct stat stat1;

       memset(filename, 0, 80);
       system("clear");
       printf("\nEnter Het Group file name -->  ");
       fflush(stdout);
       fflush(stdin);
       fscanf(stdin, "%s", filename);
       ndb_clean_string(filename);

       if (stat(filename, &stat1) < 0) {
            printf("Can not find file: %s\n", filename);
            waiting_for_continue();
            return;
       }

       fobjR = new CifFileObj("TEMP.CIF", WRITE_MODE);
       if (fobjR == NULL) {
            printf("Import Het Group(s) %s into component.cif failed\n", filename);
            waiting_for_continue();
            return;
       }

       fobjR->Read(filename, diags);
       if (diags && strlen(diags)) {
            printf("Read cif file %s failed\n%s\n", filename, diags);
            waiting_for_continue();
            if (fobjR) delete fobjR;
            return;
       }

       Index.Clear();
       drug_tmp = Dictionary->GetFirstConnect();
       while (drug_tmp) {
            string.Copy("");
            if (drug_tmp->formula() && strcmp(drug_tmp->formula(), ""))
                 string.Copy(drug_tmp->formula());
            ReorderFormula(string, string1, 0);
            _ssidx.set_ivalue(drug_tmp->drugname());
            _ssidx.set_svalue(string.Text());
            Index.Add(_ssidx);
            drug_tmp = Dictionary->GetNextConnect();
       }

       blockName = fobjR->GetBlockNames(num);
       drug = new ConnectFormat*[num];
       for (i = 0; i < num; i++) drug[i] = NULL;

       found = 0;
       get_date(date);
       for (n = 0; n < num; n++) {
            drug[n] = new ConnectFormat();
            if (Read_Chem_Comp(drug[n], fobjR, blockName[n], 1)) {
                 printf("Read Het Group %s failed\n", blockName[n]);
                 waiting_for_continue();
                 for (i = 0; i < num; i++) {
                      delete [] blockName[i];
                      if (drug[i]) delete drug[i];
                 }
                 delete [] blockName;
                 delete [] drug;
                 if (fobjR) delete fobjR;
                 return;
            }

            if (drug[n]->formal_charge() && strcmp(drug[n]->formal_charge(), "") &&
                strcmp(drug[n]->formal_charge(), "0")) {
                 strcpy(value, drug[n]->formal_charge());
                 reformatting_charge_to_suffix(value);
                 drug[n]->set_formal_charge(value);
            }
            drug[n]->set_modified_date(date);

            if (CheckFormula(drug[n], stdout, string) ||
               !CheckConnect(drug[n], stdout, string)) {
/*
                 waiting_for_continue();
                 for (i = 0; i < num; i++) {
                      delete [] blockName[i];
                      if (drug[i]) delete drug[i];
                 }
                 delete [] blockName;
                 delete [] drug;
                 if (fobjR) delete fobjR;
                 return;
*/
                 found |= 2;
            }

            if (!strcasecmp(drug[n]->drugname(), "UNL")) {
                 found |= 1;
                 printf("Het Group ID 'UNL' is reserved for 'unknown ligand'.\n");
                 printf("Please change to another ID.\n");
            }

            if (drug[n]->FindAlignPos()) {
                 found |= 1;
                 printf("%s: rcsb_align error\n", drug[n]->drugname()); 
            }

            drug_tmp = Dictionary->find_drug(drug[n]->drugname());
            if (drug_tmp) {
                 found |= 1;
                 printf("%s exists: New [%s (%s)] --- Old [%s (%s)]\n", drug[n]->drugname(),
                        drug[n]->chemical_name(), drug[n]->formula(),
                        drug_tmp->chemical_name(), drug_tmp->formula());
            }

            graph = Connect2Graph(drug[n]);
            if (graph) {
                 string.Copy(drug[n]->formula());
                 ReorderFormula(string, string1, 0);
                 _ssidx.set_svalue(string.Text());
                 ret = Index.Seek(_ssidx);
                 while (ret >= 0) {
                      _ssidx = Index.GetCurrData();
                      drug_tmp = Dictionary->find_drug(_ssidx.ivalue());
                      graph1 = Connect2Graph(drug_tmp);
                      if (graph1) {
                           list = graph1->find_match(*graph, n_list);
                           if (list && n_list == drug[n]->natoms() &&
                               n_list == drug_tmp->natoms()) {
                                printf("%s is an EXACT MATCH for %s\n",
                                    drug[n]->drugname(), drug_tmp->drugname());
                                found |= 1;
                           }
                           if (list) delete [] list;
                           delete graph1;
                      }
                      ret = Index.GoToNext();
                      if (ret >= 0 && Index.GetCurrData() != _ssidx) break;
                 }
                 delete graph;
            }
       }
       for (i = 0; i < num; i++) delete [] blockName[i];
       delete [] blockName;

       if (found & 2) {
            waiting_for_continue();
            for (i = 0; i < num; i++) {
                 if (drug[i]) delete drug[i];
            }
            delete [] drug;
            if (fobjR) delete fobjR;
            return;
       } else if (found) {
            strcpy(filename, "no");
            printf("\n\n Do you want to continue ? (yes/no) : ");
            fflush(stdout);
            fflush(stdin);
            fscanf(stdin, "%s", filename);
            if (filename[0] == 'n' || filename[0] == 'N') {
                 for (i = 0; i < num; i++) {
                      if (drug[i]) delete drug[i];
                 }
                 delete [] drug;
                 if (fobjR) delete fobjR;
                 return;
            }
       } else waiting_for_continue();

       for (i = 0; i < num; i++) {
            // drug[i]->FindAlignPos();
            drug[i]->ReorderAtoms();
            drug_tmp = Dictionary->find_drug(drug[i]->drugname());
            if (drug_tmp) {
                 if (drug_tmp->type() && strcmp(drug_tmp->type(), "NON-POLYMER") &&
                    (!drug[i]->type() || drug[i]->type() &&
                     !strcmp(drug[i]->type() , "NON-POLYMER")))
                      drug[i]->set_type(drug_tmp->type());

                 if (drug_tmp->AtomType() && strcmp(drug_tmp->AtomType(), "HETAIN") &&
                    (!drug[i]->AtomType() || drug[i]->AtomType() &&
                     !strcmp(drug[i]->AtomType() , "HETAIN")))
                      drug[i]->set_AtomType(drug_tmp->AtomType());

                 if (drug_tmp->typeModified() != 0 && drug[i]->typeModified() == 0)
                      drug[i]->set_typeModified(drug_tmp->typeModified());

                 if (drug_tmp->class_1() && strcmp(drug_tmp->class_1(), "") &&
                    (!drug[i]->class_1() || drug[i]->class_1() &&
                     !strcmp(drug[i]->class_1() , "")))
                      drug[i]->set_class_1(drug_tmp->class_1());

                 if (drug_tmp->class_2() && strcmp(drug_tmp->class_2(), "") &&
                    (!drug[i]->class_2() || drug[i]->class_2() &&
                     !strcmp(drug[i]->class_2() , "")))
                      drug[i]->set_class_2(drug_tmp->class_2());

                 if (drug_tmp->het_name() && strcmp(drug_tmp->het_name(), "") &&
                    (!drug[i]->het_name() || drug[i]->het_name() &&
                     !strcmp(drug[i]->het_name() , "")))
                      drug[i]->set_het_name(drug_tmp->het_name());

                 if (drug_tmp->status() && !strcmp(drug_tmp->status(), "REL") &&
                    (!drug[i]->status() || drug[i]->status() &&
                     strcmp(drug[i]->status() , "REL")))
                      drug[i]->set_status(drug_tmp->status());
            }
            Dictionary->add_drug(drug[i]);
       }
       delete [] drug;

       delete fobjR;

       Dictionary->WriteNdbConnect("conect_new.cif");
       Dictionary->WriteChemComp("component_new.cif", 0, "");
}

void Compare_Component_with_Dictionary(Connect_Adm *Dictionary)
{
       int i, n, num = 0, n_list, found;
       char filename[80], *diags = NULL, **blockName = NULL;
       CifFileObj *fobjR = NULL;
       CifString string, string1, string2;
       ConnectFormat **drug = NULL, *drug_tmp = NULL;
       DiGraph *graph = NULL, *graph1 = NULL;
       FILE *fp = NULL;
       _MATCH_LIST *list = NULL;

       system("clear");
       printf("\nEnter Het Group file name -->  ");
       fflush(stdout);
       fflush(stdin);
       fscanf(stdin, "%s", filename);
       ndb_clean_string(filename);

       fobjR = new CifFileObj("TEMP.CIF", WRITE_MODE);
       if (fobjR == NULL) {
            printf("Import Het Group(s) %s into component.cif failed\n", filename);
            waiting_for_continue();
            return;
       }

       fobjR->Read(filename, diags);
       if (diags && strlen(diags)) {
            printf("Read cif file %s failed\n%s\n", filename, diags);
            waiting_for_continue();
            if (fobjR) delete fobjR;
            return;
       }

       blockName = fobjR->GetBlockNames(num);
       drug = new ConnectFormat*[num];
       for (i = 0; i < num; i++) drug[i] = NULL;

       fp = fopen("compare_check_list", "w");
       for (n = 0; n < num; n++) {
            drug[n] = new ConnectFormat();
            if (Read_Chem_Comp(drug[n], fobjR, blockName[n], 0)) {
                 printf("Read Het Group %s failed\n", blockName[n]);
                 waiting_for_continue();
                 for (i = 0; i < num; i++) {
                      delete [] blockName[i];
                      if (drug[i]) delete drug[i];
                 }
                 delete [] blockName;
                 delete [] drug;
                 if (fobjR) delete fobjR;
                 return;
            }
            if (CheckFormula(drug[n], stdout, string) ||
               !CheckConnect(drug[n], stdout, string)) {
                 waiting_for_continue();
                 for (i = 0; i < num; i++) {
                      delete [] blockName[i];
                      if (drug[i]) delete drug[i];
                 }
                 delete [] blockName;
                 delete [] drug;
                 if (fobjR) delete fobjR;
                 return;
            }
            drug_tmp = Dictionary->find_drug(drug[n]->drugname());
            if (!drug_tmp) {
                 printf("Het Group %s is not in component.cif file\n",
                                 drug[n]->drugname());
                 fprintf(fp, "Het Group %s is not in component.cif file\n",
                                 drug[n]->drugname());
                 continue;
            }

            string.Copy(drug_tmp->formula());
            string1.Copy(drug[n]->formula());
            ReorderFormula(string, string2, 0);
            ReorderFormula(string1, string2, 0);
            if (string != string1) {
                 printf("Het Group %s's formula difference: New(%s) --- Exist(%s)\n",
                    drug[n]->drugname(), drug[n]->formula(), drug_tmp->formula());
                 fprintf(fp, "Het Group %s's formula difference: New(%s) --- Exist(%s)\n",
                    drug[n]->drugname(), drug[n]->formula(), drug_tmp->formula());
                 continue;
            }

            found = 0;
            graph = Connect2Graph(drug[n]);
            graph1 = Connect2Graph(drug_tmp);
            if (graph && graph1) {
                 list = graph1->find_match(*graph, n_list);
                 if (!list || n_list != drug[n]->natoms() || n_list != drug_tmp->natoms()) {
                      printf("Het Group %s is not match exist one\n", drug[n]->drugname());
                      fprintf(fp, "Het Group %s is not match exist one\n", drug[n]->drugname());
                      found = 1;
                 }
                 if (list) delete [] list;
            }
            if (graph) delete graph;
            if (graph1) delete graph1;
            if (found) continue;

            if (drug[n]->chemical_name() && drug_tmp->chemical_name() &&
                strcasecmp(drug[n]->chemical_name(), drug_tmp->chemical_name())) {
                 printf("Het Group %s's chemical_name difference: New(%s) --- Exist(%s)\n",
                    drug[n]->drugname(), drug[n]->chemical_name(), drug_tmp->chemical_name());
                 fprintf(fp, "Het Group %s's chemical_name difference: New(%s) --- Exist(%s)\n",
                    drug[n]->drugname(), drug[n]->chemical_name(), drug_tmp->chemical_name());
                 continue;
            }

            if (drug[n]->formal_charge() && drug_tmp->formal_charge() &&
                strcasecmp(drug[n]->formal_charge(), drug_tmp->formal_charge())) {
                 printf("Het Group %s's formal_charge difference: New(%s) --- Exist(%s)\n",
                    drug[n]->drugname(), drug[n]->formal_charge(), drug_tmp->formal_charge());
                 fprintf(fp, "Het Group %s's formal_charge difference: New(%s) --- Exist(%s)\n",
                    drug[n]->drugname(), drug[n]->formal_charge(), drug_tmp->formal_charge());
                 continue;
            }

            if (drug[n]->synonym() && drug_tmp->synonym() &&
                strcasecmp(drug[n]->synonym(), drug_tmp->synonym())) {
                 printf("Het Group %s's synonym difference: New(%s) --- Exist(%s)\n",
                    drug[n]->drugname(), drug[n]->synonym(), drug_tmp->synonym());
                 fprintf(fp, "Het Group %s's synonym difference: New(%s) --- Exist(%s)\n",
                    drug[n]->drugname(), drug[n]->synonym(), drug_tmp->synonym());
                 continue;
            }

            if (drug[n]->parent_residue() && drug_tmp->parent_residue() &&
                strcasecmp(drug[n]->parent_residue(), drug_tmp->parent_residue())) {
                 printf("Het Group %s's parent_residue difference: New(%s) --- Exist(%s)\n",
                    drug[n]->drugname(), drug[n]->parent_residue(), drug_tmp->parent_residue());
                 fprintf(fp, "Het Group %s's parent_residue difference: New(%s) --- Exist(%s)\n",
                    drug[n]->drugname(), drug[n]->parent_residue(), drug_tmp->parent_residue());
                 continue;
            }

            printf("Het Group %s is same\n", drug[n]->drugname());
            fprintf(fp, "Het Group %s is same\n", drug[n]->drugname());
       }
       fclose (fp);

       for (i = 0; i < num; i++) {
            delete [] blockName[i];
            if (drug[i]) delete drug[i];
       }
       delete [] blockName;
       delete [] drug;
       delete fobjR;
}

void Find_Component_Based_On_ID(Connect_Adm *Dictionary)
{
       char string[84];
       int  i, j;
       ConnectFormat *drug = NULL;

       system("clear");
       printf("\nEnter Het Group ID --> ");
       fflush(stdout);
       fflush(stdin);
       fscanf(stdin, "%s", string);
       ndb_clean_string(string);
       ndb_set_string_to_upper(string);
       if (strcmp(string, "")) {
            drug = Dictionary->find_drug(string);
            if (drug) {
                 printf("Het Group ID: %s\n", drug->drugname());
                 printf("Het Group Chemical Name: %s\n", drug->chemical_name());
                 if (drug->synonym() && strcmp(drug->synonym(), ""))
                      printf("Het Group Synonym: %s\n", drug->synonym());
                 if (drug->formula() && strcmp(drug->formula(), ""))
                      printf("Het Group Formula: %s\n", drug->formula());
                 if (drug->parent_residue() && strcmp(drug->parent_residue(), ""))
                      printf("Parent Residue: %s\n", drug->parent_residue());
                 if (drug->formal_charge() && strcmp(drug->formal_charge(), ""))
                      printf("Formal Charge: %s\n", drug->formal_charge());
                 if (drug->class_1() && strcmp(drug->class_1(), ""))
                      printf("Classification1: %s\n", drug->class_1());
                 if (drug->class_2() && strcmp(drug->class_2(), ""))
                      printf("Classification2: %s\n", drug->class_2());
                 printf("\n");

                 printf("%6s %d\n\n", drug->AtomType(), drug->typeModified());

                 printf("Atom Name     Connected Atom\n");
                 for (i = 0; i < drug->natoms(); i++) {
                      printf("  %-4s        ", drug->atoms(i)->atomname());
                      for (j = 0; j < drug->atoms(i)->nconect(); j++) {
                           printf(" %-4s", drug->atoms(i)->connectto(j));
                      }
                      printf("\n");
                 }
            } else printf("Het Group \"%s\" is not in component.cif file\n", string);
       }
       waiting_for_continue();
}

void Get_Component_From_Dictionary(Connect_Adm *Dictionary)
{
       char drug_name[84];

       system("clear");
       printf("\nPlease enter the name of Het group --> ");
       fflush(stdout);
       fflush(stdin);
       fscanf(stdin, "%s", drug_name);

       if (Get_Component_From_Dictionary(Dictionary, drug_name))
            waiting_for_continue();
}

int Get_Component_From_Dictionary(Connect_Adm *Dictionary, char *het_name)
{
       char filename[84];

       ndb_clean_string(het_name);
       ndb_set_string_to_upper(het_name);

       ConnectFormat *drug = Dictionary->find_drug(het_name);
       if (!drug) {
            printf("Can not find %s in component.cif\n", het_name);
            return 1;
       }

       CifFileObj *fobjR = new CifFileObj("./TEMP.CIF", WRITE_MODE);
       Write_Chem_Comp(drug, fobjR, 0);

       sprintf(filename, "%s.cif", het_name);
       fobjR->Write(filename);
       // fobjR->CloseFile();
       delete fobjR;
       return 0;
}

void Switch_Hold_To_Release(Connect_Adm *Dictionary, const char *filename)
{
       FILE *fp = fopen(filename, "r");
       if (fp == NULL) {
            printf("Can't open file %s\n", filename);
            return;
       }
       char line[100], date[20];
       ConnectFormat *drug = NULL;

       get_date(date);
       while (!feof(fp)) {
            fgets(line, 99, fp);
            if (feof(fp)) break;
            ndb_clean_string(line);
            drug = Dictionary->find_drug(line);
            if (drug) {
                 if (strcmp(drug->status(), "REL"))
                      drug->set_modified_date(date);
                 drug->set_status("REL");
            }
       }
       fclose (fp);
       Dictionary->WriteNdbConnect("conect_new.cif");
       Dictionary->WriteChemComp("component_new.cif", 0, "");
}

void Write_PDB_Het_Dictionary(Connect_Adm *Dictionary, const char *filename)
{
       ConnectFormat *drug = NULL;
       FILE *fp = NULL;

       fp = fopen(filename, "w");
       if (fp == NULL) {
            printf("Can't open file %s\n", filename);
            return;
       }
       drug = Dictionary->GetFirstConnect();
       while (drug) {
            if (strlen(drug->drugname()) < 4 && !strcmp(drug->status(), "REL")) {
                 Write_PDB_Conect_File(fp, drug);
            }
            drug = Dictionary->GetNextConnect();
       }
       fclose (fp);
}

void Write_All_Components_for_Client_Server(Connect_Adm *Dictionary)
{
       CifFileObj *fobjR = new CifFileObj("./TEMP.CIF", WRITE_MODE);
       ConnectFormat *drug = Dictionary->GetFirstConnect();
       while (drug) {
            if (drug->natoms() > 1 && strcmp(drug->drugname(), "BAN") &&
                strcmp(drug->drugname(), "GLX") &&
                strcmp(drug->drugname(), "ASX")) {
                 Write_Chem_Comp(drug, fobjR, 0);
            }
            drug = Dictionary->GetNextConnect();
       }
       fobjR->Write("Ligand-dict-0.cif");
       delete fobjR;
}

void Write_All_Components_for_Ligand_Server(Connect_Adm *Dictionary)
{
       char drug_name[84];
       CifFileObj *fobjR = NULL;
       ConnectFormat *drug = Dictionary->GetFirstConnect();
       while (drug) {
            if (drug->natoms() > 1 && strcmp(drug->drugname(), "BAN") &&
                strcmp(drug->drugname(), "GLX") &&
                strcmp(drug->drugname(), "ASX")) {
                 fobjR = new CifFileObj("./TEMP.CIF", WRITE_MODE);
                 Write_Chem_Comp(drug, fobjR, 0);
                 sprintf(drug_name, "%s.cif", drug->drugname());
                 fobjR->Write(drug_name);
                 delete fobjR;
            }
            drug = Dictionary->GetNextConnect();
       }
}

void Write_All_Components_Separately(Connect_Adm *Dictionary, const int flag)
{
       char drug_name[84];
       CifFileObj *fobjR = NULL;
       ConnectFormat *drug = Dictionary->GetFirstConnect();
       while (drug) {
            if (strlen(drug->drugname()) < 4 && (!flag || flag &&
               !strcmp(drug->status(), "REL"))) {
                 fobjR = new CifFileObj("./TEMP.CIF", WRITE_MODE);
                 Write_Chem_Comp(drug, fobjR, flag);
                 sprintf(drug_name, "%s.cif", drug->drugname());
                 fobjR->Write(drug_name);
                 delete fobjR;
            }
            drug = Dictionary->GetNextConnect();
       }
}

void Write_Delimited_Name_and_Formulas(Connect_Adm *Dictionary)
{
       ConnectFormat *drug = Dictionary->GetFirstConnect();
       while (drug) {
            if (strlen(drug->drugname()) < 4) {
                 printf("%s\t", drug->drugname());
                 if (drug->chemical_name() && strcmp(drug->chemical_name(), ""))
                      printf("%s", drug->chemical_name());
                 printf("\t");
                 if (drug->formula() && strcmp(drug->formula(), ""))
                      printf("%s", drug->formula());
                 printf("\t");
                 if (drug->synonym() && strcmp(drug->synonym(), ""))
                      printf("%s", drug->synonym());
                 printf("\n");
            }
            drug = Dictionary->GetNextConnect();
       }
}


static void waiting_for_continue()
{
       char buffer[10];
       char c = ' ';
       printf("\n\n [C] Continue\n");
       fflush(stdout);
       fflush(stdin);
       while (c != 'c' && c != 'C') {
            fscanf(stdin, "%s", buffer);
            ndb_clean_string(buffer);
            c = buffer[0];
       }
}

static char *Get_words(char *string, char *buffer, const char begin, const char end)
{
       *buffer = '\0';
       if (!string) return NULL;
       while (*string == ' ' && *string != '\0') string++;
       if (*string == '\0') return NULL;
       int start = 0;
       while (*string != '\0') {
            if (start) {
                 if (*string == end) {
                      string++;
                      break;
                 }
                 *buffer = *string;
                 buffer++;
            }
            if (*string == begin) start = 1;
            string++;
       }
       *buffer = '\0';
       if(*string == '\0') return NULL;
       return string;
}

static void Write_PDB_Conect_File(FILE *fp, ConnectFormat *drug)
{
       int i = 0, j = 0, k = 0, count = 2;
       char stringbuffer[10], buffer[80], *p = NULL, namebuffer[8000];
       
       fprintf(fp, "RESIDUE   %-3s    %3d\n", drug->drugname(), drug->natoms());
       for (i = 0; i < drug->natoms(); i++) {
            memset(stringbuffer, 0, 10);
            print_atom_atomName_field(stringbuffer, drug->atoms(i)->atomname(),
                       drug->atoms(i)->align_pos()); 
            fprintf(fp, "CONECT     %-4s   %2d", stringbuffer, drug->atoms(i)->nconect());
            for (j = 0; j < drug->atoms(i)->nconect(); j++) {
                 memset(stringbuffer, 0, 10);
                 for (k = 0; k < drug->natoms(); k++) {
                      if (!strcmp(drug->atoms(k)->atomname(), drug->atoms(i)->connectto(j)))
                           break;
                 }
                 if (k < drug->natoms()) {
                      print_atom_atomName_field(stringbuffer, drug->atoms(k)->atomname(),
                                 drug->atoms(k)->align_pos());
                      fprintf(fp, "%-4s ", stringbuffer);
                 }
            }
            fprintf(fp, "\n");
       }
       fprintf(fp, "END\n");

       fprintf(fp, "HET    %-3s            %3d\n", drug->drugname(), drug->natoms());
       if (drug->synonym() && strcmp(drug->synonym(), "")) {
            strcpy(namebuffer, drug->synonym());
            p = get_max_length_word(namebuffer, buffer, 55);
            fprintf(fp, "HETSYN     %-3s %s\n", drug->drugname(), buffer);
            count = 2;
            while (p) {
                 p = get_max_length_word(p, buffer, 55);
                 fprintf(fp, "HETSYN  %2d %-3s %s\n", count++, drug->drugname(), buffer);
            }
       }
       if (drug->chemical_name() && strcmp(drug->chemical_name(), "")) {
            strcpy(namebuffer, drug->chemical_name());
            p = get_max_length_word(namebuffer, buffer, 55);
            fprintf(fp, "HETNAM     %-3s %s\n", drug->drugname(), buffer);
            count = 2;
            while (p) {
                 p = get_max_length_word(p, buffer, 55);
                 fprintf(fp, "HETNAM  %2d %-3s %s\n", count++, drug->drugname(), buffer);
            }
       }
       if (drug->formal_charge() && strcmp(drug->formal_charge(), "") &&
           strcmp(drug->formal_charge(), "0"))
            fprintf(fp, "FORMUL      %-3s    %s %s\n", drug->drugname(), drug->formula(), drug->formal_charge());
       else fprintf(fp, "FORMUL      %-3s    %s\n", drug->drugname(), drug->formula());
       fprintf(fp, "\n");
}

static void print_atom_atomName_field(char *temp_line, const char *atomName, const int align)
{
       int l;

       l = strlen(atomName);
       if (l == 4 || l == 0) {
            sprintf(temp_line, "%-4s", atomName);
       } else if (align == 0) {
            if (l == 2) sprintf(temp_line, "%2s  ", atomName);
            else if (l == 3) sprintf(temp_line, "%3s ", atomName);
       } else {
            if (l == 1) sprintf(temp_line, " %s  ", atomName);
            else if (l == 2) sprintf(temp_line, " %2s ", atomName);
            else if (l == 3) sprintf(temp_line, " %3s", atomName);
       }
}

static char *get_max_length_word(char *string, char *words, const int max_length)
{
       int i, str_len, length;
       char *p;

       str_len = strlen(string);
       if (str_len <= max_length) {
            strcpy(words, string);
            return NULL;
       }

       words[0] = '\0';
       length = 0;
       for (i = 0; i < str_len; i++) {
            if (string[i] == ' ') {
                if (i >= max_length) break;
                length = i;
            // } else if (string[i] == ',' || string[i] == '-') {
            } else if (!isalnum(string[i]) && string[i] != '.' &&
                  string[i] != '(' && string[i] != '[') {
                if ((i + 1) >= max_length) break;
                length = i + 1;
            } else if (isalpha(string[i]) && (string[i+1] == '-' /* ||
                  string[i+1] == '(' || string[i+1] == '[' */ )) {
                if ((i + 1) >= max_length) break;
                length = i + 1;
            }
       }

       for (i = 0; i < length; i++) words[i] = string[i];
       words[length] = '\0';

       p = string + length;
       ndb_clean_string(p);
       if (p[0] == '\0') return NULL;
       else              return p;
}
