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

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

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

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

1. LICENSE AGREEMENT

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

2. LICENSE GRANT

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

2. COPYRIGHT; RETENTION OF RIGHTS.  

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

3. NO MAINTENANCE OR SUPPORT; TREATMENT OF ENHANCEMENTS 

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

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

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

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

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

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

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

static void write_text_part(FILE *fp, ATLAS_TEXT *text, const int is_prev_check,
              const int experiment_type);
static void get_citation_val(CifString &buff, One_Card_Info_Format *Head,
              const int serial_no, const int field_no);
static int get_multiple_rows(One_Card_Info_Format *Head, const int field_no,
        const int serial_no, const int value, CifString &res);
static void add_superscripts(char *modifier_st, char *buff, const int isindex);
static void correct_string(char *string);
static REFN *get_refn(CifString &authors, CifString &title, CifString &jrnl,
         CifString &volume, CifString &first_page, CifString &last_page,
         CifString &year);
static CRYS *get_crys(CifString &method, CifString &drop,
           CifString &reservoir, CifString &soaking);

void _VALIDATION::ndb_write_atlas_entries(char *File_ID, const int is_prev_check)
{
       char fname[160];
       char small_sid[160];

       strcpy(small_sid, _StructureId);
       ndb_clean_string(small_sid);
       lowercased(small_sid);

       char pdb_id[20];
       pdb_id[0] = '\0';
       if (_CardInfo[PDBFIL_TOKEN-1].Head() &&
           strcmp(_CardInfo[PDBFIL_TOKEN-1].Head()->Field(1), ""))
            strcpy(pdb_id, _CardInfo[PDBFIL_TOKEN-1].Head()->Field(1));

       ATLAS_TEXT *atlas_text = get_atlas_text(_StructureId, pdb_id);

       sprintf(fname, "%s.html", File_ID);
       FILE *fp_entry = fopen(fname, "w");
       sprintf(fname, "RCSB Atlas Entry for Structure %s", small_sid);
       html_atlas_preamble(fp_entry, fname);
       
       write_text_part(fp_entry, atlas_text, is_prev_check, _experiment_type);
       // html_atlas_trailer(fp_entry);
       fclose(fp_entry);

       delete [] atlas_text->struct_features;
       delete [] atlas_text->compound_name;
       for (int i = 0; i < atlas_text->Num_seqs; i++) delete [] atlas_text->seqs[i];
       delete [] atlas_text->seqs;
       if (atlas_text->refn) {
            if (atlas_text->refn->author) delete [] atlas_text->refn->author;
            if (atlas_text->refn->title) delete [] atlas_text->refn->title;
            if (atlas_text->refn->refn) delete [] atlas_text->refn->refn;
            delete atlas_text->refn;
       }
       if (atlas_text->crys) {
            if (atlas_text->crys->method) delete [] atlas_text->crys->method;
            if (atlas_text->crys->drop) delete [] atlas_text->crys->drop;
            if (atlas_text->crys->reservoir) delete [] atlas_text->crys->reservoir;
            if (atlas_text->crys->soaking) delete [] atlas_text->crys->soaking;
            delete atlas_text->crys;
       }
       delete [] atlas_text->refinement;
       delete atlas_text;
}

