/*
FILE:     write_letter.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 <sys/types.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>

#include "_validation.h"
#include "erf_util.h"
#include "ndb_misclib.h"
#include "util.h"

#define NDB_FIND_MISSING_RESIDUE               0
#define NDB_FIND_MISSING_ATOM                  1
#define NDB_FIND_EXTRA_ATOM                    2

#define letterpdb   "pdb_letter1"
#define letternmr   "nmr_letter"

#define letterVSRVxray   "vsrv_xray_letter"
#define letterVSRVnmr    "vsrv_nmr_letter"

#define letterADITxray  "adit_xray_letter"
#define letterADITnmr   "adit_nmr_letter"

static int  find_letter_token(char *line, char* token);
void ndb_writing_missing_words(FILE *infile, FILE *outfile);
static void passing_missing_words(const int missing, FILE *infile, const char *oldtoken);

void _VALIDATION::get_letter(FILE *outfile, const int is_prev_check)
{
       unsigned int i, j;
       int ret;
       char line[MxLen], token[MxLen];
       char date_string[MxStrLen], letterdbname[200];
       time_t curr_time;
       CifString message;
       FILE *fp = NULL;
     
       time(&curr_time);
       memset(date_string, 0, MxStrLen);
       strcpy(date_string, ctime(&curr_time));
       strcpy(date_string, &date_string[4]);

       for (i = 0; i < strlen(date_string); i++) {
            if (!strncmp(&date_string[i], "199", 3)) {
                 strcpy(&date_string[7], &date_string[i]);
            }
       } 

       ndb_clean_string(date_string);
       for (i = 0; i < strlen(date_string); i++) {
            if (date_string[i] == ' ') break;
       }
       for (j = strlen(date_string) - 1; j >= i; j--) {
            date_string[j + 1] = date_string[j];
       }
       date_string[i] = '.';
     
       for (i += 2; i < strlen(date_string); i++) {
            if (date_string[i] == ' ') break;
       }
       for (j = strlen(date_string); j >= i; j--) {
            date_string[j + 1] = date_string[j];
       }
       date_string[i] = ',';

       if (_experiment_type == EXPERIMENT_TYPE_NMR ||
           _experiment_type == EXPERIMENT_TYPE_MODEL) {
            if (is_prev_check == 2)
	         sprintf(letterdbname, "%s/data/ascii/%s", root_dir, letterADITnmr);
            else if (is_prev_check == 1)
	         sprintf(letterdbname, "%s/data/ascii/%s", root_dir, letterVSRVnmr);
	    else sprintf(letterdbname, "%s/data/ascii/%s", root_dir, letternmr);
       } else {
            if (is_prev_check==2)
	         sprintf(letterdbname, "%s/data/ascii/%s", root_dir, letterADITxray);
            else if (is_prev_check == 1)
	         sprintf(letterdbname, "%s/data/ascii/%s", root_dir, letterVSRVxray);
            else sprintf(letterdbname, "%s/data/ascii/%s", root_dir, letterpdb);
       }

       fp = fopen(letterdbname, "r");
       if (fp == NULL) {
            ndb_log_message(NDB_MSG_ERR,
                 "Unable to open residue name database: %s\n", letterdbname);
            return;
       }

       if (_experiment_type == EXPERIMENT_TYPE_NMR)
            calculate_all_contact(3.5, 0);
       else calculate_all_contact(3.5, 1);

       while (!feof(fp)) {
            fgets(line,MxLen,fp);
            for (i = 0; i < strlen(line); i++)  {
                 ret = find_letter_token(&line[i], token);

                 if (ret == FALSE) fprintf(outfile, "%c", line[i]);
                 else {
                      i += ret;
                      if (!strcmp(token, "DATE")) 
                           fprintf(outfile, date_string);
                      else if (!strcmp(token, "REPRINTS"))
                           passing_missing_words(FALSE, fp, token);
                      else {
                           ret = write_letter_token(fp, outfile, token);
                           if (ret == TRUE) break;
                      }
                 }
            }
       }
       fclose(fp);

       check_link_records(outfile);
       check_terminal_atoms(message);
       if (strcmp(message.Text(), "")) fprintf(outfile, "%s\n", message.Text());
}

int _VALIDATION::write_letter_token(FILE *infile, FILE *outfile, const char *token)
{
       unsigned int pos;
       int card_id, field_no, numRemark;
       char tmp_string[MxLen];
       One_Card_Info_Format *pCard = NULL;
     
       for (pos = 0; pos < strlen(token); pos++) {
            if (token[pos] == ' ') break;
       }
       strncpy(tmp_string, token, pos);
       tmp_string[pos] = 0;
       card_id = find_card_id(tmp_string);
       if (card_id == -1) write_special_letter_information(infile, 
                     outfile, token);
       else {
            for (; pos < strlen(token); pos++)
            if (token[pos] != ' ') break;
            strcpy(tmp_string, &token[pos]);
            if (!strcmp(tmp_string, "")) {
                 print_general_cards(outfile, card_id, 
                          NDB_FILE_FORMAT_NDB, numRemark, 0);
                 return 1;
            } else {
                 field_no = atoi(tmp_string) -1;
                 pCard = _CardInfo[card_id].Head();
                 if (pCard && strcmp(pCard->Field(field_no), ""))
                      fprintf(outfile, "%s", pCard->Field(field_no));
                 else if (NdbToken[card_id].FieldList[field_no].FieldType 
                     == NDB_DATE_FIELD) 
                      fprintf(outfile, "%s", "yyyy-mm-dd");
            }
       }

       if (card_id == -1) return 1;
       else return 0;
}

void _VALIDATION::write_special_letter_information(FILE *infile, 
        FILE *outfile, const char *token)
{
       if (!strcmp(token, "MISSING RESIDUES"))
            ndb_write_letter_misplace_atoms(NDB_FIND_MISSING_RESIDUE, 
                     infile, outfile, token);
       else if (!strcmp(token, "MISSING ATOMS"))
            ndb_write_letter_misplace_atoms(NDB_FIND_MISSING_ATOM, 
                     infile, outfile, token);
       else if (!strcmp(token, "EXTRA ATOMS"))
            ndb_write_letter_misplace_atoms(NDB_FIND_EXTRA_ATOM, 
                     infile, outfile, token);
       else if (!strcmp(token, "HYDROGEN ATOMS")) {
/*
            int id = find_card_id("COORDH");
            int found = 0;
            One_Card_Info_Format *pCard = _CardInfo[id].Head();
            if (pCard && !strcmp(pCard->Field(1), "Y")) found = 1;
            if (found && (_experiment_type & EXPERIMENT_TYPE_XRAY))
                 ndb_writing_missing_words(infile, outfile);
            else
*/
            passing_missing_words(FALSE, infile, token);
       } else if (!strcmp(token, "CHIRALITY")) {
/*
            if (ndb_check_stereochemistry(infile, outfile))
                 passing_missing_words(FALSE, infile, token);
*/
            ndb_check_stereochemistry(infile, outfile);
       } else if (!strcmp(token, "EZ")) {
/*
            if (ndb_check_E_Z_labeling(infile, outfile))
                 passing_missing_words(FALSE, infile, token);
*/
            if (_experiment_type == EXPERIMENT_TYPE_NMR)
                 ndb_check_E_Z_labeling(infile, outfile);
            else passing_missing_words(FALSE, infile, token);
       } else if (!strcmp(token, "CLOSE CONTACT1")) 
            find_out_range_waters(outfile);
       else if (!strcmp(token, "CLOSE CONTACT2"))
            move_out_range_waters(outfile);
       else if (!strcmp(token,"STRUCTURE FACTOR"))
            write_structure_factor(infile, outfile);
       else if (!strcmp(token,"PUBLICATION"))
            write_publication_question(infile, outfile);
       else if (!strcmp(token, ".1.close"))
            output_close_contact_to_letter('a', outfile);
       else if (!strcmp(token, ".close"))
            output_close_contact_to_letter('s', outfile);
       else if (!strcmp(token, ".cov-bond-rpt"))
            ndb_find_bond_differences(outfile);
       else if (!strcmp(token, ".cov-angle-rpt"))
            ndb_find_angle_differences(outfile);
}

