/*
FILE:     _validation.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 "_validation.h"
#include "erf_util.h"
#include "util.h"

static int find_symmetry_related_chain(const int n_stbiol, _STBIOL **stbiol,
               const int i, const int index);
static int find_symmetry_related_chains(const int n_stbiol, _STBIOL **stbiol,
               const int index, char *ndb_chnid);
static int find_asymmetric_chains(const int n_stbiol, _STBIOL **stbiol,
               const int start);

_VALIDATION::_VALIDATION(const int mxtokens, const int mxjrnltokens): _FileObj(mxtokens, mxjrnltokens)
{
       _alloc_link = 0; _n_link = 0; _link = NULL;
       _alloc_mismat = 0; _n_mismat = 0; _mismat = NULL;
       _alloc_bspair = 0; _n_bspair = 0; _bspair = NULL;
       _alloc_a_contact = 0; _n_a_contact = 0; _a_contact = NULL;
       _alloc_s_contact = 0; _n_s_contact = 0; _s_contact = NULL;
       _alloc_waters = 0; _n_waters = 0; _waters = NULL;
       _alloc_moving_waters = 0; _n_moving_waters = 0; _moving_waters = NULL;
       _alloc_speical = 0; _n_speical = 0; _speical = NULL;
       _alloc_bond = 0; _n_bond = 0; _bond = NULL;
       _alloc_angle = 0; _n_angle = 0; _angle = NULL;
       _alloc_torsion = 0; _n_torsion = 0; _torsion = NULL;
       _alloc_t_pairs = 0; _n_t_pairs = 0; _t_pairs = NULL;
       _alloc_z_a_1 = 0; _n_z_a_1 = 0; _z_a_1 = NULL;
       _alloc_z_b_1 = 0; _n_z_b_1 = 0; _z_b_1 = NULL;
       _alloc_z_e = 0; _n_z_e = 0; _z_e = NULL;
       _alloc_a_g = 0; _n_a_g = 0; _a_g = NULL;
       _alloc_z_x = 0; _n_z_x = 0; _z_x = NULL;
       _alloc_d_x = 0; _n_d_x = 0; _d_x = NULL;
       _calculated_bond_angle_torsion = 0;
       _alloc_bb_params = 0; _n_bb_params = 0; _bb_params = NULL;
       _alloc_ib_params = 0; _n_ib_params = 0; _ib_params = NULL;
       _alloc_ribbons = 0; _n_ribbons = 0; _ribbons = NULL;
       _alloc_link_bonds = 0; _n_link_bonds = 0; _link_bonds = NULL;
       _alloc_blocks = 0; _n_blocks = 0; _blocks = NULL;
       _bondResIndex.Clear();
       _bondNamIndex.Clear();
       _bondComIndex.Clear();
       _angleResIndex.Clear();
       _angleNamIndex.Clear();
       _angleComIndex.Clear();
       _torsionIndex.Clear();
       _classification = 0;
       _spell_check.Clear();
       _large_cell.Clear();
       _date_error.Clear();
}

_VALIDATION::~_VALIDATION()
{
       int i;
       if (_link) {
            for (i = 0; i < _n_link; i++) {
                 if (_link[i]) {
                      if (_link[i]->details) delete _link[i]->details;
                      delete _link[i];
                 }
            }
            delete [] _link;
       }
       if (_mismat) {
            for (i = 0; i < _n_mismat; i++)
                 if (_mismat[i]) delete _mismat[i];
            delete [] _mismat;
       }
       Clear_Bspair();
       Clear_Contact();
       if (_bond) {
            for (i = 0; i < _n_bond; i++)
                 if (_bond[i]) delete _bond[i];
            delete [] _bond;
       }
       if (_angle) {
            for (i = 0; i < _n_angle; i++)
                 if (_angle[i]) delete _angle[i];
            delete [] _angle;
       }
       if (_torsion) {
            for (i = 0; i < _n_torsion; i++)
                 if (_torsion[i]) delete _torsion[i];
            delete [] _torsion;
       }
       if (_t_pairs) {
            for (i = 0; i < _n_t_pairs; i++)
                 if (_t_pairs[i]) delete _t_pairs[i];
            delete [] _t_pairs;
       }
       if (_z_a_1) {
            for (i = 0; i < _n_z_a_1; i++)
                 if (_z_a_1[i]) delete _z_a_1[i];
            delete [] _z_a_1;
       }
       if (_z_b_1) {
            for (i = 0; i < _n_z_b_1; i++)
                 if (_z_b_1[i]) delete _z_b_1[i];
            delete [] _z_b_1;
       }
       if (_z_e) {
            for (i = 0; i < _n_z_e; i++)
                 if (_z_e[i]) delete _z_e[i];
            delete [] _z_e;
       }
       if (_a_g) {
            for (i = 0; i < _n_a_g; i++)
                 if (_a_g[i]) delete _a_g[i];
            delete [] _a_g;
       }
       if (_z_x) {
            for (i = 0; i < _n_z_x; i++)
                 if (_z_x[i]) delete _z_x[i];
            delete [] _z_x;
       }
       if (_d_x) {
            for (i = 0; i < _n_d_x; i++)
                 if (_d_x[i]) delete _d_x[i];
            delete [] _d_x;
       }
       if (_bb_params) {
            for (i = 0; i < _n_bb_params; i++)
                 if (_bb_params[i]) delete _bb_params[i];
            delete [] _bb_params;
       }
       if (_ib_params) {
            for (i = 0; i < _n_ib_params; i++)
                 if (_ib_params[i]) delete _ib_params[i];
            delete [] _ib_params;
       }
       Clear();
}

void _VALIDATION::Clear_Bspair()
{
       int i;
       if (_bspair) {
            for (i = 0; i < _n_bspair; i++)
                 if (_bspair[i]) delete _bspair[i];
            delete [] _bspair;
       }
       _bspair = NULL;
       _n_bspair = 0;
       _alloc_bspair = 0;
}

void _VALIDATION::Clear_Contact()
{
       int i;
       if (_a_contact) {
            for (i = 0; i < _n_a_contact; i++)
                 if (_a_contact[i]) delete _a_contact[i];
            delete [] _a_contact;
       }
       if (_s_contact) {
            for (i = 0; i < _n_s_contact; i++)
                 if (_s_contact[i]) delete _s_contact[i];
            delete [] _s_contact;
       }
       if (_waters) {
            for (i = 0; i < _n_waters; i++)
                 if (_waters[i]) delete _waters[i];
            delete [] _waters;
       }
       if (_moving_waters) {
            for (i = 0; i < _n_moving_waters; i++)
                 if (_moving_waters[i]) delete _moving_waters[i];
            delete [] _moving_waters;
       }
       if (_speical) {
            for (i = 0; i < _n_speical; i++)
                 if (_speical[i]) delete _speical[i];
            delete [] _speical;
       }
       _alloc_a_contact = 0; _n_a_contact = 0; _a_contact = NULL;
       _alloc_s_contact = 0; _n_s_contact = 0; _s_contact = NULL;
       _alloc_waters = 0; _n_waters = 0; _waters = NULL;
       _alloc_moving_waters = 0; _n_moving_waters = 0; _moving_waters = NULL;
       _alloc_speical = 0; _n_speical = 0; _speical = NULL;
}

void _VALIDATION::Clear()
{
       int i;
       if (_ribbons) {
            for (i = 0; i < _n_ribbons; i++) {
                 if (_ribbons[i]) {
                      if (_ribbons[i]->ribbon) delete [] _ribbons[i]->ribbon;
                      delete _ribbons[i];
                 }
            }
            delete [] _ribbons;
       }
       _alloc_ribbons = 0; _n_ribbons = 0; _ribbons = NULL;

       if (_link_bonds) {
            for (i = 0; i < _n_link_bonds; i++)
                 if (_link_bonds[i]) delete _link_bonds[i];
            delete [] _link_bonds;
       }
       _alloc_link_bonds = 0; _n_link_bonds = 0; _link_bonds = NULL;

       if (_blocks) {
            for (i = 0; i < _n_blocks; i++)
                 if (_blocks[i]) delete _blocks[i];
            delete [] _blocks;
       }
       _alloc_blocks = 0; _n_blocks = 0; _blocks = NULL;
}

void _VALIDATION::Get_Stbiol(const int exchange)
{
       int i, j, rowNo, colNo, id_idx, flag_idx;
       CifString string;
       ReVarCifArray<CifString> *ColumnNames = NULL;
       ISTable *Table = NULL;
       One_Card_Info_Format *pCard = _CardInfo[STBIOL_TOKEN-1].Head();
       while (pCard) pCard = _CardInfo[STBIOL_TOKEN-1].delete_a_card(pCard);

       Table = _CifObj->GetTablePtr(_StructureId, "struct_biol_gen");
       if (is_empty_table(Table)) return;

       if (Table->GetColumnIndex("ndb_new_pdb_asym_id") < 0)
            _exist_pdb_chain_id = 0;

       if (exchange) _exist_pdb_chain_id = 0;

       rowNo = Table->GetNumRows();
       colNo = Table->GetNumColumns();
       ColumnNames = Table->GetColumnNames();

       if (_stbiol) {
            for (i = 0; i < _n_stbiol; i++) if (_stbiol[i]) delete _stbiol[i];
            delete [] _stbiol;
       }
       _n_stbiol = rowNo;
       _stbiol = new _STBIOL*[_n_stbiol];

       for (i = 0; i < rowNo ; i++) {
            _stbiol[i] = new _STBIOL;
            _stbiol[i]->internal_order = i;
            _stbiol[i]->order = i;
            _stbiol[i]->Biol_ID = 1;
            _stbiol[i]->Asym_ID.Clear();
            _stbiol[i]->NDB_Strand_ID.Clear();
            _stbiol[i]->PDB_Strand_ID[0] = '\0';
            _stbiol[i]->PDB_Strand_ID_Flag[0] = '\0';
            strcpy(_stbiol[i]->Symmetry, "1_555");
            _stbiol[i]->bbrn = -99999;
            _stbiol[i]->bern = -99999;
            _stbiol[i]->abrn = -99999;
            _stbiol[i]->aern = -99999;
            for (j = 0; j < colNo; j++) {
                 Table->GetCell(string, j, i);
                 if (string == "" || string == "?" || string == ".") continue;
                 if (!strcmp((*ColumnNames)[j].Text(), "biol_id"))
                      _stbiol[i]->Biol_ID = atoi(string.Text());
                 else if (!strcmp((*ColumnNames)[j].Text(), "asym_id"))
                      _stbiol[i]->Asym_ID.Copy(string);
                 else if (!strcmp((*ColumnNames)[j].Text(), "ndb_new_asym_id"))
                      _stbiol[i]->NDB_Strand_ID.Copy(string);
                 else if (!strcmp((*ColumnNames)[j].Text(), "ndb_new_pdb_asym_id"))
                      strcpy(_stbiol[i]->PDB_Strand_ID, string.Text());
                 else if (!strcmp((*ColumnNames)[j].Text(), "symmetry"))
                      strcpy(_stbiol[i]->Symmetry, string.Text());
                 else if (!strcmp((*ColumnNames)[j].Text(), "ndb_before_begin_residue_no"))
                      _stbiol[i]->bbrn = atoi(string.Text());
                 else if (!strcmp((*ColumnNames)[j].Text(), "ndb_before_end_residue_no"))
                      _stbiol[i]->bern = atoi(string.Text());
                 else if (!strcmp((*ColumnNames)[j].Text(), "ndb_after_begin_residue_no"))
                      _stbiol[i]->abrn = atoi(string.Text());
                 else if (!strcmp((*ColumnNames)[j].Text(), "ndb_after_end_residue_no"))
                      _stbiol[i]->aern = atoi(string.Text());
                 else if (!strcmp((*ColumnNames)[j].Text(), "rcsb_pdb_order"))
                      _stbiol[i]->order = atoi(string.Text());
            }
       }
       if (ColumnNames) delete ColumnNames;

       Table = _CifObj->GetTablePtr(_StructureId, "struct_asym");
       if (is_empty_table(Table)) return;

       rowNo = Table->GetNumRows();
       id_idx = Table->GetColumnIndex("id");
       flag_idx = Table->GetColumnIndex("rcsb_blank_PDB_chainid_flag");
       if (flag_idx < 0 || id_idx < 0) return;

       for (i = 0; i < _n_stbiol; i++) {
            if (strcmp(_stbiol[i]->Symmetry, "1_555")) continue;
            for (j = 0; j < rowNo; j++) {
                 Table->GetCell(string, id_idx, j);
                 if (string == _stbiol[i]->Asym_ID) {
                      Table->GetCell(string, flag_idx, j);
                      if (string == "Y" || string == "N" ||
                          string == "y" || string == "n") {
                           strcpy(_stbiol[i]->PDB_Strand_ID_Flag, string.Text());
                      }
                      break;
                 }
            }
       }
}

void _VALIDATION::Input_Stbiol()
{
       int found_order = 1, i = 0, k = 0, tokenid[9], count = 0;
       int exist_symmetry_related_chain = 0;
       _CHAIN *chain = NULL;
       One_Card_Info_Format *pCard = _CardInfo[STBIOL_TOKEN-1].Head();
       while (pCard) {
            count++;
            pCard = pCard->Next();
       }
       if (!count) return;

       if (_stbiol) {
            for (i = 0; i < _n_stbiol; i++) if (_stbiol[i]) delete _stbiol[i];
            delete [] _stbiol;
       }
       _n_stbiol = count;
       _stbiol = new _STBIOL*[_n_stbiol];
       for (i = 0; i < _n_stbiol; i++) _stbiol[i] = NULL;
       count = 0;
       pCard = _CardInfo[STBIOL_TOKEN-1].Head();
       while (pCard) {
            _stbiol[count] = new _STBIOL;
            _stbiol[count]->internal_order = atoi(pCard->Field(1));
            if (strcmp(pCard->Field(15), ""))
                 _stbiol[count]->order = atoi(pCard->Field(15));
            else found_order = 0;
            _stbiol[count]->Biol_ID = atoi(pCard->Field(2));
            _stbiol[count]->Asym_ID.Copy(pCard->Field(3));
            _stbiol[count]->NDB_Strand_ID.Copy(pCard->Field(12));
            strcpy(_stbiol[count]->PDB_Strand_ID, pCard->Field(13));
            strcpy(_stbiol[count]->PDB_Strand_ID_Flag, pCard->Field(16));
            strcpy(_stbiol[count]->Symmetry, pCard->Field(4));
            if (strcmp(_stbiol[count]->Symmetry, "1_555"))
                 exist_symmetry_related_chain = 1;
            if (strcmp(pCard->Field(5), ""))
                 _stbiol[count]->bbrn = atoi(pCard->Field(5));
            else _stbiol[count]->bbrn = -99999;
            if (strcmp(pCard->Field(6), ""))
                 _stbiol[count]->bern = atoi(pCard->Field(6));
            else _stbiol[count]->bern = -99999;
            if (strcmp(pCard->Field(7), ""))
                 _stbiol[count]->abrn = atoi(pCard->Field(7));
            else _stbiol[count]->abrn = -99999;
            if (strcmp(pCard->Field(8), ""))
                 _stbiol[count]->aern = atoi(pCard->Field(8));
            else _stbiol[count]->aern = -99999;
            count++;
            pCard = pCard->Next();
       }
       pCard = _CardInfo[STBIOL_TOKEN-1].Head();
       while (pCard) pCard = _CardInfo[STBIOL_TOKEN-1].delete_a_card(pCard);
       if (exist_symmetry_related_chain) Reorder_Stbiol();

       if (!found_order && _num_mol) {
            count = 1;
            tokenid[0] = ATOMP_TOKEN; tokenid[1] = ATOMN_TOKEN;  tokenid[2] = ATOMS_TOKEN;
            tokenid[3] = HETAD_TOKEN; tokenid[4] = HETAI_TOKEN;  tokenid[5] = HETIC_TOKEN;
            tokenid[6] = HETAC_TOKEN; tokenid[7] = HETAIN_TOKEN; tokenid[8] = HETAS_TOKEN;
            for (k = 0; k < 9; k++) {
                 for (i = 0; i < _n_stbiol; i++) {
                      chain = _molecules[_rep_mol]->GetFirstChain();
                      while (chain) {
                           if (_stbiol[i]->NDB_Strand_ID == chain->ChainID()) break;
                           chain = _molecules[_rep_mol]->GetNextChain();
                      }
                      if (chain && chain->chain_type() == tokenid[k]) {
                           _stbiol[i]->order = count;
                           count++;
                      }
                 }
            }
       }
}

void _VALIDATION::Reorder_Stbiol()
{
       int i, j, count, asymId, asymId_2;
       char asym_id[5];
       _STBIOL **tmp = NULL;

       tmp = _stbiol;
       _stbiol = new _STBIOL*[_n_stbiol];
       for (i = 0; i < _n_stbiol; i++) _stbiol[i] = NULL;
       j = -1;
       count = 0;
       asymId = 'A';
       asymId_2 = '@';
       while (1) {
            j = find_asymmetric_chains(_n_stbiol, tmp, j);
            if (j < 0) break;
            _stbiol[count] = new _STBIOL;
            _stbiol[count]->internal_order = tmp[j]->internal_order;
            _stbiol[count]->order = tmp[j]->order;
            _stbiol[count]->Biol_ID = tmp[j]->Biol_ID;
            _stbiol[count]->Asym_ID.Copy(tmp[j]->Asym_ID);
            strcpy(_stbiol[count]->PDB_Strand_ID, tmp[j]->PDB_Strand_ID);
            strcpy(_stbiol[count]->PDB_Strand_ID_Flag, tmp[j]->PDB_Strand_ID_Flag);
            strcpy(_stbiol[count]->Symmetry, tmp[j]->Symmetry);
            _stbiol[count]->bbrn = tmp[j]->bbrn;
            _stbiol[count]->bern = tmp[j]->bern;
            _stbiol[count]->abrn = tmp[j]->abrn;
            _stbiol[count]->aern = tmp[j]->aern;

            if (asymId_2 != '@') sprintf(asym_id, "%c%c", asymId, asymId_2);
            else sprintf(asym_id, "%c", asymId);
            _stbiol[count]->NDB_Strand_ID.Copy(asym_id);

            asymId++;
            if (asymId > 'Z') {
                 asymId = 'A';
                 asymId_2++;
                 if (asymId_2 > 'Z') asymId_2 = 'A';
            }
            count++;

            i = -1;
            while (1) {
                 i = find_symmetry_related_chain(_n_stbiol, tmp, j, i);
                 if (i < 0) break;
                 _stbiol[count] = new _STBIOL;
                 _stbiol[count]->internal_order = tmp[i]->internal_order;
                 _stbiol[count]->order = tmp[i]->order;
                 _stbiol[count]->Biol_ID = tmp[i]->Biol_ID;
                 _stbiol[count]->Asym_ID.Copy(tmp[i]->Asym_ID);
                 strcpy(_stbiol[count]->PDB_Strand_ID, tmp[i]->PDB_Strand_ID);
                 strcpy(_stbiol[count]->PDB_Strand_ID_Flag, tmp[i]->PDB_Strand_ID_Flag);
                 strcpy(_stbiol[count]->Symmetry, tmp[i]->Symmetry);
                 _stbiol[count]->bbrn = tmp[i]->bbrn;
                 _stbiol[count]->bern = tmp[i]->bern;
                 _stbiol[count]->abrn = tmp[i]->abrn;
                 _stbiol[count]->aern = tmp[i]->aern;

                 if (asymId_2 != '@') sprintf(asym_id, "%c%c", asymId, asymId_2);
                 else sprintf(asym_id, "%c", asymId);
                 _stbiol[count]->NDB_Strand_ID.Copy(asym_id);

                 asymId++;
                 if (asymId > 'Z') {
                      asymId = 'A';
                      asymId_2++;
                      if (asymId_2 > 'Z') asymId_2 = 'A';
                 }
                 count++;
            }
       }
       if (tmp) {
            for (i = 0; i < _n_stbiol; i++) if (tmp[i]) delete tmp[i];
            delete [] tmp;
       }
}

void _VALIDATION::Input_Link()
{
       int FstIndex, FstRes, SndIndex, SndRes;
       if (_num_mol == 0 || _molecules == NULL) return;

       _MOLECULE *mol = _molecules[0];

       One_Card_Info_Format *pCard = _CardInfo[LINK_TOKEN-1].Head();
       while (pCard) {
            if (mol->find_pdb_residue(pCard->Field(4), pCard->Field(3),
                  atoi(pCard->Field(5)), pCard->Field(6), FstIndex, FstRes) &&
                mol->find_pdb_residue(pCard->Field(10), pCard->Field(9),
                  atoi(pCard->Field(11)), pCard->Field(12), SndIndex, SndRes)) {
                 Insert_a_Link(pCard->Field(1), pCard->Field(2), FstIndex, FstRes,
                        pCard->Field(7), pCard->Field(8), SndIndex, SndRes,
                        pCard->Field(13), pCard->Field(14), pCard->Field(16));
            }
            pCard = pCard->Next();
       }
       _CardInfo[LINK_TOKEN-1].clear_Cards();
}

void _VALIDATION::update_residues_nomenclature(const int ndb_only)
{
       int m;
       _CHAIN *chain = NULL;
       if (_num_mol == 0 || _molecules == NULL) return;

       for (m = 0; m < _num_mol; m++) {
            chain = _molecules[m]->GetFirstChain();
            while (chain) {
                 chain->update_residues_nomenclature(ndb_only);
                 chain = _molecules[m]->GetNextChain();
            }
       }
}

void _VALIDATION::match_stbiol_with_molecules()
{
       int i, j, m, serialNo, prOrder, naOrder, count, n_tmp;
       int asymId, asymId_2, index;
       char asym_id[5], old_asym_id[5];
       _STBIOL **tmp = NULL, **tmp1 = NULL;
       _CHAIN *chain = NULL;
       One_Card_Info_Format *pCard = NULL;

       if (_num_mol == 0 || _molecules == NULL) return;

       chain = _molecules[_rep_mol]->GetFirstChain();
       while (chain) {
            for (j = 0; j < _n_stbiol; j++) {
                 if (_stbiol[j]->Asym_ID == chain->ChainID() &&
                     !strcmp(_stbiol[j]->Symmetry, "1_555")) break;
            }
            if (j == _n_stbiol) break;
            chain = _molecules[_rep_mol]->GetNextChain();
       }
       if (!chain) {
            pCard = _CardInfo[SEQIFO_TOKEN-1].Head();
            while (pCard) pCard = _CardInfo[SEQIFO_TOKEN-1].delete_a_card(pCard);
            serialNo = 0;
            prOrder = 0;
            naOrder = 0;
            chain = _molecules[_rep_mol]->GetFirstChain();
            while (chain) {
                 if (!chain->has_sequence()) {
                      chain = _molecules[_rep_mol]->GetNextChain();
                      continue;
                 }
                 pCard = _CardInfo[SEQIFO_TOKEN-1].
                           add_a_new_card(NdbToken[SEQIFO_TOKEN-1], 0);
                 pCard->AddElementToField(++serialNo, 1);
                 pCard->AddElementToField(chain->ChainID(), 2);
                 pCard->AddElementToField(chain->PDB_ChainID(), 3);
                 pCard->AddElementToField(chain->PUB_ChainID(), 4);
                 if (chain->chain_type() == ATOMN_TOKEN) {
                      pCard->AddElementToField("NA", 5);
                      pCard->AddElementToField(++naOrder, 6);
                 } else if (chain->chain_type() == ATOMP_TOKEN) {
                      pCard->AddElementToField("PR", 5);
                      pCard->AddElementToField(++prOrder, 6);
                 }
                 if (chain->isModified())
                      pCard->AddElementToField("Y", 7);
                 else pCard->AddElementToField("N", 7);
                 pCard->AddElementToField(chain->entity_id(), 9);
                 chain = _molecules[_rep_mol]->GetNextChain();
            }
       }

       tmp = _stbiol; n_tmp = _n_stbiol;
       count = 0;
       for (i = 0; i < n_tmp; i++) {
            if (strcmp(tmp[i]->Symmetry, "1_555")) count++;
       }
       _n_stbiol = _molecules[_rep_mol]->Num_Chain() + count;
       _stbiol = new _STBIOL*[_n_stbiol];
       for (i = 0; i < _n_stbiol; i++) _stbiol[i] = NULL;

       asymId = 'A';
       asymId_2 = '@';

       index = 0;
       chain = _molecules[_rep_mol]->GetFirstChain();
       while (chain) {
            if (asymId_2 != '@') sprintf(asym_id, "%c%c", asymId, asymId_2);
            else sprintf(asym_id, "%c", asymId);
            strcpy(old_asym_id, asym_id);

            if ((index + 1) > _n_stbiol) {
                 tmp1 = _stbiol;
                 _stbiol = new _STBIOL*[index + 1];
                 for (i = 0; i < _n_stbiol; i++) _stbiol[i] = tmp1[i];
                 for (i = _n_stbiol; i < index + 1; i++) _stbiol[i] = NULL;
                 _n_stbiol = index + 1;
                 if (tmp1) delete [] tmp1;
            }
            _stbiol[index] = new _STBIOL;
            _stbiol[index]->internal_order = index + 1;
            chain->set_internal_order(index + 1);
            _stbiol[index]->order = chain->order();
            _stbiol[index]->Biol_ID = chain->biol_id();
            _stbiol[index]->Asym_ID.Copy(asym_id);
            _stbiol[index]->NDB_Strand_ID.Copy(asym_id);
            strcpy(_stbiol[index]->PDB_Strand_ID, chain->PDB_ChainID());
            strcpy(_stbiol[index]->PDB_Strand_ID_Flag, chain->PDB_ChainID_Flag());
            strcpy(_stbiol[index]->Symmetry, "1_555");
            _stbiol[index]->bbrn = 1;
            _stbiol[index]->bern = chain->TotalResidueNumbers();
            _stbiol[index]->abrn = 1;
            _stbiol[index]->aern = chain->TotalResidueNumbers();
            index++;

            if (count) {
                 j = -1;
                 do {
                      j = find_symmetry_related_chains(n_tmp, tmp, j,
                                        chain->ChainID());;
                      if (j >= 0) {
                           if ((index + 1) > _n_stbiol) {
                                tmp1 = _stbiol;
                                _stbiol = new _STBIOL*[index + 1];
                                for (i = 0; i < _n_stbiol; i++) _stbiol[i] = tmp1[i];
                                for (i = _n_stbiol; i < index + 1; i++) _stbiol[i] = NULL;
                                _n_stbiol = index + 1;
                                if (tmp1) delete [] tmp1;
                           }
                           _stbiol[index] = new _STBIOL;
                           _stbiol[index]->internal_order = index + 1;
                           _stbiol[index]->order = tmp[j]->order;
                           _stbiol[index]->Biol_ID = tmp[j]->Biol_ID;
                           _stbiol[index]->Asym_ID.Copy(old_asym_id);
                           asymId++;
                           if (asymId > 'Z') {
                                asymId = 'A';
                                asymId_2++;
                                if (asymId_2 > 'Z') asymId_2 = 'A';
                           }
                           if (asymId_2 != '@')
                                sprintf(asym_id, "%c%c", asymId, asymId_2);
                           else sprintf(asym_id, "%c", asymId);
                           _stbiol[index]->NDB_Strand_ID.Copy(asym_id);
                           strcpy(_stbiol[index]->PDB_Strand_ID, tmp[j]->PDB_Strand_ID);
                           strcpy(_stbiol[index]->PDB_Strand_ID_Flag, tmp[j]->PDB_Strand_ID_Flag);
                           strcpy(_stbiol[index]->Symmetry, tmp[j]->Symmetry);
                           _stbiol[index]->bbrn = 1;
                           _stbiol[index]->bern = chain->TotalResidueNumbers();
                           _stbiol[index]->abrn = 1;
                           _stbiol[index]->aern = chain->TotalResidueNumbers();
                           index++;
                      }
                 } while (j >= 0);
            }
            asymId++;
            if (asymId > 'Z') {
                 asymId = 'A';
                 asymId_2++;
                 if (asymId_2 > 'Z') asymId_2 = 'A';
            }
            chain = _molecules[_rep_mol]->GetNextChain();
       }
       _n_stbiol = index;
       if (tmp) {
            for (i = 0; i < n_tmp; i++) if (tmp[i]) delete tmp[i];
            delete [] tmp;
       }

       for (i = 0;  i < _n_stbiol; i++) {
            if (!_stbiol[i]) continue;
            if (_stbiol[i]->order <= 0) break;
       }

       if (i < _n_stbiol) {
            for (i = 0; i < _n_stbiol; i++) {
                 if (!_stbiol[i]) continue;
                 _stbiol[i]->order = _stbiol[i]->internal_order;
            }
       }

       for (m = 0; m < _num_mol; m++) {
            j = -1;
            chain = _molecules[m]->GetFirstChain();
            while (chain) {
                 j = find_asymmetric_chains(_n_stbiol, _stbiol, j);
                 if (j >= 0) {
                      chain->set_ChainID(_stbiol[j]->NDB_Strand_ID.Text());
                      chain->set_order(_stbiol[j]->order);
                 }
                 chain = _molecules[m]->GetNextChain();
            }

            if (!m) {
                 pCard = _CardInfo[SEQIFO_TOKEN-1].Head();
                 while (pCard) pCard = _CardInfo[SEQIFO_TOKEN-1].delete_a_card(pCard);
                 serialNo = 0;
                 prOrder = 0;
                 naOrder = 0;
                 chain = _molecules[m]->GetFirstChain();
                 while (chain) {
                      if (!chain->has_sequence()) {
                           chain = _molecules[m]->GetNextChain();
                           continue;
                      }
                      pCard = _CardInfo[SEQIFO_TOKEN-1].
                                add_a_new_card(NdbToken[SEQIFO_TOKEN-1], 0);
                      pCard->AddElementToField(++serialNo, 1);
                      pCard->AddElementToField(chain->ChainID(), 2);
                      pCard->AddElementToField(chain->PDB_ChainID(), 3);
                      pCard->AddElementToField(chain->PUB_ChainID(), 4);
                      if (chain->chain_type() == ATOMN_TOKEN) {
                           pCard->AddElementToField("NA", 5);
                           pCard->AddElementToField(++naOrder, 6);
                      } else if (chain->chain_type() == ATOMP_TOKEN) {
                           pCard->AddElementToField("PR", 5);
                           pCard->AddElementToField(++prOrder, 6);
                      }
                      if (chain->isModified())
                           pCard->AddElementToField("Y", 7);
                      else pCard->AddElementToField("N", 7);
                      pCard->AddElementToField(chain->entity_id(), 9);
                      chain = _molecules[m]->GetNextChain();
                 }
            }
       }
}


void _VALIDATION::Insert_a_Link(const char *FstAtom, const char *altLoc1, const int FstIndex,
           const int FstRes, const char *SndAtom, const char *altLoc2, const int SndIndex,
           const int SndRes, const char *SymOP_1, const char *SymOP_2, const char *details)
{
       int i = 0;
       _LINK **tmp = NULL;
       for (i = 0; i < _n_link; i++) {
            if (!strcmp(_link[i]->FstAtom, FstAtom) && !strcmp(_link[i]->altLoc1, altLoc1) &&
                _link[i]->FstIndex == FstIndex && _link[i]->FstRes == FstRes &&
                !strcmp(_link[i]->SndAtom, SndAtom) && !strcmp(_link[i]->altLoc2, altLoc2) &&
                _link[i]->SndIndex == SndIndex && _link[i]->SndRes == SndRes &&
                !strcmp(_link[i]->SymOP_1, SymOP_1) && !strcmp(_link[i]->SymOP_2, SymOP_2) ||
                !strcmp(_link[i]->FstAtom, SndAtom) && !strcmp(_link[i]->altLoc1, altLoc2) &&
                _link[i]->FstIndex == SndIndex && _link[i]->FstRes == SndRes &&
                !strcmp(_link[i]->SndAtom, FstAtom) && !strcmp(_link[i]->altLoc2, altLoc1) &&
                _link[i]->SndIndex == FstIndex && _link[i]->SndRes == FstRes &&
                !strcmp(_link[i]->SymOP_1, SymOP_2) && !strcmp(_link[i]->SymOP_2, SymOP_1))
                 break;
       }
       if (i < _n_link) return;

       if (_n_link >= _alloc_link) {
            _alloc_link += 10;
            tmp = _link;
            _link = new _LINK*[_alloc_link];
            for (i = 0; i < _n_link; i++) _link[i] = tmp[i];
            for (i = _n_link; i < _alloc_link; i++) _link[i] = NULL;
            delete [] tmp;
       }
       _link[_n_link] = new _LINK;
       strcpy(_link[_n_link]->FstAtom, FstAtom);
       strcpy(_link[_n_link]->altLoc1, altLoc1);
       _link[_n_link]->FstIndex = FstIndex;
       _link[_n_link]->FstRes = FstRes;
       strcpy(_link[_n_link]->SndAtom, SndAtom);
       strcpy(_link[_n_link]->altLoc2, altLoc2);
       _link[_n_link]->SndIndex = SndIndex;
       _link[_n_link]->SndRes = SndRes;
       strcpy(_link[_n_link]->SymOP_1, SymOP_1);
       strcpy(_link[_n_link]->SymOP_2, SymOP_2);
       int len = strlen(details) + 1;
       _link[_n_link]->details = new char[len];
       strcpy(_link[_n_link]->details, details);
       _n_link++;
}

void _VALIDATION::Insert_a_Mismat(const int FstIndex, const int FstRes, const int SndIndex,
                  const int SndRes)
{
       int i = 0;
       _MISMAT **tmp = NULL;
       for (i = 0; i < _n_mismat; i++) {
            if (_mismat[i]->FstIndex == FstIndex && _mismat[i]->FstRes == FstRes &&
                _mismat[i]->SndIndex == SndIndex && _mismat[i]->SndRes == SndRes)
                 break;
       }
       if (i < _n_mismat) return;

       if (_n_mismat >= _alloc_mismat) {
            _alloc_mismat += 10;
            tmp = _mismat;
            _mismat = new _MISMAT*[_alloc_mismat];
            for (i = 0; i < _n_mismat; i++) _mismat[i] = tmp[i];
            for (i = _n_mismat; i < _alloc_mismat; i++) _mismat[i] = NULL;
            delete [] tmp;
       }
       _mismat[_n_mismat] = new _MISMAT;
       _mismat[_n_mismat]->FstIndex = FstIndex;
       _mismat[_n_mismat]->FstRes = FstRes;
       _mismat[_n_mismat]->SndIndex = SndIndex;
       _mismat[_n_mismat]->SndRes = SndRes;
       _n_mismat++;
}

void _VALIDATION::Insert_a_Bspair(const char *FstAtom, const int FstIndex, const int FstRes,
           const char *SndAtom, const int SndIndex, const int SndRes,
           const char *Asym_or_Gen, const char *Type)
{
       int i = 0;
       _BSPAIR **tmp = NULL;
       for (i = 0; i < _n_bspair; i++) {
            if (!strcmp(_bspair[i]->FstAtom, FstAtom) &&
                _bspair[i]->FstIndex == FstIndex && _bspair[i]->FstRes == FstRes &&
                !strcmp(_bspair[i]->SndAtom, SndAtom) &&
                _bspair[i]->SndIndex == SndIndex && _bspair[i]->SndRes == SndRes &&
                !strcmp(_bspair[i]->Asym_or_Gen, Asym_or_Gen) &&
                !strcmp(_bspair[i]->Type, Type)) break;
       }
       if (i < _n_bspair) return;

       if (_n_bspair >= _alloc_bspair) {
            _alloc_bspair += 10;
            tmp = _bspair;
            _bspair = new _BSPAIR*[_alloc_bspair];
            for (i = 0; i < _n_bspair; i++) _bspair[i] = tmp[i];
            for (i = _n_bspair; i < _alloc_bspair; i++) _bspair[i] = NULL;
            delete [] tmp;
       }
       _bspair[_n_bspair] = new _BSPAIR;
       strcpy(_bspair[_n_bspair]->FstAtom, FstAtom);
       _bspair[_n_bspair]->FstIndex = FstIndex;
       _bspair[_n_bspair]->FstRes = FstRes;
       strcpy(_bspair[_n_bspair]->SndAtom, SndAtom);
       _bspair[_n_bspair]->SndIndex = SndIndex;
       _bspair[_n_bspair]->SndRes = SndRes;
       strcpy(_bspair[_n_bspair]->Asym_or_Gen, Asym_or_Gen);
       strcpy(_bspair[_n_bspair]->Type, Type);
       _n_bspair++;
}

void _VALIDATION::generate_symmetry_strands(const int change_chnid)
{
       int i = 0, j = 0, k = 0, op = 0, trans[3], sucessful = 0, len;

       if (_num_mol == 0 || _molecules == NULL) return;

       for (i = 0; i < _n_stbiol; i++) {
            if (strcmp(_stbiol[i]->Symmetry, NDB_BASE_SYMMETRY)) break;
       }
       if (i == _n_stbiol) return;

       _molecules[0]->convert_between_orthogonal_and_fractional(_cell, NDB_TRANS_ORTHO_TO_FRAC);
       for (i = 0; i < _n_stbiol; i++) {
            if (!_stbiol[i]) continue;
            if (strcmp(_stbiol[i]->Symmetry, NDB_BASE_SYMMETRY)) {
                 op = atoi(_stbiol[i]->Symmetry) - 1;
                 trans[0] = trans[1] = trans[2] = 0;
                 len = strlen(_stbiol[i]->Symmetry); 
                 for (j = 0; j < len; j++)
                      if (_stbiol[i]->Symmetry[j] == '_') break;
                 if (j+3 < len) {
                      for (k = 0; k < 3; k++)
                           trans[k] = _stbiol[i]->Symmetry[j+k+1] - '5';
                 }
                 sucessful = 0;
                 if (change_chnid)
                      sucessful = _molecules[0]->symmetry_related_chain(_stbiol[i]->internal_order,
                           _stbiol[i]->order, _stbiol[i]->Biol_ID, _stbiol[i]->Asym_ID.Text(),
                           _stbiol[i]->NDB_Strand_ID.Text(), _stbiol[i]->PDB_Strand_ID,
                           _cell, op, trans[0], trans[1], trans[2], 1);
                 else sucessful= _molecules[0]->symmetry_related_chain(_stbiol[i]->internal_order,
                           _stbiol[i]->order, _stbiol[i]->Biol_ID, _stbiol[i]->Asym_ID.Text(),
                           "", _stbiol[i]->PDB_Strand_ID, _cell, op, trans[0], trans[1],
                           trans[2], 1);
                 if (sucessful) strcpy(_stbiol[i]->Symmetry, NDB_BASE_SYMMETRY);
            }
       }
       _molecules[0]->convert_between_orthogonal_and_fractional(_cell, NDB_TRANS_FRAC_TO_ORTHO);
}

void _VALIDATION::insert_bond(const char *ChainID, const char *ResName, const int ResNum,
           const char *ins_code, const char *Rep_Name, const char *type, const double val,
           const double ept, const double std, const int mol_id, _ATOM *fst, _ATOM *snd)
{
       int i = 0;
       _BOND **tmp = NULL;
       if (_n_bond >= _alloc_bond) {
            _alloc_bond += 10000;
            tmp = _bond;
            _bond = new _BOND*[_alloc_bond];
            for (i = 0; i < _n_bond; i++) _bond[i] = tmp[i];
            for (i = _n_bond; i < _alloc_bond; i++) _bond[i] = NULL;
            delete [] tmp;
       }
       _bond[_n_bond] = new _BOND;
       _bond[_n_bond]->Mol_ID = mol_id;
       strcpy(_bond[_n_bond]->ChainID, ChainID);
       strcpy(_bond[_n_bond]->ResName, ResName);
       _bond[_n_bond]->ResNum = ResNum;
       strcpy(_bond[_n_bond]->ins_code, ins_code);
       strcpy(_bond[_n_bond]->Rep_Name, Rep_Name);
       strcpy(_bond[_n_bond]->type, type);
       _bond[_n_bond]->val = val;
       _bond[_n_bond]->ept = ept;
       _bond[_n_bond]->std = std;
       _bond[_n_bond]->fst = fst;
       _bond[_n_bond]->snd = snd;
       _n_bond++;

       CifString index(ResName);
       if (_bondResIndex.Seek(index) < 0) _bondResIndex.Add(index);
       index += Rep_Name;
       _bondComIndex.Add(index);
       index.Copy(Rep_Name);
       _bondNamIndex.Add(index);
}

void _VALIDATION::insert_angle(const char *ChainID, const char *ResName, const int ResNum,
           const char *ins_code, const char *Rep_Name, const char *type, const double val,
           const double ept, const double std, const int mol_id, _ATOM *fst, _ATOM *snd,
           _ATOM *trd)
{
       int i = 0;
       _ANGLE **tmp = NULL;
       if (_n_angle >= _alloc_angle) {
            _alloc_angle += 10000;
            tmp = _angle;
            _angle = new _ANGLE*[_alloc_angle];
            for (i = 0; i < _n_angle; i++) _angle[i] = tmp[i];
            for (i = _n_angle; i < _alloc_angle; i++) _angle[i] = NULL;
            delete [] tmp;
       }
       _angle[_n_angle] = new _ANGLE;
       _angle[_n_angle]->Mol_ID = mol_id;
       strcpy(_angle[_n_angle]->ChainID, ChainID);
       strcpy(_angle[_n_angle]->ResName, ResName);
       _angle[_n_angle]->ResNum = ResNum;
       strcpy(_angle[_n_angle]->ins_code, ins_code);
       strcpy(_angle[_n_angle]->Rep_Name, Rep_Name);
       strcpy(_angle[_n_angle]->type, type);
       _angle[_n_angle]->val = val;
       _angle[_n_angle]->ept = ept;
       _angle[_n_angle]->std = std;
       _angle[_n_angle]->fst = fst;
       _angle[_n_angle]->snd = snd;
       _angle[_n_angle]->trd = trd;
       _n_angle++;

       CifString index(ResName);
       if (_angleResIndex.Seek(index) < 0) _angleResIndex.Add(index);
       index += Rep_Name;
       _angleComIndex.Add(index);
       index.Copy(Rep_Name);
       _angleNamIndex.Add(index);
}

void _VALIDATION::insert_torsion(const char *ChainID, const char *ResName, const int ResNum,
           const char *ins_code, const char *Rep_Name, const char *type, const double val,
           const int mol_id, _ATOM *fst, _ATOM *snd, _ATOM *trd, _ATOM *fth)
{
       int i = 0;
       _TORSION **tmp = NULL;
       if (_n_torsion >= _alloc_torsion) {
            _alloc_torsion += 10000;
            tmp = _torsion;
            _torsion = new _TORSION*[_alloc_torsion];
            for (i = 0; i < _n_torsion; i++) _torsion[i] = tmp[i];
            for (i = _n_torsion; i < _alloc_torsion; i++) _torsion[i] = NULL;
            delete [] tmp;
       }
       _torsion[_n_torsion] = new _TORSION;
       _torsion[_n_torsion]->Mol_ID = mol_id;
       strcpy(_torsion[_n_torsion]->ChainID, ChainID);
       strcpy(_torsion[_n_torsion]->ResName, ResName);
       _torsion[_n_torsion]->ResNum = ResNum;
       strcpy(_torsion[_n_torsion]->ins_code, ins_code);
       strcpy(_torsion[_n_torsion]->Rep_Name, Rep_Name);
       strcpy(_torsion[_n_torsion]->type, type);
       _torsion[_n_torsion]->val = val;
       _torsion[_n_torsion]->fst = fst;
       _torsion[_n_torsion]->snd = snd;
       _torsion[_n_torsion]->trd = trd;
       _torsion[_n_torsion]->fth = fth;
       _n_torsion++;

       CifString index(Rep_Name);
       _torsionIndex.Add(index);
}

void _VALIDATION::insert_torsion_pair(const char *ChainID, const char *ResName,
          const int ResNum, const char *ins_code, const double phi, const double psi,
          const int mol_id)
{
       int i = 0;
       _TORSION **tmp = NULL;
       if (_n_t_pairs >= _alloc_t_pairs) {
            _alloc_t_pairs += 100;
            tmp = _t_pairs;
            _t_pairs = new _TORSION*[_alloc_t_pairs];
            for (i = 0; i < _n_t_pairs; i++) _t_pairs[i] = tmp[i];
            for (i = _n_t_pairs; i < _alloc_t_pairs; i++) _t_pairs[i] = NULL;
            delete [] tmp;
       }
       _t_pairs[_n_t_pairs] = new _TORSION;
       _t_pairs[_n_t_pairs]->Mol_ID = mol_id;
       strcpy(_t_pairs[_n_t_pairs]->ChainID, ChainID);
       strcpy(_t_pairs[_n_t_pairs]->ResName, ResName);
       _t_pairs[_n_t_pairs]->ResNum = ResNum;
       strcpy(_t_pairs[_n_t_pairs]->ins_code, ins_code);
       _t_pairs[_n_t_pairs]->val = phi;
       _t_pairs[_n_t_pairs]->ept = psi;
       _n_t_pairs++;
}

void _VALIDATION::insert_pair_z_a_1(const int res_num, const double x, const double y)
{
       int i = 0;
       _PAIR_VALUE **tmp = NULL;
       if (_n_z_a_1 >= _alloc_z_a_1) {
            _alloc_z_a_1 += 100;
            tmp = _z_a_1;
            _z_a_1 = new _PAIR_VALUE*[_alloc_z_a_1];
            for (i = 0; i < _n_z_a_1; i++) _z_a_1[i] = tmp[i];
            for (i = _n_z_a_1; i < _alloc_z_a_1; i++) _z_a_1[i] = NULL;
            delete [] tmp;
       }
       _z_a_1[_n_z_a_1] = new _PAIR_VALUE;
       _z_a_1[_n_z_a_1]->res_num = res_num;
       _z_a_1[_n_z_a_1]->x = x;
       _z_a_1[_n_z_a_1]->y = y;
       _n_z_a_1++;
}

void _VALIDATION::insert_pair_z_b_1(const int res_num, const double x, const double y)
{
       int i = 0;
       _PAIR_VALUE **tmp = NULL;
       if (_n_z_b_1 >= _alloc_z_b_1) {
            _alloc_z_b_1 += 100;
            tmp = _z_b_1;
            _z_b_1 = new _PAIR_VALUE*[_alloc_z_b_1];
            for (i = 0; i < _n_z_b_1; i++) _z_b_1[i] = tmp[i];
            for (i = _n_z_b_1; i < _alloc_z_b_1; i++) _z_b_1[i] = NULL;
            delete [] tmp;
       }
       _z_b_1[_n_z_b_1] = new _PAIR_VALUE;
       _z_b_1[_n_z_b_1]->res_num = res_num;
       _z_b_1[_n_z_b_1]->x = x;
       _z_b_1[_n_z_b_1]->y = y;
       _n_z_b_1++;
}

void _VALIDATION::insert_pair_z_e(const int res_num, const double x, const double y)
{
       int i = 0;
       _PAIR_VALUE **tmp = NULL;
       if (_n_z_e >= _alloc_z_e) {
            _alloc_z_e += 100;
            tmp = _z_e;
            _z_e = new _PAIR_VALUE*[_alloc_z_e];
            for (i = 0; i < _n_z_e; i++) _z_e[i] = tmp[i];
            for (i = _n_z_e; i < _alloc_z_e; i++) _z_e[i] = NULL;
            delete [] tmp;
       }
       _z_e[_n_z_e] = new _PAIR_VALUE;
       _z_e[_n_z_e]->res_num = res_num;
       _z_e[_n_z_e]->x = x;
       _z_e[_n_z_e]->y = y;
       _n_z_e++;
}

void _VALIDATION::insert_pair_a_g(const int res_num, const double x, const double y)
{
       int i = 0;
       _PAIR_VALUE **tmp = NULL;
       if (_n_a_g >= _alloc_a_g) {
            _alloc_a_g += 100;
            tmp = _a_g;
            _a_g = new _PAIR_VALUE*[_alloc_a_g];
            for (i = 0; i < _n_a_g; i++) _a_g[i] = tmp[i];
            for (i = _n_a_g; i < _alloc_a_g; i++) _a_g[i] = NULL;
            delete [] tmp;
       }
       _a_g[_n_a_g] = new _PAIR_VALUE;
       _a_g[_n_a_g]->res_num = res_num;
       _a_g[_n_a_g]->x = x;
       _a_g[_n_a_g]->y = y;
       _n_a_g++;
}

void _VALIDATION::insert_pair_z_x(const int res_num, const double x, const double y)
{
       int i = 0;
       _PAIR_VALUE **tmp = NULL;
       if (_n_z_x >= _alloc_z_x) {
            _alloc_z_x += 100;
            tmp = _z_x;
            _z_x = new _PAIR_VALUE*[_alloc_z_x];
            for (i = 0; i < _n_z_x; i++) _z_x[i] = tmp[i];
            for (i = _n_z_x; i < _alloc_z_x; i++) _z_x[i] = NULL;
            delete [] tmp;
       }
       _z_x[_n_z_x] = new _PAIR_VALUE;
       _z_x[_n_z_x]->res_num = res_num;
       _z_x[_n_z_x]->x = x;
       _z_x[_n_z_x]->y = y;
       _n_z_x++;
}

void _VALIDATION::insert_pair_d_x(const int res_num, const double x, const double y)
{
       int i = 0;
       _PAIR_VALUE **tmp = NULL;
       if (_n_d_x >= _alloc_d_x) {
            _alloc_d_x += 100;
            tmp = _d_x;
            _d_x = new _PAIR_VALUE*[_alloc_d_x];
            for (i = 0; i < _n_d_x; i++) _d_x[i] = tmp[i];
            for (i = _n_d_x; i < _alloc_d_x; i++) _d_x[i] = NULL;
            delete [] tmp;
       }
       _d_x[_n_d_x] = new _PAIR_VALUE;
       _d_x[_n_d_x]->res_num = res_num;
       _d_x[_n_d_x]->x = x;
       _d_x[_n_d_x]->y = y;
       _n_d_x++;
}

void _VALIDATION::get_link_record(ISTable *Table, const int is_rcsb_link)
{
       int irow, BegIndex, BegRes, EndIndex, EndRes, beg, end;
       char comment[10];
       CifString atom1, loc1, atom2, loc2, symm1, symm2, type;
       if (_num_mol == 0 || _molecules == NULL) return;
       _MOLECULE *mol = _molecules[0];

       int rowNo = Table->GetNumRows();

       int conn_type_id = Table->GetColumnIndex("conn_type_id");
       int ptnr1_label_alt_id = Table->GetColumnIndex("ndb_ptnr1_label_alt_loc");
       if (is_rcsb_link)
            ptnr1_label_alt_id = Table->GetColumnIndex("ptnr1_label_alt_id");
       int ptnr1_label_asym_id = Table->GetColumnIndex("ptnr1_label_asym_id");
       int ptnr1_label_atom_id = Table->GetColumnIndex("ptnr1_label_atom_id");
       int ptnr1_label_comp_id = Table->GetColumnIndex("ptnr1_label_comp_id");
       int ptnr1_label_seq_id = Table->GetColumnIndex("ptnr1_label_seq_id");
       int ptnr1_label_ins_code = Table->GetColumnIndex("ndb_ptnr1_label_ins_code");
       if (is_rcsb_link)
            ptnr1_label_ins_code = Table->GetColumnIndex("ptnr1_label_ins_code");
       int ptnr1_symmetry = Table->GetColumnIndex("ptnr1_symmetry");
       int ptnr2_label_alt_id = Table->GetColumnIndex("ndb_ptnr2_label_alt_loc");
       if (is_rcsb_link)
            ptnr2_label_alt_id = Table->GetColumnIndex("ptnr2_label_alt_id");
       int ptnr2_label_asym_id = Table->GetColumnIndex("ptnr2_label_asym_id");
       int ptnr2_label_atom_id = Table->GetColumnIndex("ptnr2_label_atom_id");
       int ptnr2_label_comp_id = Table->GetColumnIndex("ptnr2_label_comp_id");
       int ptnr2_label_seq_id = Table->GetColumnIndex("ptnr2_label_seq_id");
       int ptnr2_label_ins_code = Table->GetColumnIndex("ndb_ptnr2_label_ins_code");
       if (is_rcsb_link)
            ptnr2_label_ins_code = Table->GetColumnIndex("ptnr2_label_ins_code");
       int ptnr2_symmetry = Table->GetColumnIndex("ptnr2_symmetry");

       for (irow = 0; irow < rowNo; irow++) {
            memset(comment, '\0', 10);
            atom1.Clear(); loc1.Clear(); atom2.Clear(); loc2.Clear();
            symm1.Clear(); symm2.Clear(); type.Clear();
            if (!is_rcsb_link) {
                 get_value(type, Table, conn_type_id, irow);
                 if (strcasecmp(type.Text(), "link")) continue;
            }
            get_value(loc1, Table, ptnr1_label_alt_id, irow);
            get_value(atom1, Table, ptnr1_label_atom_id, irow);
            get_value(symm1, Table, ptnr1_symmetry, irow);
            get_value(loc2, Table, ptnr2_label_alt_id, irow);
            get_value(atom2, Table, ptnr2_label_atom_id, irow);
            get_value(symm2, Table, ptnr2_symmetry, irow);
            beg = get_residue_index(mol, Table, irow, -1, -1, -1,
                   ptnr1_label_comp_id, ptnr1_label_asym_id,
                   ptnr1_label_seq_id, ptnr1_label_ins_code,
                   BegIndex, BegRes);
            end = get_residue_index(mol, Table, irow, -1, -1, -1,
                   ptnr2_label_comp_id, ptnr2_label_asym_id,
                   ptnr2_label_seq_id, ptnr2_label_ins_code,
                   EndIndex, EndRes);
            if (!beg || !end) continue;
            if (symm1 == "1_555") symm1.Clear();
            if (symm2 == "1_555") symm2.Clear();
            Insert_a_Link(atom1.Text(), loc1.Text(), BegIndex, BegRes, atom2.Text(),
                 loc2.Text(), EndIndex, EndRes, symm1.Text(), symm2.Text(), comment);
       }
}

int get_residue_index(_MOLECULE *mol, ISTable *Table, const int irow,
                const int ndb_comp_id, const int ndb_asym_id, const int ndb_seq_id,
                const int pdb_comp_id, const int pdb_asym_id, const int pdb_seq_id,
                const int ins_code_id, int &FstIndex, int &FstRes)
{
       FstIndex = -1; FstRes = -1;

       CifString res_name, chain_id, ins_code, value;
       int seq_num = -99999;
       get_value(res_name, Table, ndb_comp_id, irow);
       get_value(chain_id, Table, ndb_asym_id, irow);
       if (get_value(value, Table, ndb_seq_id, irow))
            seq_num = atoi(value.Text());
       get_value(ins_code, Table, ins_code_id, irow);

       if (chain_id != "" && res_name != "" && seq_num != -99999 &&
           mol->find_ndb_residue(chain_id.Text(), res_name.Text(), seq_num,
           ins_code.Text(), FstIndex, FstRes)) return 1;

       get_value(res_name, Table, pdb_comp_id, irow);
       get_value(chain_id, Table, pdb_asym_id, irow);
       if (get_value(value, Table, pdb_seq_id, irow))
            seq_num = atoi(value.Text());

       if (pdb_comp_id >= 0 && pdb_asym_id >= 0 && pdb_seq_id >= 0 &&
           mol->find_pdb_residue(chain_id.Text(), res_name.Text(), seq_num,
           ins_code.Text(), FstIndex, FstRes)) return 1;

       return 0;
}

static int find_symmetry_related_chain(const int n_stbiol, _STBIOL **stbiol,
               const int i, const int index)
{
       int j;
       if (!stbiol[i]) return -1;
       for (j = 0; j < n_stbiol; j++) {
            if (!stbiol[j]) continue;
            if (stbiol[i]->Asym_ID == stbiol[j]->Asym_ID &&
                 strcmp(stbiol[j]->Symmetry, "1_555") && j > index) break;
       }
       if (j < n_stbiol) return j;
       else return -1;
}

static int find_symmetry_related_chains(const int n_stbiol, _STBIOL **stbiol,
               const int index, char *ndb_chnid)
{
       int i = 0, j = 0;
       for (i = 0; i < n_stbiol; i++) {
            if (!stbiol[i]) continue;
            if (stbiol[i]->NDB_Strand_ID == ndb_chnid) break;
       }
       if (i == n_stbiol) return -1;

       for (j = 0; j < n_stbiol; j++) {
            if (!stbiol[j]) continue;
            if (stbiol[i]->Asym_ID == stbiol[j]->Asym_ID &&
                 strcmp(stbiol[j]->Symmetry, "1_555") && j > index) break;
       }
       if (j < n_stbiol) return j;
       else return -1;
}

static int find_asymmetric_chains(const int n_stbiol, _STBIOL **stbiol,
               const int start)
{
       int j = 0;
       if ((start + 1) >= n_stbiol) return -1;

       for (j = start + 1; j < n_stbiol; j++) {
            if (!stbiol[j]) continue;
            if (!strcmp(stbiol[j]->Symmetry, "1_555")) break;
       }
       if (j < n_stbiol) return j;
       else return -1;
}