ATLAS_TEXT* _VALIDATION::get_atlas_text(const char *sid, const char *pdb_id)
{
       int len, i, j, commas, index, jrnl_id, name_index, Serial_No;
       char buffer[BIGSTRING], *stmpt = NULL;
       CifString buff, tmp_buff, authors, title, jrnl, volume, first_page, year;
       CifString last_page, program, rvalue, reflections, high, low, sigmaF;
       FILE *fp = NULL;
       One_Card_Info_Format *pJrnlCard = NULL;
       ISTable *Table = NULL;

       ATLAS_TEXT *atlas_text = new ATLAS_TEXT;
       atlas_text->struct_features = NULL;
       atlas_text->compound_name = NULL;
       atlas_text->Num_seqs = 0;
       atlas_text->isComplex = 0;
       atlas_text->seqs = NULL;
       atlas_text->refn = NULL;
       atlas_text->crys = NULL;
       atlas_text->refinement = NULL;
       atlas_text->struct_id[0] = '\0';
       atlas_text->spacegroup[0] = '\0';
       atlas_text->cell[0] = '\0';

       if (pdb_id[0] != '\0')
            sprintf(atlas_text->struct_id, "RCSB ID: %s    PDB ID: %s", sid, pdb_id);
       else sprintf(atlas_text->struct_id, "RCSB ID: %s", sid);
       get_classification_st(buff, atlas_text->isComplex);
       if (buff != "") {
            atlas_text->struct_features = new char[strlen(buff.Text())+1];
            strcpy(atlas_text->struct_features, buff.Text());
       }

       get_name_st(buff, tmp_buff);
       if (buff != "") {
            if (tmp_buff != "") {
                 len = strlen(buff.Text()) + strlen(tmp_buff.Text()) + 20;
                 atlas_text->compound_name = new char[len];
                 commas = get_ncommas(tmp_buff.Text());
                 sprintf(atlas_text->compound_name, "%s\n<br>\nModifier%s: %s\n",
                           buff.Text(), commas ? "s" : "", tmp_buff.Text());
            } else {
                 len = strlen(buff.Text()) + 5;
                 atlas_text->compound_name = new char[len];
                 sprintf(atlas_text->compound_name, "%s\n", buff.Text());
            }
       }
 
       if (_Num_Seqs) {
            fp = fopen("SEQUENCE.DAT", "w");
            atlas_text->Num_seqs = _Num_Seqs;
            atlas_text->seqs = new char*[_Num_Seqs];
            for (i = 0; i < _Num_Seqs; i++) {
                 buff.Copy("Chain ");
                 buff += _Seqs[i]->ChainId;
                 buff += ": ";
                 tmp_buff.Copy(_Seqs[i]->ChainId);
                 tmp_buff += " ";
                 len = strlen(buff.Text());
                 for (j = 0; j < _Seqs[i]->SeqLen; j++) {
                      stmpt = get_oneletter_code(_Seqs[i]->res[j]->name);
                      if (strlen(_Seqs[i]->res[j]->name) == 3 && strlen(stmpt) == 1)
                           tmp_buff += stmpt;
                      if (len >= 54) {
                           if (strlen(stmpt) == 1) {
                                buff += stmpt;
                                buff += "<br>\n";
                           } else {
                                buff += "(";
                                buff += stmpt;
                                buff += ")<br>\n";
                           }
                           len = 0;
                      } else {
                           if (strlen(stmpt) == 1)
                                buff += stmpt;
                           else {
                                buff += "(";
                                buff += stmpt;
                                buff += ")";
                           }
                           len += strlen(stmpt);
                      }
                 }
                 if (strlen(tmp_buff.Text()) > 4) fprintf(fp, "%s\n", tmp_buff.Text());
                 atlas_text->seqs[i] = new char[strlen(buff.Text())+1];
                 strcpy(atlas_text->seqs[i], buff.Text());
            }
            fclose (fp);
       }
 
       jrnl_id = find_jrnl_id("TITL");
       pJrnlCard = _JrnlCardInfo[jrnl_id].Head();
       Serial_No = 0;
       while (pJrnlCard) {
            if (strcmp(pJrnlCard->Field(4), "")) {
                 Serial_No = atoi(pJrnlCard->Field(1));
                 break;
            }
            pJrnlCard = pJrnlCard->Next();
       }

       authors.Clear(); title.Clear(); jrnl.Clear(); volume.Clear();
       first_page.Clear(); last_page.Clear(); year.Clear();
       if (pJrnlCard) {
            jrnl_id = find_jrnl_id("AUTH");
            get_citation_val(authors, _JrnlCardInfo[jrnl_id].Head(), Serial_No, 5);
            jrnl_id = find_jrnl_id("TITL");
            get_citation_val(title, _JrnlCardInfo[jrnl_id].Head(), Serial_No, 5);
            jrnl_id = find_jrnl_id("REF");
            get_citation_val(jrnl, _JrnlCardInfo[jrnl_id].Head(), Serial_No, 5);
            get_citation_val(volume, _JrnlCardInfo[jrnl_id].Head(), Serial_No, 7);
            get_citation_val(first_page, _JrnlCardInfo[jrnl_id].Head(), Serial_No, 8);
            get_citation_val(last_page, _JrnlCardInfo[jrnl_id].Head(), Serial_No, 10);
            get_citation_val(year, _JrnlCardInfo[jrnl_id].Head(), Serial_No, 9);
       } else if (_input_format == NDB_FILE_FORMAT_MIX ||
           _input_format == NDB_FILE_FORMAT_MMCIF) {
            Table = _CifObj->GetTablePtr(_StructureId, "citation");
            if (!is_empty_table(Table)) {
                 jrnl_id = Table->GetColumnIndex("title");
                 get_value(title, Table, jrnl_id, 0);
                 jrnl_id = Table->GetColumnIndex("journal_abbrev");
                 get_value(jrnl, Table, jrnl_id, 0);
                 jrnl_id = Table->GetColumnIndex("journal_volume");
                 get_value(volume, Table, jrnl_id, 0);
                 jrnl_id = Table->GetColumnIndex("page_first");
                 get_value(first_page, Table, jrnl_id, 0);
                 jrnl_id = Table->GetColumnIndex("page_last");
                 get_value(last_page, Table, jrnl_id, 0);
                 jrnl_id = Table->GetColumnIndex("year");
                 get_value(year, Table, jrnl_id, 0);

                 jrnl_id = Table->GetColumnIndex("id");
                 get_value(tmp_buff, Table, jrnl_id, 0);

                 authors.Clear();
                 Table = _CifObj->GetTablePtr(_StructureId, "citation_author");
                 if (!is_empty_table(Table)) {
                      name_index = Table->GetColumnIndex("name");
                      jrnl_id = Table->GetColumnIndex("citation_id");
                      len = Table->GetNumRows();
                      for (i = 0; i < len; i++) {
                           Table->GetCell(buff, jrnl_id, i);
                           if (buff != tmp_buff) continue;
                           get_value(buff, Table, name_index, i);
                           if (buff == "") continue;
                           strcpy(buffer, buff.Text());
                           ndb_name_conversion_first_last(buffer);
                           if (authors != "") authors += ", ";
                           authors += buffer;
                      }
                 }
            }
       }
       atlas_text->refn = get_refn(authors, title, jrnl, volume, first_page, last_page, year);

       if (_cell && !_cell->is_artifical) {
            strcpy(buffer, _cell->space_group);
            if (buffer[0] != '\0') strcpy(atlas_text->spacegroup, map_space_group(buffer));
            sprintf(atlas_text->cell,
                "<pre>\n%6s = %7.2lf %6s = %7.2lf %6s = %7.2lf (&Aring;ngstroms)\n",
                "A", _cell->a, "B", _cell->b, "C", _cell->c);
            int len = strlen(atlas_text->cell);
            sprintf(&atlas_text->cell[len],
                "%6s = %7.2lf %6s = %7.2lf %6s = %7.2lf (degrees)\n</pre>\n",
                "alpha", _cell->alpha, "beta", _cell->beta, "gamma", _cell->gamma);
       }

       authors.Clear(); title.Clear(); jrnl.Clear(); volume.Clear();
       if (_CardInfo[CRMETH_TOKEN-1].Head() || _CardInfo[CRSOLU_TOKEN-1].Head()) {
            if (_CardInfo[CRMETH_TOKEN-1].Head() &&
                strcmp(_CardInfo[CRMETH_TOKEN-1].Head()->Field(2), "")) {
                 sprintf(buffer, "METHOD: %s", _CardInfo[CRMETH_TOKEN-1].Head()->Field(2));
                 ndb_set_string_to_mixed(buffer);
                 authors.Copy(buffer);
            }
  
            if (_CardInfo[CRSOLU_TOKEN-1].Head()) {
                 get_multiple_rows(_CardInfo[CRSOLU_TOKEN-1].Head(), 4, 3, 1, title);
                 get_multiple_rows(_CardInfo[CRSOLU_TOKEN-1].Head(), 4, 3, 2, jrnl);
                 get_multiple_rows(_CardInfo[CRSOLU_TOKEN-1].Head(), 4, 3, 3, volume);
            }
       } else if (_input_format == NDB_FILE_FORMAT_MIX ||
                  _input_format == NDB_FILE_FORMAT_MMCIF) {
            Table = _CifObj->GetTablePtr(_StructureId, "exptl_crystal_grow");
            if (!is_empty_table(Table)) {
                 index = Table->GetColumnIndex("method");
                 get_value(authors, Table, index, 0);
                 if (authors != "") {
                      sprintf(buffer, "METHOD: %s", authors.Text());
                      ndb_set_string_to_mixed(buffer);
                      authors.Copy(buffer);
                 }
            }
            Table = _CifObj->GetTablePtr(_StructureId, "exptl_crystal_grow_comp");
            if (!is_empty_table(Table)) {
                 index = Table->GetColumnIndex("sol_id");
                 name_index = Table->GetColumnIndex("name");
                 len = Table->GetNumRows();
                 for (i = 0; i < len; i++) {
                      get_value(buff, Table, index, i);
                      get_value(tmp_buff, Table, name_index, i);
                      if (tmp_buff != "") {
                           tmp_buff.ToLower();
                           strcpy(buffer, tmp_buff.Text());
                           map_solution_case(buffer);
                           if (buff == "1") {
                                title += buffer;
                                title += ", ";
                           } else if (buff == "2") {
                                jrnl += buffer;
                                jrnl += ", ";
                           } else if (buff == "3") {
                                volume += buffer;
                                volume += ", ";
                           }
                      }
                 }
                 if (title != "") {
                      strcpy(buffer, title.Text());
                      correct_string(buffer);
                      title.Copy(buffer);
                 }
                 if (jrnl != "") {
                      strcpy(buffer, jrnl.Text());
                      correct_string(buffer);
                      jrnl.Copy(buffer);
                 }
                 if (volume != "") {
                      strcpy(buffer, volume.Text());
                      correct_string(buffer);
                      volume.Copy(buffer);
                 }
            }
       }
       atlas_text->crys = get_crys(authors, title, jrnl, volume);

       if (!(_experiment_type & EXPERIMENT_TYPE_NMR)) {
            program.Clear(); rvalue.Clear(); reflections.Clear();
            high.Clear(); low.Clear(); sigmaF.Clear();
            if (_input_format == NDB_FILE_FORMAT_MIX ||
                _input_format == NDB_FILE_FORMAT_MMCIF) {
                 Table = _CifObj->GetTablePtr(_StructureId, "refine");
                 if (!is_empty_table(Table)) {
                      index = Table->GetColumnIndex("ls_R_factor_obs");
                      get_value(rvalue, Table, index, 0);
                      if (rvalue == "") {
                           index = Table->GetColumnIndex("ls_R_factor_R_work");
                           get_value(rvalue, Table, index, 0);
                      }
                      if (rvalue == "") {
                           index = Table->GetColumnIndex("ls_R_factor_all");
                           get_value(rvalue, Table, index, 0);
                      }
                      if (rvalue != "") {
                           float r = atof(rvalue.Text());
                           sprintf(buffer, "%.3f", r * 100.0);
                           rvalue.Copy(buffer);
                      }

                      index = Table->GetColumnIndex("ls_number_reflns_obs");
                      get_value(reflections, Table, index, 0);

                      index = Table->GetColumnIndex("ls_d_res_low");
                      get_value(low, Table, index, 0);

                      index = Table->GetColumnIndex("ls_d_res_high");
                      get_value(high, Table, index, 0);

                      index = Table->GetColumnIndex("ndb_ls_sigma_F");
                      get_value(sigmaF, Table, index, 0);
                 }
     
                 Table = _CifObj->GetTablePtr(_StructureId, "computing");
                 if (!is_empty_table(Table)) {
                      index = Table->GetColumnIndex("structure_refinement");
                      get_value(program, Table, index, 0);
                 }
            } else {
                 if (_CardInfo[REFMET_TOKEN-1].Head() && 
                     strcmp(_CardInfo[REFMET_TOKEN-1].Head()->Field(3), "")) 
                      program.Copy(_CardInfo[REFMET_TOKEN-1].Head()->Field(3));

                 if (_CardInfo[RFACTR_TOKEN-1].Head()) {
                      if (strcmp(_CardInfo[RFACTR_TOKEN-1].Head()->Field(7), ""))
                           rvalue.Copy(_CardInfo[RFACTR_TOKEN-1].Head()->Field(7));
                      else if (strcmp(_CardInfo[RFACTR_TOKEN-1].Head()->Field(10), ""))
                           rvalue.Copy(_CardInfo[RFACTR_TOKEN-1].Head()->Field(10));
                      else if (strcmp(_CardInfo[RFACTR_TOKEN-1].Head()->Field(8), ""))
                           rvalue.Copy(_CardInfo[RFACTR_TOKEN-1].Head()->Field(8));

                      if (strcmp(_CardInfo[RFACTR_TOKEN-1].Head()->Field(2), ""))
                           reflections.Copy(_CardInfo[RFACTR_TOKEN-1].Head()->Field(2));

                      if (strcmp(_CardInfo[RFACTR_TOKEN-1].Head()->Field(5), ""))
                           low.Copy(_CardInfo[RFACTR_TOKEN-1].Head()->Field(5));

                      if (strcmp(_CardInfo[RFACTR_TOKEN-1].Head()->Field(6), ""))
                           high.Copy(_CardInfo[RFACTR_TOKEN-1].Head()->Field(6));

                      if (strcmp(_CardInfo[RFACTR_TOKEN-1].Head()->Field(4), ""))
                           sigmaF.Copy(_CardInfo[RFACTR_TOKEN-1].Head()->Field(4));
                 }
            }
            buff.Clear();
            if (program != "") {
                 buff += "The structure was refined using the ";
                 buff += program;
                 buff += " program. ";
            }
            len = 0;
            if (rvalue != "") {
                 buff += "The R value is ";
                 buff += rvalue;
                 len = 1;
            }
            if (reflections != "") {
                 buff += " for ";
                 buff += reflections;
                 buff += " reflections";
                 len = 1;
            }
            if (low != "" && high != "") {
                 if (len) buff += "\n";
                 buff += " in the resolution range ";
                 buff += low;
                 buff += " to ";
                 buff += high;
                 buff += " &Aring;";
                 len = 1;
            } else if (high != "") {
                 if (len) buff += "\n";
                 buff += "to a resolution of ";
                 buff += high;
                 buff += " &Aring;";
                 len = 1;
            }
            if (sigmaF != "") {
                 buff += " with Fobs > ";
                 buff += sigmaF;
                 buff += " sigma (Fobs)";
                 len = 1;
            }
            if (len) buff += ".";
            if (buff != "") {
                 atlas_text->refinement = new char[strlen(buff.Text())+1];
                 strcpy(atlas_text->refinement, buff.Text());
            }
       }

       return atlas_text;
}