void _VALIDATION::find_out_range_waters(FILE *letter)
{
       int i, num = 0, atomSerialNo = 0, WaterSerialNo = 0;
       char FieldInfo[MxField][MxLen];
       _ATOM **atom = NULL;

       if (_n_waters == 0 || _waters == NULL) {
            if (letter) fprintf(letter, "     none\n\n");
            return;
       }

       for (i = 0; i < _n_waters; i++) {
            atom = _molecules[0]->find_ndb_atom(_waters[i]->a_atomtyp,
                      _waters[i]->a_chnid, _waters[i]->a_resnam,
                      _waters[i]->a_resnum, "", num);
            if (!atom) continue;
    
            strcpy(FieldInfo[0], atom[0]->type());
            sprintf(FieldInfo[1], "%d", atom[0]->atnum());
            atomSerialNo = atom[0]->atnum() - 1;
            strcpy(FieldInfo[2], atom[0]->atmtype());
            strcpy(FieldInfo[3], atom[0]->alt_loc());
            strcpy(FieldInfo[4], atom[0]->restype());
            strcpy(FieldInfo[5], atom[0]->chnid());
            sprintf(FieldInfo[6], "%d", atom[0]->resnum());
            strcpy(FieldInfo[7], atom[0]->ins_code());
            sprintf(FieldInfo[8], "%.4f", atom[0]->orig().x);
            sprintf(FieldInfo[9], "%.4f", atom[0]->orig().y);
            sprintf(FieldInfo[10], "%.4f", atom[0]->orig().z);
            sprintf(FieldInfo[11], "%6.2f", atom[0]->occ());
            sprintf(FieldInfo[12], "%6.2f", atom[0]->t_fct());
            if (atom[0]->footnote() != -10000)
                 sprintf(FieldInfo[13], "%d", atom[0]->footnote());
            else strcpy(FieldInfo[13], "");
            strcpy(FieldInfo[14], atom[0]->not_in_asym());
            sprintf(FieldInfo[15], "%d", atom[0]->pdb_resnum());
            strcpy(FieldInfo[16], atom[0]->pdb_resnam());
            strcpy(FieldInfo[17], atom[0]->pdb_chnid());
            strcpy(FieldInfo[18], atom[0]->pdb_atmnam());
            sprintf(FieldInfo[19], "%d", atom[0]->pub_resnum());
            strcpy(FieldInfo[20], atom[0]->pub_resnam());
            strcpy(FieldInfo[21], atom[0]->pub_chnid());
            strcpy(FieldInfo[22], atom[0]->pub_atmnam());
            strcpy(FieldInfo[23], atom[0]->atom_type());
            print_atom_card(letter, HETAS_TOKEN-1, HETAS_TOKEN-1, atomSerialNo,
              WaterSerialNo, FieldInfo, NDB_FILE_FORMAT_PDB, atom[0]->align(), 0);
            delete [] atom;
       }
}