void _VALIDATION::get_name_st(CifString &name, CifString &modifier_st)
{
       int  i, j, hit = 0, drugsYN, modifiedYN, index, rowNo, STRUCT_TOKEN;
       char st1[25], ch, st2[25], buff[BIGSTRING], *stpt = NULL;
       char conformation_type[BIGSTRING], buffer[BIGSTRING];
       CifString cifstring;
       ISTable *Table = NULL;
 
       name.Clear();
       modifier_st.Clear();
       memset(buff, '\0', BIGSTRING);
       memset(buffer, '\0', BIGSTRING);
       memset(conformation_type, '\0', BIGSTRING);

       STRUCT_TOKEN = find_card_id("STRUCT");
       if (_CardInfo[STRUCT_TOKEN].Head())
            strcpy(conformation_type, _CardInfo[STRUCT_TOKEN].Head()->Field(1));
       else if (_input_format == NDB_FILE_FORMAT_MIX ||
                _input_format == NDB_FILE_FORMAT_MMCIF) {
            Table = _CifObj->GetTablePtr(_StructureId, "ndb_na_struct_keywds");
            if (!is_empty_table(Table)) {
                 index = Table->GetColumnIndex("conformation_type");
                 get_value(cifstring, Table, index, 0);
                 if (cifstring != "") strcpy(conformation_type, cifstring.Text());
            }
       }

       drugsYN = (_CardInfo[DCHEM_TOKEN-1].Head() != NULL);
       if (_input_format == NDB_FILE_FORMAT_MIX ||
           _input_format == NDB_FILE_FORMAT_MMCIF) {
           Table = _CifObj->GetTablePtr(_StructureId, "ndb_drug_info");
           if (!is_empty_table(Table)) drugsYN = 1;
       }

       buff[0] = '\0';
       if (_CardInfo[COMPND_TOKEN-1].Head() && 
           strcmp(_CardInfo[COMPND_TOKEN-1].Head()->Field(2), "")) {
            strcpy(buff, _CardInfo[COMPND_TOKEN-1].Head()->Field(2));
       }
       modifiedYN = 0;
       if (_CardInfo[MODIFB_TOKEN-1].Head() ||
           _CardInfo[MODIFP_TOKEN-1].Head() ||
           _CardInfo[MODIFS_TOKEN-1].Head()) modifiedYN = 1;
       else if (_input_format == NDB_FILE_FORMAT_MIX ||
                _input_format == NDB_FILE_FORMAT_MMCIF) {
            Table = _CifObj->GetTablePtr(_StructureId, "struct_conn_type");
            if (!is_empty_table(Table)) {
                 index = Table->GetColumnIndex("id");
                 rowNo = Table->GetNumRows();
                 for (i = 0; i < rowNo; i++) {
                      Table->GetCell(cifstring, index, i);
                      if (!strcasecmp(cifstring.Text(), "covale_base") ||
                          !strcasecmp(cifstring.Text(), "covale_sugar") ||
                          !strcasecmp(cifstring.Text(), "covale_phosphate")) {
                           modifiedYN = 1; break;
                      }
                 }
            }
       }

       if (strcmp(buff, "")) {
            if (!strncmp(buff, "5'-", 3)) {
                 lowercased((char *) buff);
                 if (modifiedYN || drugsYN) {
                      add_superscripts(buffer, buff, 0);
                      modifier_st.Copy(buffer);
                 }
                 repl_subst(buff, "A",  "*a");
                 repl_subst(buff, "G",  "*g");
                 repl_subst(buff, "C",  "*c");
                 repl_subst(buff, "T",  "*t");
                 repl_subst(buff, "U",  "*u");
                 repl_subst(buff, "I",  "*i");
                 repl_subst(buff, "+A",  "+a");
                 repl_subst(buff, "+G",  "+g");
                 repl_subst(buff, "+C",  "+c");
                 repl_subst(buff, "+T",  "+t");
                 repl_subst(buff, "+U",  "+u");
                 repl_subst(buff, "+I",  "+i");
                 repl_subst(buff, ")A",  ")a");
                 repl_subst(buff, ")G",  ")g");
                 repl_subst(buff, ")C",  ")c");
                 repl_subst(buff, ")T",  ")t");
                 repl_subst(buff, ")U",  ")u");
                 repl_subst(buff, ")I",  ")I");
                 repl_subst(buff, "", "*");     
                 map_descriptor_case(buff);
            }
  
            strcpy(st1, "0k");
            strcpy(st2, "0K");
            for (ch = '0'; (!hit && (ch <= '9')); ch++) {
                 st1[0] = ch;
                 st2[0] = ch;
                 hit = repl_subst(buff, st2, st1);
            }

            strcpy(st1, "0 k,");
            strcpy(st2, "0K");
            for (ch = '0';  (!hit && (ch <= '9')); ch++) {
                 st1[0] = ch;
                 st2[0] = ch;
                 hit = repl_subst(buff, st2, st1);
            }
  
            strcpy(st1, "0 k");
            strcpy(st2, "0K");
            for (ch = '0';  (!hit && (ch <= '9')); ch++) {
                 st1[0] = ch;
                 st2[0] = ch;
                 hit = repl_subst_last(buff, st2, st1);
            }
          
            strcpy(st1, "0c");
            strcpy(st2, "0C");
            for (ch = '0'; (!hit && (ch <= '9')); ch++) {
                 st1[0] = ch;
                 st2[0] = ch;
                 hit = repl_subst(buff, st2, st1);
            }

            strcpy(st1, "0 c,");
            strcpy(st2, "0C");
            for (ch = '0'; (!hit && (ch <= '9')); ch++) {
                 st1[0] = ch;
                 st2[0] = ch;
                 hit = repl_subst(buff, st2, st1);
            }

            strcpy(st1, "0 c,");
            strcpy(st2, "0C");
            for (ch = '0'; (!hit && (ch <= '9')); ch++) {
                 st1[0] = ch;
                 st2[0] = ch;
                 hit = repl_subst_last(buff, st2, st1);
            }
  
            i = 0;
            for (stpt = buff; *stpt != '\0'; stpt++) {    
                 if (strncmp(buff, "5'-", 3) || strncmp(conformation_type, "P", 1)) {
                      if (isalpha(stpt[0]) && isdigit(stpt[1])) {
                           j = i;
                           while ((j > 0) && isalpha(buff[j])) {
                                buff[j] = toupper(buff[j]);
                                j--;
                           }
                      }
                 }
           
                 if (((stpt[0] == ' ') || (stpt[0] == ',') || (stpt[0] == '(')) && 
                    (isalpha(stpt[1])) && ((stpt[2] == '\0') || (stpt[2] == '-') || 
                     (stpt[2] == ' ') || (stpt[2] ==')'))) stpt[1] = toupper(stpt[1]);
                 else if ((stpt[0] == 'n') && (stpt[1] == ',') && 
                          (stpt[2] == 'n') && !(isalpha(stpt[3]))) {
                      stpt[0] = 'N';
                      stpt[2] = 'N';
                 }
                 i++;
            }
  
            repl_subst(buff, "DNA",  "dna");
            repl_subst(buff, "RNA",  "rna");
            repl_subst(buff, "(pH ",  "(ph ");
            repl_subst(buff, "( pH ",  " ph ");
            repl_subst(buff, "Hoechst",  "hoechst");
            repl_subst(buff, "(II)",  "(ii)");
            repl_subst(buff, "(III)",  "(iii)");
            repl_subst(buff, "-O-","-o-");
            repl_subst(buff, " HCHO",  " hcho");
            repl_subst(buff, "N-","n-");
            if (drugsYN) {
              repl_subst(buff, "actinomycin D", "actinomycin d");  
              repl_subst(buff, "triostin A", "triostin a");  
              repl_subst(buff, "distamycin A", "distamycin a");
            }
       }
       name.Copy(buff);
}

void _VALIDATION::get_classification_st(CifString &Classification, int& isComplex)
{
       int drugsYN = 0, mismatch_YN = 0, modified_YN = 0, i, index, rowNo;
       int STRUCT_TOKEN, STRKEY_TOKEN;
       char helix_type[BIGSTRING], classification[BIGSTRING];
       char conformation_type[BIGSTRING], tmp_buff[BIGSTRING];
       static char buff[BIGSTRING];
       CifString cifstring;
       ISTable *Table = NULL;

       isComplex = 0;
       memset(buff, '\0', BIGSTRING);
       memset(tmp_buff, '\0', BIGSTRING);
       memset(helix_type, '\0', BIGSTRING);
       memset(classification, '\0', BIGSTRING);
       memset(conformation_type, '\0', BIGSTRING);

       if (_input_format == NDB_FILE_FORMAT_MIX ||
                _input_format == NDB_FILE_FORMAT_MMCIF) {
            Table = _CifObj->GetTablePtr(_StructureId, "struct_conn_type");
            if (!is_empty_table(Table)) {
                 index = Table->GetColumnIndex("id");
                 rowNo = Table->GetNumRows();
                 for (i = 0; i < rowNo; i++) {
                      Table->GetCell(cifstring, index, i);
                      if (!strcasecmp(cifstring.Text(), "covale_base") ||
                          !strcasecmp(cifstring.Text(), "covale_sugar") ||
                          !strcasecmp(cifstring.Text(), "covale_phosphate")) {
                           modified_YN = 1;
                      } else if (!strcasecmp(cifstring.Text(), "mismat"))
                           mismatch_YN = 1;
                 }
            }
            Table = _CifObj->GetTablePtr(_StructureId, "ndb_na_struct_keywds");
            if (!is_empty_table(Table)) {
                 index = Table->GetColumnIndex("conformation_type");
                 get_value(cifstring, Table, index, 0);
                 strcpy(conformation_type, cifstring.Text());
                 index = Table->GetColumnIndex("strand_description");
                 get_value(cifstring, Table, index, 0);
                 strcpy(helix_type, cifstring.Text());
            }
            Table = _CifObj->GetTablePtr(_StructureId, "struct_keywords");
            if (!is_empty_table(Table)) {
                 index = Table->GetColumnIndex("ndb_keywords");
                 get_value(cifstring, Table, index, 0);
                 strcpy(classification, cifstring.Text());
            }
       } else {
            drugsYN = (_CardInfo[DCHEM_TOKEN-1].Head() != NULL);
            mismatch_YN = (_CardInfo[MISMAT_TOKEN-1].Head() != NULL);
            modified_YN = (_CardInfo[MODIFB_TOKEN-1].Head() != NULL || 
                           _CardInfo[MODIFP_TOKEN-1].Head() != NULL ||
                           _CardInfo[MODIFS_TOKEN-1].Head() != NULL);
            STRUCT_TOKEN = find_card_id("STRUCT");
            if (_CardInfo[STRUCT_TOKEN].Head()) {
                 strcpy(conformation_type, _CardInfo[STRUCT_TOKEN].Head()->Field(1));
                 strcpy(helix_type, _CardInfo[STRUCT_TOKEN].Head()->Field(2));
            }
            if (_CardInfo[HEADER_TOKEN-1].Head())
                 strcpy(classification, _CardInfo[HEADER_TOKEN-1].Head()->Field(1));
       }
       ndb_set_string_to_upper(conformation_type);
       
  
       if (!strncmp("A", conformation_type, 1) || !strncmp("B", conformation_type, 1) ||
   	   !strncmp("Z", conformation_type, 1)) {
   	    strcat(buff, conformation_type);
   	    strcat(buff, "-");
       } else if (!strncmp("RH", conformation_type, 2)) {
   	    strcat(buff, (strlen(buff)) ? " right handed" : " Right handed ");
       } else if (!strncmp("U", conformation_type, 1)) {
   	    strcat(buff, (strlen(buff) == 0) ? "Unusual " :  "unusual ");
       }
  
       if ((!strncmp("DNA/RNA", classification, 7)) ||
           (!strncmp("DEOXYRIBONUCLEIC ACID/RIBONUCLEIC ACID", classification, 38)))
	    strcat(buff, "Form nucleic acid hybrid");
       else if (strstr(classification, "COMPLEX") &&
                strstr(classification, "DNA")) strcat(buff, "DNA");
       else if (strstr(classification, "COMPLEX") &&
                strstr(classification, "RNA")) strcat(buff, "RNA");
       else if (!strcmp(classification, "DNA")) strcat(buff, "DNA");
       else if (!strcmp(classification, "RNA")) strcat(buff, "RNA");
       else strcat(buff, "");

       if (strstr(classification, "COMPLEX") &&
          (strstr(classification, "DNA") &&
           strcmp(classification, "DNA-BINDING PROTEIN") ||
           strstr(classification, "RNA") &&
           strcmp(classification, "RNA-BINDING PROTEIN"))) isComplex = 1;
  
       if (strcmp(helix_type, "")) {
            strcat(buff, " ");
            strcpy(tmp_buff, helix_type);
            lowercased(tmp_buff);
            strcat(buff, tmp_buff);
       }
  
       if (!strcmp("T", conformation_type)) strcpy(buff, "tRNA"); 
       else if (!strcmp("P", conformation_type)) strcpy(buff, "Protein-nucleic acid complex");
       else if (!strncmp("RIBONUCL", classification, 8) ||
   	        !strncmp("HIV-1RT", classification, 7)) strcpy(buff, "Ribonuclease"); 
       else if (!strncmp("KIN", classification, 3)) strcpy(buff, "Kinase"); 
  
       memset(tmp_buff, '\0', BIGSTRING);
       STRKEY_TOKEN = find_card_id("STRKEY");
       if (_input_format == NDB_FILE_FORMAT_MIX ||
                _input_format == NDB_FILE_FORMAT_MMCIF) {
            Table = _CifObj->GetTablePtr(_StructureId, "ndb_na_struct_keywds");
            if (!is_empty_table(Table)) {
                 index = Table->GetColumnIndex("special_feature");
                 get_value(cifstring, Table, index, 0);
                 if (cifstring != "") strcpy(tmp_buff, cifstring.Text());
            }
       } else if (_CardInfo[STRKEY_TOKEN].Head() &&
                strcmp(_CardInfo[STRKEY_TOKEN].Head()->Field(2), "")) {
            strcpy(tmp_buff, _CardInfo[STRKEY_TOKEN].Head()->Field(2));
       }

       if (strcmp(tmp_buff, "")) {
            strcat(buff, ", ");
            lowercased(tmp_buff);
            repl_subst(tmp_buff, " DNA",  " dna");
            repl_subst(tmp_buff, "-DNA",  "-dna");
            repl_subst(tmp_buff, "DNA-",  "-dna");
            repl_subst(tmp_buff, "/DNA",  "/dna");
            repl_subst(tmp_buff, "DNA/",  "/dna");
            repl_subst(tmp_buff, " RNA",  " rna");
            repl_subst(tmp_buff, "-RNA",  "-rna");
            repl_subst(tmp_buff, "RNA-",  "rna-");
            repl_subst(tmp_buff, "RNA/",  "rna/");
            repl_subst(tmp_buff, "/RNA",  "/rna");
            strcat(buff, tmp_buff);
       }
   
       if (modified_YN ) {
            if (strcmp(buff, "")) strcat(buff, ", modified");
            else strcpy(buff, "modified");
       }
       if (mismatch_YN ) {
            if (strcmp(buff, "")) strcat(buff, ", mismatch");
            else strcpy(buff, "mismatch");
       }
       if (drugsYN) {
            if (strcmp(buff, "")) strcat(buff, ", bound to drug");
            else strcpy(buff, "bound to drug");
       }
       Classification.Copy(buff);
}