void _VALIDATION::move_out_range_waters(FILE *letter)
{
       int i, num = 0, atomSerialNo = 0, WaterSerialNo = 0;
       char FieldInfo[MxField][MxLen];
       COORD coord;
       _ATOM **atom = NULL;

       if (_n_moving_waters == 0 || _moving_waters == NULL) {
            if (letter) fprintf(letter, "     none\n\n");
            return;
       }

       for (i = 0; i < _n_moving_waters; i++) {
            atom = _molecules[0]->find_ndb_atom(_moving_waters[i]->a_atomtyp,
                      _moving_waters[i]->a_chnid, _moving_waters[i]->a_resnam,
                      _moving_waters[i]->a_resnum, "", num);
            if (!atom) continue;
    
            coord = atom[0]->orig();
            ndb_trans_coord_3by3(coord, _cell, NDB_TRANS_ORTHO_TO_FRAC);
            do_symmetry_operation(coord, coord, &(_cell->symops[_moving_waters[i]->sym]));
            coord.x += (float) _moving_waters[i]->transl[0];
            coord.y += (float) _moving_waters[i]->transl[1];
            coord.z += (float) _moving_waters[i]->transl[2];
            ndb_trans_coord_3by3(coord, _cell, NDB_TRANS_FRAC_TO_ORTHO);

            strcpy(FieldInfo[0], atom[0]->type());
            sprintf(FieldInfo[1], "%d", atom[0]->atnum());
            atomSerialNo = atom[0]->atnum() - 1;
            strcpy(FieldInfo[2], atom[0]->atmtype());
            strcpy(FieldInfo[3], atom[0]->alt_loc());
            strcpy(FieldInfo[4], atom[0]->restype());
            strcpy(FieldInfo[5], atom[0]->chnid());
            sprintf(FieldInfo[6], "%d", atom[0]->resnum());
            strcpy(FieldInfo[7], atom[0]->ins_code());
            sprintf(FieldInfo[8], "%.4f", coord.x);
            sprintf(FieldInfo[9], "%.4f", coord.y);
            sprintf(FieldInfo[10], "%.4f", coord.z);
            sprintf(FieldInfo[11], "%6.2f", atom[0]->occ());
            sprintf(FieldInfo[12], "%6.2f", atom[0]->t_fct());
            if (atom[0]->footnote() != -10000)
                 sprintf(FieldInfo[13], "%d", atom[0]->footnote());
            else strcpy(FieldInfo[13], "");
            strcpy(FieldInfo[14], atom[0]->not_in_asym());
            sprintf(FieldInfo[15], "%d", atom[0]->pdb_resnum());
            strcpy(FieldInfo[16], atom[0]->pdb_resnam());
            strcpy(FieldInfo[17], atom[0]->pdb_chnid());
            strcpy(FieldInfo[18], atom[0]->pdb_atmnam());
            sprintf(FieldInfo[19], "%d", atom[0]->pub_resnum());
            strcpy(FieldInfo[20], atom[0]->pub_resnam());
            strcpy(FieldInfo[21], atom[0]->pub_chnid());
            strcpy(FieldInfo[22], atom[0]->pub_atmnam());
            strcpy(FieldInfo[23], atom[0]->atom_type());
            print_atom_card(letter, HETAS_TOKEN-1, HETAS_TOKEN-1, atomSerialNo,
              WaterSerialNo, FieldInfo, NDB_FILE_FORMAT_PDB, atom[0]->align(), 0);
            delete [] atom;
       }
}

void _VALIDATION::output_close_contact_to_letter(const char type, FILE *letter)
{
       int i, count;
       if (type == 'a') {
            if (_n_a_contact && _a_contact) { 
                 count = 0;
                 for (i = 0; i < _n_a_contact; i++) {
                      if (find_a_link(_a_contact[i])) count++;
                 }
                 if (count < _n_a_contact) {
                      fprintf(letter, "   Chain Atom    Res  Seq   Chain Atom    Res  Seq");
                      if (_experiment_type == EXPERIMENT_TYPE_NMR)
                           fprintf(letter, "   Mol_ID            Distance\n");
                      else fprintf(letter, "   Symm_Code         Distance\n");
                      fprintf(letter, "   -----------------------------------------");
                      fprintf(letter, "--------------------------------\n");
                      output_close_contact(_a_contact, _n_a_contact, 1, letter);
                 } else fprintf(letter, "      none\n\n");
            } else fprintf(letter, "      none\n\n");
       } else if (type == 's') {
            if (_n_s_contact && _s_contact) {
                 fprintf(letter, "   Chain Atom    Res  Seq   Chain Atom    Res  Seq");
                 fprintf(letter, "   Symm_Code         Distance\n");
                 fprintf(letter, "   -----------------------------------------");
                 fprintf(letter, "--------------------------------\n");
                 output_close_contact(_s_contact, _n_s_contact, 0, letter);
            } else fprintf(letter, "      none\n\n");
       }
}