static void write_text_part(FILE *fp, ATLAS_TEXT *text, const int is_prev_check,
              const int experiment_type)
{
       if (strcmp(text->struct_id, "")) atlas_head(fp, 1, text->struct_id);
       atlas_par(fp);
 
       if (text->struct_features && !is_prev_check) {
            if (text->isComplex) atlas_head(fp, 2, "Nucleic acid features");
            else                 atlas_head(fp, 2, "Features");
            atlas_par(fp); 
            atlas_line(fp, text->struct_features);
            atlas_par(fp);
       }
 
       if (text->compound_name && !is_prev_check) {
            atlas_head(fp, 2, "Compound name"); 
            atlas_line(fp, text->compound_name);
            atlas_par(fp);
       }

       if (text->Num_seqs) {
            if (experiment_type & EXPERIMENT_TYPE_NMR ||
                experiment_type & EXPERIMENT_TYPE_MODEL)
                 atlas_head(fp, 2, "Sequence");
            else atlas_head(fp, 2, "Sequence in asymmetric unit"); 
            atlas_begin(fp, "itemize");
            for (int i = 0; i < text->Num_seqs; i++)
                 atlas_item(fp, "", text->seqs[i]);
            atlas_end(fp, "itemize");
       }
 
       if (text->refn) {
            atlas_head(fp, 2, "Citation"); 
            if (text->refn->author) {
                 atlas_line(fp, text->refn->author);
                 atlas_line_break(fp);
            }
            if (text->refn->title) {
                 atlas_line(fp, text->refn->title);
                 atlas_line_break(fp);
            }
            if (text->refn->refn) atlas_line(fp, text->refn->refn);
            atlas_par(fp);
       }

       if (strcmp(text->spacegroup, "") &&
           !(experiment_type & EXPERIMENT_TYPE_NMR) &&
           !(experiment_type & EXPERIMENT_TYPE_MODEL)) {
            atlas_head(fp, 2, "Space group"); 
            atlas_line(fp, "\n");
            atlas_line(fp, text->spacegroup);
            atlas_line(fp, "\n");
            atlas_par(fp);
       }

       if (strcmp(text->cell, "") &&
           !(experiment_type & EXPERIMENT_TYPE_NMR) &&
           !(experiment_type & EXPERIMENT_TYPE_MODEL)) {
            atlas_head(fp, 2, "Cell constants");
            html_begin(fp, "pre");
            atlas_line(fp, text->cell);
            html_end(fp, "pre");
            atlas_par(fp);
       }

       if (text->crys &&
           !(experiment_type & EXPERIMENT_TYPE_NMR) &&
           !(experiment_type & EXPERIMENT_TYPE_MODEL)) {
            atlas_head(fp, 2, "Crystallization conditions"); 
            atlas_line(fp,"");
            atlas_line(fp,"");
            atlas_begin(fp,"itemize");
            if (text->crys->method)    atlas_item(fp, NULL, text->crys->method);
            if (text->crys->drop)      atlas_item(fp, NULL, text->crys->drop);
            if (text->crys->reservoir) atlas_item(fp, NULL, text->crys->reservoir);
            if (text->crys->soaking)   atlas_item(fp, NULL, text->crys->soaking);
            atlas_end(fp, "itemize");
            atlas_line(fp,"\n");
       }

       if (text->refinement && !(experiment_type & EXPERIMENT_TYPE_NMR)) {
            atlas_head(fp, 2, "Refinement");
            atlas_line(fp, "\n");
            atlas_line(fp, text->refinement);
            atlas_par(fp);
       }
       atlas_par(fp);
}

static void get_citation_val(CifString &buff, One_Card_Info_Format *Head,
         const int serial_no, const int field_no)
{
       One_Card_Info_Format *pJrnlCard = Head;

       buff.Clear();
       while (pJrnlCard) {
            if (atoi(pJrnlCard->Field(1)) == serial_no) break;
            pJrnlCard = pJrnlCard->Next();
       }
       if (pJrnlCard) buff.Copy(pJrnlCard->Field(field_no-1));
}

static int get_multiple_rows(One_Card_Info_Format *Head, const int field_no,
        const int serial_no, const int value, CifString &res)
{
       char buff[BIGSTRING];
       int first = 1, nrow = 0;

       memset(buff, 0, BIGSTRING);
       One_Card_Info_Format *pCard = Head;
       while (pCard) {
            strcpy(buff, pCard->Field(field_no));
            lowercased(buff);
            if (atoi(pCard->Field(serial_no)) == value) {
                 map_solution_case(buff);
            } else buff[0] = '\0';

            if (strcmp(buff, "")) {
                 if (first) first = 0;
                 else if (serial_no < 0 && pCard->Next() &&
                     pCard->Next()->Next() == NULL)
                      res += " and ";
                 else res += ", ";
                 res += buff;
            }
            nrow++;
            pCard = pCard->Next();
       }

       return nrow;
}