void _VALIDATION::output_close_contact(CONTACT **contact, const int ncontact,
            const int skip, FILE *outfile)
{
       int num = 0, ret = 1, i;
       char atomName_a[5], atomName_b[5], alt_a[4], alt_b[4];
       BTreeObj<_DIndex> _Index;
       _DIndex _idx;
       _ATOM **atom_a = NULL, **atom_b = NULL;

       for (i = 0; i < ncontact; i++) {
            if (skip && find_a_link(contact[i])) continue;
            _idx.set_value(contact[i]->dist);
            _idx.set_pos(i);
            _Index.Add(_idx);
       }
       if (_Index.Root() < 0) return;

       _Index.GoFirst();
       while (ret >= 0) {
            _idx = _Index.GetCurrData();
            i = _idx.pos();
            atom_a = _molecules[0]->find_ndb_atom(contact[i]->a_atomtyp,
                      contact[i]->a_chnid, contact[i]->a_resnam,
                      contact[i]->a_resnum, "", num);
            atom_b = _molecules[0]->find_ndb_atom(contact[i]->b_atomtyp,
                      contact[i]->b_chnid, contact[i]->b_resnam,
                      contact[i]->b_resnum, "", num);
            if (!atom_a || !atom_b) {
                 if (atom_a) delete [] atom_a;
                 if (atom_b) delete [] atom_b;
                 ret = _Index.GoToNext();
                 continue;
            }
            strcpy(alt_a, "   ");
            if (contact[i]->a_alt_loc != '\0') sprintf(alt_a, "(%c)", contact[i]->a_alt_loc);
            strcpy(alt_b, "   ");
            if (contact[i]->b_alt_loc != '\0') sprintf(alt_b, "(%c)", contact[i]->b_alt_loc);

            print_atom_atomName_field(atom_a[0]->atom_type(), 0, atomName_a,
               atom_a[0]->pdb_atmnam(), atom_a[0]->pdb_resnam(), atom_a[0]->align());
            print_atom_atomName_field(atom_b[0]->atom_type(), 0, atomName_b,
               atom_b[0]->pdb_atmnam(), atom_b[0]->pdb_resnam(), atom_b[0]->align());

            fprintf(outfile, "   %5s %s%s %3s %4d - ", atom_a[0]->pdb_chnid(),
                atomName_a, alt_a, atom_a[0]->pdb_resnam(), atom_a[0]->pdb_resnum());
            fprintf(outfile, "%5s %s%s %3s %4d", atom_b[0]->pdb_chnid(),
                atomName_b, alt_b, atom_b[0]->pdb_resnam(), atom_b[0]->pdb_resnum());
            if (_experiment_type == EXPERIMENT_TYPE_NMR)
                 fprintf(outfile, "    %5d            Dist = %.2lf\n",
                     contact[i]->Mol_ID, contact[i]->dist);
            else fprintf(outfile, "  ( %2d, %2d, %2d, %2d)  Dist = %.2lf\n",
                     contact[i]->sym, contact[i]->transl[0]+5,
                     contact[i]->transl[1]+5, contact[i]->transl[2]+5,
                     contact[i]->dist);
            _Error_Check[0]++;
            if (atom_a) delete [] atom_a;
            if (atom_b) delete [] atom_b;

            ret = _Index.GoToNext();
       }
}

void _VALIDATION::ndb_find_bond_differences(FILE *fp)
{
       int first = 1, i = 0, j = 0, len;
       double hi = 0, low = 0, d = 0, range = 0, d2 = 0.0, rmsbond = 0.0;
       char buffer[20], chnid[4], Fst_Atom[5], Snd_Atom[5], *p = NULL;

       for (i = 0; i < _n_bond; i++) {
            d = _bond[i]->val - _bond[i]->ept;
            d2 += d * d;
       }
       if (_n_bond) rmsbond = sqrt ((d2) / (double) _n_bond);

       fprintf(fp, "\nThe RMS deviation for covalent bonds relative to the standard \n");
       fprintf(fp, "dictionary is %7.3f Angstroms\n", rmsbond);

       range =  6.0 * rmsbond;
       for (i = 0; i < _n_bond; i++) {
            hi  = _bond[i]->ept + range;
            low = _bond[i]->ept - range;
            if (_bond[i]->val < low || _bond[i]->val > hi) {
                 d = _bond[i]->val - _bond[i]->ept;
                 if (first) {
                      first = 0;
                      fprintf(fp, "\n\nThe following table contains a list ");
                      fprintf(fp, "of the covalent bonds\n");
                      fprintf(fp, "greater than 6.0*RMSD.\n\n\n");
                      // if (_bond[i]->Mol_ID > 0)
                      if (_num_mol > 1)
                           fprintf(fp, " Deviation  Residue  Chain  Sequence  Model  ");
                      else fprintf(fp, " Deviation  Residue  Chain  Sequence  ");
                      fprintf(fp, "AT1  -  AT2    Bond    Dictionary\n");
                      fprintf(fp, "             Name     ID     Number   ");
                      fprintf(fp, "              Distance    Value\n");
                      fprintf(fp, "--------------------------------------");
                      fprintf(fp, "----------------------------------\n");
                 }

                 if (strcmp(_bond[i]->ChainID, ""))
                      strcpy(chnid, _bond[i]->ChainID);
                 else strcpy(chnid, " ");
                 strcpy(buffer, _bond[i]->type);
                 len = strlen(buffer);
                 for (j = 0; j < len; j++) {
                      if (buffer[j] == '-') buffer[j] = ' ';
                 }
                 p = get_word(buffer, Fst_Atom);
                 p = get_word(p, Snd_Atom);

                 // if (_bond[i]->Mol_ID > 0) 
                 if (_num_mol > 1)
                      fprintf(fp, " %7.3f    %4s        %s   %4d      %3d   ",
                           d, _bond[i]->ResName, chnid, _bond[i]->ResNum, _bond[i]->Mol_ID);
                 else fprintf(fp, " %7.3f    %4s        %s   %4d      ",
                           d, _bond[i]->ResName, chnid, _bond[i]->ResNum);
                 fprintf(fp, "%-4s -  %-4s %7.3f   %7.3f\n",
                           Fst_Atom, Snd_Atom, _bond[i]->val, _bond[i]->ept);
                 _Error_Check[1]++;
            }
       }

       if (first) {
            fprintf(fp, "\nAll covalent bonds lie within a 6.0*RMSD range about the \n");
            fprintf(fp, "standard dictionary values.\n");
       }
}