static void add_superscripts(char *modifier_st, char *buff, const int isindex) 
{
   const char *html_syms[11] = {"+", "^","++","^^","+", "^","++","^^","+", "^","++"};
   int  maxsyms = 11;
   int  nmods = 0;
   int  len, i, j; 
   int  found_mod = 0;
   int  at_5_prime = 0;
   char mod_substring[160];
   char old_st[160];
   char new_st[160];
   char buffer[BIGSTRING];
   char modifier_tmp[MxStrLen];
 
    strcpy(modifier_st, "");
    strcpy(buffer, buff);
    len = strlen(buff);
    for (i = 0; i < len; i++) {
        strcpy(modifier_tmp, "");
	if (!strncmp(buff + i, "5'-", 3)) 
	    if (at_5_prime) {
		ndb_log_message(NDB_MSG_DEBUG4, 
                     "Something's wrong, two consecutive 5'-.\n");
		ndb_log_message(NDB_MSG_DEBUG4, 
                     "String %s in add_superscripts.\n", buff);
		exit(1);
	    }
	    else at_5_prime = 1;
	else if (!strncmp(buff + i, "-3'", 3))
	    if (at_5_prime) 
		at_5_prime = 0;
   
	if (at_5_prime) {
	    if (buff[i+1] == '(') {
		if ((buff[i] == '*') || (buff[i] == '('))
		    found_mod = 1;
		else if (buff[i] == 'p')
		    found_mod = 2;
		else if (buff[i] == '-')
		    found_mod = 3;
    
		if (found_mod) {
		    i++;   
		    j = i; 
		    while ((j < len) && (buff[j] != ')')) j++;
		    if (j >= BIGSTRING) {
			ndb_log_message(NDB_MSG_DEBUG4, 
                   "String \"%s\" ended while searching for modifier end in ");
			ndb_log_message(NDB_MSG_DEBUG4, "add_superscripts.\n");
			exit(1);
		    }   
		    strncpy(mod_substring, buff + i + 1, j -i -1);
		    mod_substring[j -i -1] = '\0';
		    strcpy(old_st, "(");
		    strcat(old_st, mod_substring);
		    strcat(old_st, ")");
		    if ((found_mod == 1) || (found_mod == 3)) 
			strncat(old_st, buff + j + 1, 1);
    
		    if ((found_mod == 1) || (found_mod == 3)) {
			strncpy(new_st,   buff + j + 1, 1);
			new_st[1] = '\0';
			if (found_mod == 1)
			    new_st[0] = toupper(new_st[0]);
		    }
		    else strcpy(new_st, "");

		    if (isindex) { 
			strcat(new_st,"+");
			repl_subst_one(buffer, new_st, old_st);
		    }
		    else {
			if (nmods >= maxsyms) {
			    ndb_log_message(NDB_MSG_DEBUG4, 
                              "Error: too many modifiers in compound name.\n");
			    exit(1);
			}
			strcat(new_st,"<small>");
			strcat(new_st, html_syms[nmods]);
			strcat(new_st,"</small>");
			strcat(modifier_tmp, (nmods > 0) ? ", " : " ");
			strcat(modifier_tmp, "");	
			strcat(modifier_tmp, html_syms[nmods]);
			strcat(modifier_tmp, "");	
			strcat(modifier_tmp, " = ");
			strcat(modifier_tmp, replace_mod(mod_substring));
                        if (!strstr(modifier_st, modifier_tmp)) {
                             strcat(modifier_st, modifier_tmp);
                        }
		    }
		    found_mod = 0;
		    repl_subst_one(buffer, new_st, old_st);
		}
	    }
	}
    }
    strcpy(buff, buffer);
}

static void correct_string(char *string)
{
       int i, len;
       char *buffer = NULL;
       if (string[0] == '\0') return;

       len = strlen(string);
       buffer = new char[len + 20];
       for (i = len - 1; i >= 0; i--) {
            if (string[i] == ',') {
                 string[i] = '\0'; break;
            }
       }
       strcpy(buffer, string);
       len = strlen(string);
       for (i = len - 1; i >= 0; i--) {
            if (buffer[i] == ',') {
                 buffer[i] = '\0'; break;
            }
       }
       if (i > 0) {
            strcat(buffer, " and");
            strcat(buffer, &string[i+1]);
            strcpy(string, buffer);
       }
       delete [] buffer;
}

static REFN *get_refn(CifString &authors, CifString &title, CifString &jrnl,
         CifString &volume, CifString &first_page, CifString &last_page,
         CifString &year)
{
       int i, len;
       char *stmpt = NULL;
       CifString buff;

       REFN *refn = new REFN;
       refn->author = NULL;
       refn->title  = NULL;
       refn->refn   = NULL;

       if (authors != "") {
            stmpt = authors.Text();
            len = strlen(stmpt);
            buff.Clear();
            for (i = 0; i < len; i++) {
                 buff += stmpt[i];
                 if (stmpt[i] == ',' && (i + 1) < len && stmpt[i + 1] != ' ')
                      buff += " ";
                 else if (stmpt[i] == '.' && (i + 2) < len &&
                          stmpt[i + 1] != ' ' && stmpt[i + 2] != '.')
                      buff += " ";
            }
            refn->author = new char[strlen(buff.Text())+1];
            strcpy(refn->author, buff.Text());
       }

       if (title != "") {
            refn->title = new char[strlen(title.Text())+1];
            strcpy(refn->title, title.Text());
       }

       buff.Clear();
       if (jrnl != "" && strncasecmp(jrnl.Text(), "To Be Published", 15)) {
            stmpt = jrnl.Text();
            len = strlen(stmpt);
            i = 0;
            buff.Copy("<i>");
            while (i < len) {
                 buff += stmpt[i];
                 if (stmpt[i] == '.' && (i + 1) < len)
                      buff += " ";
                 i++;
            }
            buff += ",</i>\n";

            if (volume != "") {
                 buff += "<b>";
                 buff += volume;
                 buff += "</b>, ";
            }

            if (first_page != "") {
                 if (last_page != "") {
                      buff += "pp. ";
                      buff += first_page;
                      buff += "-";
                      buff += last_page;
                 } else {
                      buff += "p. ";
                      buff += first_page;
                 }
            }

            if (year != "") {
                 buff += ", ";
                 buff += year;
                 buff += ".";
            }
       } else buff.Copy("To Be Published.");

       refn->refn = new char[strlen(buff.Text())+1];
       strcpy(refn->refn, buff.Text());

       return refn;
}

static CRYS *get_crys(CifString &method, CifString &drop,
           CifString &reservoir, CifString &soaking)
{
       if (method == "" && drop == "" && reservoir == "" &&
           soaking == "") return NULL;

       CRYS *crys = new CRYS;
       crys->method    = NULL;
       crys->drop      = NULL;
       crys->reservoir = NULL;
       crys->soaking   = NULL;
       if (method != "") {
            crys->method = new char[strlen(method.Text())+1];
            strcpy(crys->method, method.Text());
       }
       if (drop != "") {
            crys->drop = new char[strlen(drop.Text())+7];
            sprintf(crys->drop, "Drop: %s", drop.Text());
       }
       if (reservoir != "") {
            crys->reservoir = new char[strlen(reservoir.Text())+12];
            sprintf(crys->reservoir, "Reservoir: %s", reservoir.Text());
       }
       if (soaking != "") {
            crys->soaking = new char[strlen(soaking.Text())+19];
            sprintf(crys->soaking, "Soaking solution: %s", soaking.Text());
       }

       return crys;
}