void _VALIDATION::ndb_find_angle_differences(FILE *fp)
{
       int first = 1, i = 0, j = 0, len;
       double hi = 0, low = 0, d = 0, d2 = 0.0, rmsangle = 0.0, range = 0;
       char buffer[20], chnid[4], Fst_Atom[5], Snd_Atom[5], Trd_Atom[5], *p = NULL;

       for (i = 0; i < _n_angle; i++) {
            d = _angle[i]->val - _angle[i]->ept;
            d2 += d * d;
       }
       if (_n_angle) rmsangle = sqrt ((d2) / (double) _n_angle);

       fprintf(fp, "\nThe RMS deviation for covalent angles relative to the standard \n");
       fprintf(fp, "dictionary is %6.1f degrees.\n",rmsangle);

       range = 6.0 * rmsangle;
       for (i = 0; i < _n_angle; i++) {
            hi  = _angle[i]->ept + range;
            low = _angle[i]->ept - range;
            if (_angle[i]->val < low || _angle[i]->val > hi) {
                 d = _angle[i]->val - _angle[i]->ept;
                 if (first) {
                      first = 0;
                      fprintf(fp, "\nThe following table contains a list ");
                      fprintf(fp, "of the covalent bond angles\n");
                      fprintf(fp, "greater than 6.0*RMSD.\n\n\n");
                      // if (_angle[i]->Mol_ID > 0) {
                      if (_num_mol > 1) {
                           fprintf(fp, " Deviation  Residue  Chain  Sequence  Model  ");
                           fprintf(fp, "AT1  -  AT2  -  AT3    Bond    Dictionary\n");
                           fprintf(fp, "             Name     ID     Number   ");
                           fprintf(fp, "                              Angle      Value\n");
                           fprintf(fp, "---------------------------------------");
                           fprintf(fp, "-----------------------------------------\n");
                      } else {
                           fprintf(fp, " Deviation  Residue  Chain  Sequence  ");
                           fprintf(fp, "AT1  -  AT2  -  AT3    Bond    Dictionary\n");
                           fprintf(fp, "             Name     ID     Number   ");
                           fprintf(fp, "                       Angle      Value\n");
                           fprintf(fp, "---------------------------------------");
                           fprintf(fp, "-----------------------------------------\n");
                      }
                 }

                 if (strcmp(_angle[i]->ChainID, ""))
                      strcpy(chnid, _angle[i]->ChainID);
                 else strcpy(chnid, " ");
                 strcpy(buffer, _angle[i]->type);
                 len = strlen(buffer);
                 for (j = 0; j < len; j++) {
                      if (buffer[j] == '-') buffer[j] = ' ';
                 }
                 p = get_word(buffer, Fst_Atom);
                 p = get_word(p, Snd_Atom);
                 p = get_word(p, Trd_Atom);

                 // if (_angle[i]->Mol_ID > 0) 
                 if (_num_mol > 1)
                      fprintf(fp, " %7.1f   %4s       %s     %4d       %3d   ",
                           d, _angle[i]->ResName, chnid, _angle[i]->ResNum, _angle[i]->Mol_ID);
                 else fprintf(fp, " %7.1f   %4s       %s     %4d      ",
                           d, _angle[i]->ResName, chnid, _angle[i]->ResNum);
                 fprintf(fp, "%-4s -  %-4s -  %-4s %7.1f   %7.1f\n",
                           Fst_Atom, Snd_Atom, Trd_Atom, _angle[i]->val, _angle[i]->ept);
                 _Error_Check[2]++;
            }
       }

       if (first) {
            fprintf(fp, "\n\nAll covalent bond angles lie within a 6.0*RMSD range about the \n");
            fprintf(fp, "standard dictionary values.\n");
       }
}

void _VALIDATION::write_structure_factor(FILE *infile, FILE *outfile) 
{
       int foundFlag = FALSE, ret, i, len;
       char line[MxLen], token[MxLen];
       One_Card_Info_Format *pCard = _CardInfo[RECVD1_TOKEN-1].Head();
       while (pCard) {
            if (!strcmp(pCard->Field(5), "Y")) break;
            pCard = pCard->Next();
       }
       if (!pCard)  {
            passing_missing_words(FALSE, infile, "STRUCTURE FACTOR");
            return;
       } else {
            while (!feof(infile)) {
                 fgets(line,MxLen,infile);
                 len = strlen(line);
                 for (i = 0; i < len; i++)  {
                      ret = find_letter_token(&line[i], token);
                      if (ret == FALSE) fprintf(outfile, "%c", line[i]);
                      else {
                           i += ret;
                           if (strcmp(token, "STRUCTURE FACTOR")) 
                                write_letter_token(infile, outfile, token);
                           else {
                                foundFlag = TRUE; break;
                           }
                      }
                 }
                 if (foundFlag) break;
            }
       }
}

void _VALIDATION::write_publication_question(FILE *infile, FILE *outfile) 
{
       int i, ret, ifFlag = FALSE, len;
       char tmp_string[MxLen], line[MxLen], token[MxLen];
       One_Card_Info_Format *pCard = NULL;

       for (i = 0; i < MxJrnlTokens; i++)
            if (!strcmp(JrnlToken[i].TokenName, "REF")) break;
       pCard = _JrnlCardInfo[i].Head();
       if (pCard && !strcmp(pCard->Field(1), "")) {
            strcpy(tmp_string, pCard->Field(4));
            ndb_set_string_to_upper(tmp_string);
            if (!strncmp(tmp_string, "TO BE PUBLISHED", 15))
                 ifFlag = TRUE;
       } else ifFlag = TRUE;
     
       if (!ifFlag) passing_missing_words(FALSE, infile, "else");
       while (!feof(infile)) {
            fgets(line, MxLen, infile);
            len = strlen(line);
            for (i = 0; i < len; i++)  {
                 ret = find_letter_token(&line[i], token);
                 if (ret == FALSE) fprintf(outfile, "%c", line[i]);
                 else {
                      i += ret;
                      if (strcmp(token, "PUBLICATION") && strcmp(token, "else"))
                           write_letter_token(infile, outfile, token);
                      else break;
                 }
            }
            if (i != len) break;
       }
       if (ifFlag) passing_missing_words(FALSE, infile, "PUBLICATION");
}

void _VALIDATION::ndb_write_letter_misplace_atoms(const int flag, FILE *infile,
            FILE *outfile, const char *token)
{
       int first = TRUE, i = 0, j, first_residue = 0, pos = 0, need_hydrogen = 0;
       char Chain_ID[5], Mol_ID[4], insert_code[2], buff[10], *p = NULL;
       _CHAIN *chain = NULL;
       _RESIDUE *residue = NULL;
       One_Card_Info_Format *pCard = NULL;

       if (flag == NDB_FIND_MISSING_RESIDUE) {
            pCard = _CardInfo[MISRES_TOKEN-1].Head();
            if (pCard) {
                 ndb_writing_missing_words(infile, outfile);
                 first = FALSE;
            }
            while (pCard) {
                 strcpy(Chain_ID, " ");
                 strcpy(Mol_ID, "   ");
                 strcpy(insert_code, " ");
                 if (strcmp(pCard->Field(2), "")) strcpy(Mol_ID, pCard->Field(2));
                 if (strcmp(pCard->Field(3), "")) strcpy(Chain_ID, pCard->Field(3));
                 if (strcmp(pCard->Field(6), "")) strcpy(insert_code, pCard->Field(6));
                 fprintf(outfile, " %7s(%3s %s%4s%c)\n", pCard->Field(4), Mol_ID,
                              Chain_ID, pCard->Field(5), insert_code[0]);
                 pCard = pCard->Next();
            }
       } else {
            if (_experiment_type & EXPERIMENT_TYPE_NMR) need_hydrogen = 1;
            for (i = 0; i < _num_mol; i++) {
                 // if (i) break;
                 chain = _molecules[i]->GetFirstChain();
                 while (chain) {
                      if (flag == NDB_FIND_EXTRA_ATOM && need_hydrogen &&
                          chain->chain_type() == ATOMP_TOKEN &&
                          !chain->SeqRes(0)->Deleted) {
                           residue = chain->SeqRes(0)->Residue;
                           if (residue) {
                                for (j = 0; j < _n_link; j++) {
                                     if (_link[j]->FstIndex == chain->index() &&
                                         _link[j]->FstRes == 0 &&
                                         !strcmp(_link[j]->FstAtom, "N") ||
                                         _link[j]->SndIndex == chain->index() &&
                                         _link[j]->SndRes == 0 &&
                                         !strcmp(_link[j]->SndAtom, "N"))
                                          break;
                                }
                                if (j == _n_link) residue->find_extra_H_atom();
                           }
                      }
                      first_residue = 0;
                      residue = chain->GetFirstResidue();
                      while (residue) {
                           if (flag == NDB_FIND_MISSING_ATOM)
                                residue->find_missing_or_extra_atoms(chain->chain_type(),
                                   !first_residue, need_hydrogen);
                           first_residue = 1;

                           strcpy(Chain_ID, " ");
                           if (strcmp(chain->PDB_ChainID(), ""))
                                strcpy(Chain_ID, chain->PDB_ChainID());

                           if (flag == NDB_FIND_MISSING_ATOM)
                                p = residue->missing().Text();
                           else if (flag == NDB_FIND_EXTRA_ATOM)
                                p = residue->extras().Text();
                           if (p && strcmp(p, "")) {
                                if (flag == NDB_FIND_EXTRA_ATOM) _Error_Check[21]++;
                                ndb_clean_string(p);
                       	        if (first) {
                                     ndb_writing_missing_words(infile, outfile);
                                     first = FALSE;
                                }
                                if (_num_mol > 1)
                                     fprintf(outfile, " %7s(%3d %c%4d)        ",
                                         residue->ResName(), _molecules[i]->Mol_ID(),
                                         // Chain_ID[0], residue->pdb_res_no());
                                         Chain_ID[0], residue->GetFirstAtom()->pdb_resnum());
                                else fprintf(outfile, " %7s(    %c%4d)        ",
                                         residue->ResName(), Chain_ID[0],
                                         // residue->pdb_res_no());
                                         residue->GetFirstAtom()->pdb_resnum());
                                pos = 27;
                                while (p) {
                                     p = get_word(p, buff);
                                     pos += 5;
                                     if (pos > 81) {
                                          fprintf(outfile,
                                              "\n                           ");
                                          pos = 27;
                                     }
                                     fprintf(outfile, "%4s ", buff);
                                }
                                fprintf(outfile, "\n");
                           }
                           residue = chain->GetNextResidue();
                      }
                      chain = _molecules[i]->GetNextChain();
                 }
            }
       }
       if (first) passing_missing_words(FALSE, infile, token);

       if (flag == NDB_FIND_MISSING_RESIDUE) {
            fputc('\n', outfile);
            FILE *fp = fopen("validation.alignment", "r");
            if (fp) {
                  while (!feof(fp)) {
                       char c = fgetc(fp);
                       if (feof(fp)) break;
                       fputc(c, outfile);
                  }
                  fclose (fp);
            }
       }
}

void _VALIDATION::check_link_records(FILE *fp)
{
       int first = 1, found = 0, i = 0, a, b, num_a = 0, num_b = 0;
       char chnid1[5], chnid2[5], loc1[5], loc2[5];
       _ATOM **atom_a = NULL, **atom_b = NULL;
       _CHAIN *ch1 = NULL, *ch2 = NULL;
       _FIELD *Init = NULL, *End = NULL;
       _MOLECULE *mol = NULL;
       _RESIDUE *beg = NULL, *end = NULL;
       float dist = 0;

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

       mol = _molecules[0];
       for (i = 0; i < _n_link; i++) {
            ch1 = mol->GetIndexChain(_link[i]->FstIndex);
            ch2 = mol->GetIndexChain(_link[i]->SndIndex);
            if (!ch1 || !ch2) continue;
            Init = ch1->SeqResIndex(_link[i]->FstRes);
            End  = ch2->SeqResIndex(_link[i]->SndRes);
            if (!Init || !End) continue;
            beg = Init->Residue;
            end = End->Residue;
            if (!beg || !end) continue;

            found = 0;
            atom_a = beg->find_atom(_link[i]->FstAtom, num_a);
            atom_b = end->find_atom(_link[i]->SndAtom, num_b);
            if (atom_a && atom_b) {
                 found = 1;
                 for (a = 0; a < num_a; a++) {
                      if (strcmp(atom_a[a]->alt_loc(), _link[i]->altLoc1)) continue;
                      for (b = 0; b < num_b; b++) {
                           if (strcmp(atom_b[b]->alt_loc(), _link[i]->altLoc2)) continue;
                           found = 2;
                           dist = cal_distance(atom_a[a], atom_b[b]);
                           if (dist > 2.2) {
                                _Error_Check[20]++;
                                if (first) {
                                     fprintf(fp, "\n    CHECK 'LINK' RECORDS\n");
                                     fprintf(fp, "    --------------------\n\n");
                                     first = 0;
                                }
                                fprintf(fp, "The distance %.6f between '%s %s %s %d %s'",
                                      dist, atom_a[a]->atmtype(), atom_a[a]->pdb_resnam(),
                                      atom_a[a]->pdb_chnid(), atom_a[a]->pdb_resnum(),
                                      atom_a[a]->ins_code());
                                fprintf(fp, " and '%s %s %s %d %s' is larger than 2.2 Angstroms\n",
                                      atom_b[b]->atmtype(), atom_b[b]->pdb_resnam(),
                                      atom_b[b]->pdb_chnid(), atom_b[b]->pdb_resnum(),
                                      atom_b[b]->ins_code());
                           }
                      }
                 }
            }
            if (atom_a) delete [] atom_a;
            if (atom_b) delete [] atom_b;
            if (!found) {
                 _Error_Check[36]++;
                 if (first) {
                      fprintf(fp, "\n    CHECK 'LINK' RECORDS\n");
                      fprintf(fp, "    --------------------\n\n");
                      first = 0;
                 }
                 strcpy(chnid1, " ");
                 if (strcmp(ch1->PDB_ChainID(), "")) strcpy(chnid1, ch1->PDB_ChainID());
                 strcpy(chnid2, " ");
                 if (strcmp(ch2->PDB_ChainID(), "")) strcpy(chnid2, ch2->PDB_ChainID());
                 strcpy(loc1, " ");
                 if (strcmp(_link[i]->altLoc1, "")) strcpy(loc1, _link[i]->altLoc1);
                 strcpy(loc2, " ");
                 if (strcmp(_link[i]->altLoc2, "")) strcpy(loc2, _link[i]->altLoc2);
                 fprintf(fp, "Incorrect LINK record between (%s %d %s %s %s) --- (%s %d %s %s %s)\n",
                     beg->ResName(), beg->pdb_res_no(), chnid1, _link[i]->FstAtom, loc1,
                     end->ResName(), end->pdb_res_no(), chnid2, _link[i]->SndAtom, loc2);
            } else if (found == 1) {
                 _Error_Check[37]++;
                 if (first) {
                      fprintf(fp, "\n    CHECK 'LINK' RECORDS\n");
                      fprintf(fp, "    --------------------\n\n");
                      first = 0;
                 }
                 strcpy(chnid1, " ");
                 if (strcmp(ch1->PDB_ChainID(), "")) strcpy(chnid1, ch1->PDB_ChainID());
                 strcpy(chnid2, " ");
                 if (strcmp(ch2->PDB_ChainID(), "")) strcpy(chnid2, ch2->PDB_ChainID());
                 strcpy(loc1, " ");
                 if (strcmp(_link[i]->altLoc1, "")) strcpy(loc1, _link[i]->altLoc1);
                 strcpy(loc2, " ");
                 if (strcmp(_link[i]->altLoc2, "")) strcpy(loc2, _link[i]->altLoc2);
                 fprintf(fp, "Missing alternate conformation ID for LINK record between ");
                 fprintf(fp, "          (%s %d %s %s %s) --- (%s %d %s %s %s)\n",
                     beg->ResName(), beg->pdb_res_no(), chnid1, _link[i]->FstAtom, loc1,
                     end->ResName(), end->pdb_res_no(), chnid2, _link[i]->SndAtom, loc2);
            }
       }
}

void _VALIDATION::check_terminal_atoms(CifString &message)
{
       static int num_aa = 5, num_na = 3;
       static const char *aa[] = { "OXT", "HXT", "1H", "2H", "3H" };
       static const char *na[] = { "O3P", "3HOP", "H3T" };
       int first = 1, l = 0, j = 0, k = 0;
       char buffer[100];
       _CHAIN *chain = NULL;
       _RESIDUE *residue = NULL;
       _ATOM *atom = NULL;

       message.Clear();
       for (l = 0; l < _num_mol; l++) {
            chain = _molecules[l]->GetFirstChain();
            while (chain) {
                 if (chain->chain_type() != ATOMP_TOKEN &&
                     chain->chain_type() != ATOMN_TOKEN) {
                      chain = _molecules[l]->GetNextChain();
                      continue;
                 }
                 for (j = 1; j < chain->SeqLen() - 1; j++) {
                      if (chain->SeqRes(j)->Deleted) continue;
                      residue = chain->SeqRes(j)->Residue;
                      if (!residue) continue;
                      if (chain->chain_type() == ATOMP_TOKEN) {
                           for (k = 0; k < num_aa; k++) {
                                atom = residue->find_atom(aa[k]);
                                if (atom) {
                                     if (first) {
/*
                                          fprintf(fp, "\n    CHECK TERMINAL ATOMS\n");
                                          fprintf(fp, "    --------------------\n\n");
                                          fprintf(fp, "Terminal atom(s) showed in");
                                          fprintf(fp, " middle of sequence will be deleted:\n\n");
*/
                                          message += "\n    CHECK TERMINAL ATOMS\n";
                                          message += "    --------------------\n\n";
                                          message += "Terminal atom(s) showed in";
                                          message += " middle of sequence will be deleted:\n\n";
                                          first = 0;
                                     }
/*
                                     fprintf(fp, "%s %s %d%s %s\n", atom->atmtype(),
                                             atom->pdb_resnam(), atom->pdb_resnum(),
                                             atom->ins_code(), atom->pdb_chnid());
*/
                                     sprintf(buffer, "%s %s %d%s %s\n", atom->atmtype(),
                                             atom->pdb_resnam(), atom->pdb_resnum(),
                                             atom->ins_code(), atom->pdb_chnid());
                                     message += buffer;
                                     _Error_Check[3]++;
                                }
                           }
                      } else if (chain->chain_type() == ATOMN_TOKEN) {
                           for (k = 0; k < num_na; k++) {
                                atom = residue->find_atom(na[k]);
                                if (atom) {
                                     if (first) {
/*
                                          fprintf(fp, "\n    CHECK TERMINAL ATOMS\n");
                                          fprintf(fp, "    --------------------\n\n");
                                          fprintf(fp, "Terminal atom(s) showed in");
                                          fprintf(fp, " middle of sequence will be deleted:\n\n");
*/
                                          message += "\n    CHECK TERMINAL ATOMS\n";
                                          message += "    --------------------\n\n";
                                          message += "Terminal atom(s) showed in";
                                          message += " middle of sequence will be deleted:\n\n";
                                          first = 0;
                                     }
/*
                                     fprintf(fp, "%s %s %d%s %s\n", atom->atmtype(),
                                             atom->pdb_resnam(), atom->pdb_resnum(),
                                             atom->ins_code(), atom->pdb_chnid());
*/
                                     sprintf(buffer, "%s %s %d%s %s\n", atom->atmtype(),
                                             atom->pdb_resnam(), atom->pdb_resnum(),
                                             atom->ins_code(), atom->pdb_chnid());
                                     message += buffer;
                                     _Error_Check[3]++;
                                }
                           }
                      }
                 }
                 chain = _molecules[l]->GetNextChain();
            }
       }
}

static int find_letter_token(char *line, char* token)
{
       int i ,len;
       if (line == NULL || token == NULL) return FALSE;

       strcpy(token, "");
       if (strncmp(line, "$$@", 3)) return FALSE;
       else {
            len = strlen(line);
            for (i = 4; i < len; i++)
                 if (!strncmp("@$$", &line[i], 3)) break;
            if (i == len) return FALSE;
            else {
                 strncpy(token, &line[3], i-3);
                 token[i-3] = 0;
                 return (i + 2);
            }
       }
}

void ndb_writing_missing_words(FILE *infile, FILE *outfile)
{
       char line[MxLen], token[MxStrLen];
       int ret = FALSE, i, len;
       do {
            if (feof(infile)) break;
            fgets(line, MxLen, infile);
            len = strlen(line);
            for (i = 0; i < len; i++)  {
                 ret = find_letter_token(&line[i], token);
                 if (ret == FALSE) fprintf(outfile, "%c", line[i]);
                 else break;
            }
       } while (ret == FALSE);
}

static void passing_missing_words(const int missing, FILE *infile, const char *oldtoken)
{
       char line[MxLen], token[MxStrLen];
       int i, ret = FALSE, len;
     
       if (missing == FALSE) {
            do {
                 if (feof(infile)) break;
                 fgets(line,MxLen,infile);
                 len = strlen(line);
                 for (i = 0; i < len; i++)  {
                      ret = find_letter_token(&line[i], token);
                      if (ret != FALSE && !strcmp(token, oldtoken)) 
                           break;
                 }
            } while (ret == FALSE);
       }
}

