File: data.cpp

package info (click to toggle)
openbabel 2.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 36,644 kB
  • ctags: 33,717
  • sloc: cpp: 242,528; ansic: 87,037; sh: 10,280; perl: 5,518; python: 5,156; pascal: 793; makefile: 747; cs: 392; xml: 97; ruby: 54; java: 23
file content (931 lines) | stat: -rw-r--r-- 23,759 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
/**********************************************************************
data.cpp - Global data and resource file parsers.
 
Copyright (C) 1998-2001 by OpenEye Scientific Software, Inc.
Some portions Copyright (C) 2001-2008 by Geoffrey R. Hutchison
 
This file is part of the Open Babel project.
For more information, see <http://openbabel.sourceforge.net/>
 
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
 
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
***********************************************************************/

#ifdef WIN32
#pragma warning (disable : 4786)
#endif

#include <openbabel/babelconfig.h>
#include <openbabel/data.h>
#include <openbabel/mol.h>
#include <openbabel/locale.h>

// data headers with default parameters
#include "element.h"
#include "types.h"
#include "isotope.h"
#include "resdata.h"


#if !HAVE_STRNCASECMP
extern "C" int strncasecmp(const char *s1, const char *s2, size_t n);
#endif

using namespace std;

namespace OpenBabel
{

  OBElementTable   etab;
  OBTypeTable      ttab;
  OBIsotopeTable   isotab;
  OBResidueData    resdat;

  /** \class OBElementTable data.h <openbabel/data.h>
      \brief Periodic Table of the Elements
 
      Translating element data is a common task given that many file
      formats give either element symbol or atomic number information, but
      not both. The OBElementTable class facilitates conversion between
      textual and numeric element information. An instance of the
      OBElementTable class (etab) is declared as external in data.cpp. Source
      files that include the header file mol.h automatically have an extern
      definition to etab. The following code sample demonstrates the use
      of the OBElementTable class:
      \code
      cout << "The symbol for element 6 is " << etab.GetSymbol(6) << endl;
      cout << "The atomic number for Sulfur is " << etab.GetAtomicNum(16) << endl;
      cout << "The van der Waal radius for Nitrogen is " << etab.GetVdwRad(7);
      \endcode
 
      Stored information in the OBElementTable includes elemental:
      - symbols
      - covalent radii
      - van der Waal radii
      - expected maximum bonding valence
      - molar mass (by IUPAC recommended atomic masses)
      - electronegativity (Pauling and Allred-Rochow)
      - ionization potential
      - electron affinity
      - RGB colors for visualization programs
      - names (by IUPAC recommendation)
  */

  OBElementTable::OBElementTable()
  {
    _init = false;
    _dir = BABEL_DATADIR;
    _envvar = "BABEL_DATADIR";
    _filename = "element.txt";
    _subdir = "data";
    _dataptr = ElementData;
  }

  OBElementTable::~OBElementTable()
  {
    vector<OBElement*>::iterator i;
    for (i = _element.begin();i != _element.end();++i)
      delete *i;
  }

  void OBElementTable::ParseLine(const char *buffer)
  {
    int num,maxbonds;
    char symbol[4];
    char name[256];
    double Rcov,Rvdw,mass, elNeg, ARENeg, ionize, elAffin;
    double red, green, blue;

    if (buffer[0] != '#') // skip comment line (at the top)
      {
        sscanf(buffer,"%d %4s %lf %lf %*f %lf %d %lf %lf %lf %lf %lf %lf %lf %255s",
               &num,
               symbol,
               &ARENeg,
               &Rcov,
               &Rvdw,
               &maxbonds,
               &mass,
               &elNeg,
               &ionize,
               &elAffin,
               &red,
               &green,
               &blue,
               name);

        OBElement *ele = new OBElement(num,symbol,ARENeg,Rcov,Rvdw,maxbonds,mass,elNeg,
                                       ionize, elAffin, red, green, blue, name);
        _element.push_back(ele);
      }
  }

  unsigned int OBElementTable::GetNumberOfElements()
  { 
    if (!_init)
      Init();
    
    return _element.size();
  }

  const char *OBElementTable::GetSymbol(int atomicnum)
  {
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return("\0");

    return(_element[atomicnum]->GetSymbol());
  }

  int OBElementTable::GetMaxBonds(int atomicnum)
  {
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return(0);

    return(_element[atomicnum]->GetMaxBonds());
  }

  double OBElementTable::GetElectroNeg(int atomicnum)
  {
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return(0.0);

    return(_element[atomicnum]->GetElectroNeg());
  }

  double OBElementTable::GetAllredRochowElectroNeg(int atomicnum)
  {
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return(0.0);

    return(_element[atomicnum]->GetAllredRochowElectroNeg());
  }


  double OBElementTable::GetIonization(int atomicnum)
  {
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return(0.0);

    return(_element[atomicnum]->GetIonization());
  }


  double OBElementTable::GetElectronAffinity(int atomicnum)
  {
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return(0.0);

    return(_element[atomicnum]->GetElectronAffinity());
  }
 
  vector<double> OBElementTable::GetRGB(int atomicnum)
  {
    if (!_init)
      Init();

    vector <double> colors;
    colors.reserve(3);
    
    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      {
        colors.push_back(0.0);
        colors.push_back(0.0);
        colors.push_back(0.0);
        return(colors);
      }

    colors.push_back(_element[atomicnum]->GetRed());
    colors.push_back(_element[atomicnum]->GetGreen());
    colors.push_back(_element[atomicnum]->GetBlue());

    return (colors);
  }
 
  string OBElementTable::GetName(int atomicnum)
  {
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return("Unknown");

    return(_element[atomicnum]->GetName());
  }

  double OBElementTable::GetVdwRad(int atomicnum)
  {
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return(0.0);

    return(_element[atomicnum]->GetVdwRad());
  }

  double OBElementTable::CorrectedBondRad(int atomicnum, int hyb)
  {
    double rad;
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return(1.0);

    rad = _element[atomicnum]->GetCovalentRad();

    if (hyb == 2)
      rad *= 0.95;
    else if (hyb == 1)
      rad *= 0.90;

    return(rad);
  }

  double OBElementTable::CorrectedVdwRad(int atomicnum, int hyb)
  {
    double rad;
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return(1.95);

    rad = _element[atomicnum]->GetVdwRad();

    if (hyb == 2)
      rad *= 0.95;
    else if (hyb == 1)
      rad *= 0.90;

    return(rad);
  }

  double OBElementTable::GetCovalentRad(int atomicnum)
  {
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return(0.0);

    return(_element[atomicnum]->GetCovalentRad());
  }

  double OBElementTable::GetMass(int atomicnum)
  {
    if (!_init)
      Init();

    if (atomicnum < 0 || atomicnum >= static_cast<int>(_element.size()))
      return(0.0);

    return(_element[atomicnum]->GetMass());
  }

  int OBElementTable::GetAtomicNum(const char *sym)
  {
    int temp;
    return GetAtomicNum(sym, temp);
  }

  int OBElementTable::GetAtomicNum(const char *sym, int &iso)
  {
    if (!_init)
      Init();

    vector<OBElement*>::iterator i;
    for (i = _element.begin();i != _element.end();++i)
      if (!strncasecmp(sym,(*i)->GetSymbol(),3))
        return((*i)->GetAtomicNum());
    if (strcasecmp(sym, "D") == 0)
      {
        iso = 2;
        return(1);
      }
    else if (strcasecmp(sym, "T") == 0)
      {
        iso = 3;
        return(1);
      }
    else
      iso = 0;
    return(0);
  }

  /** \class OBIsotopeTable data.h <openbabel/data.h>
      \brief Table of atomic isotope masses
  */

  OBIsotopeTable::OBIsotopeTable()
  {
    _init = false;
    _dir = BABEL_DATADIR;
    _envvar = "BABEL_DATADIR";
    _filename = "isotope.txt";
    _subdir = "data";
    _dataptr = IsotopeData;
  }

  void OBIsotopeTable::ParseLine(const char *buffer)
  {
    unsigned int atomicNum;
    unsigned int i;
    vector<string> vs;

    pair <unsigned int, double> entry;
    vector <pair <unsigned int, double> > row;

    if (buffer[0] != '#') // skip comment line (at the top)
      {
        tokenize(vs,buffer);
        if (vs.size() > 3) // atomic number, 0, most abundant mass (...)
          {
            atomicNum = atoi(vs[0].c_str());
            for (i = 1; i < vs.size() - 1; i += 2) // make sure i+1 still exists
              {
                entry.first = atoi(vs[i].c_str()); // isotope
                entry.second = atof(vs[i + 1].c_str()); // exact mass
                row.push_back(entry);
              }
            _isotopes.push_back(row);
          }
        else
          obErrorLog.ThrowError(__FUNCTION__, " Could not parse line in isotope table isotope.txt", obInfo);
      }
  }

  double        OBIsotopeTable::GetExactMass(const unsigned int ele,
                                             const unsigned int isotope)
  {
    if (!_init)
      Init();

    if (ele > _isotopes.size())
      return 0.0;

    unsigned int iso;
    for (iso = 0; iso < _isotopes[ele].size(); ++iso)
      if (isotope == _isotopes[ele][iso].first)
        return _isotopes[ele][iso].second;

    return 0.0;
  }

  /** \class OBTypeTable data.h <openbabel/data.h>
      \brief Atom Type Translation Table
 
      Molecular file formats frequently store information about atoms in an
      atom type field. Some formats store only the element for each atom,
      while others include hybridization and local environments, such as the
      Sybyl mol2 atom type field. The OBTypeTable class acts as a translation
      table to convert atom types between a number of different molecular
      file formats. The constructor for OBTypeTable automatically reads the
      text file types.txt. Just as OBElementTable, an instance of
      OBTypeTable (ttab) is declared external in data.cpp and is referenced as
      extern OBTypeTable ttab in mol.h.  The following code demonstrates how
      to use the OBTypeTable class to translate the internal representation
      of atom types in an OBMol Internal to Sybyl Mol2 atom types.
 
      \code
      ttab.SetFromType("INT");
      ttab.SetToType("SYB");
      OBAtom *atom;
      vector<OBAtom*>::iterator i;
      string src,dst;
      for (atom = mol.BeginAtom(i);atom;atom = mol.EndAtom(i))
      {
         src = atom->GetType();
         ttab.Translate(dst,src);
         cout << "atom number " << atom->GetIdx() << "has mol2 type " << dst << endl;
      }
      \endcode
 
      Current atom types include (defined in the top line of the data file types.txt):
      - INT (Open Babel internal codes)
      - ATN (atomic numbers)
      - HYB (hybridization)
      - MMD (MacroModel)
      - MM2 (MM2 force field)
      - XYZ (element symbols from XYZ file format)
      - ALC (Alchemy)
      - HAD (H added)
      - MCML (MacMolecule)
      - C3D (Chem3D)
      - SYB (Sybyl mol2)
      - MOL (Sybyl mol)
      - MAP (Gasteiger partial charge types)
      - DRE (Dreiding)
      - XED (XED format)
      - DOK (Dock)
      - M3D (Molecular Arts M3D)
      - IDX (Index -- i.e., line number in the file)
      - SBN (Sybyl descriptor types for MPD files)
      - PCM (PC Model)
  */

  OBTypeTable::OBTypeTable()
  {
    _init = false;
    _dir = BABEL_DATADIR;
    _envvar = "BABEL_DATADIR";
    _filename = "types.txt";
    _subdir = "data";
    _dataptr = TypesData;
    _linecount = 0;
    _from = _to = -1;
  }

  void OBTypeTable::ParseLine(const char *buffer)
  {
    if (buffer[0] == '#')
      return; // just a comment line

    if (_linecount == 0)
      sscanf(buffer,"%d%d",&_nrows,&_ncols);
    else if (_linecount == 1)
      tokenize(_colnames,buffer);
    else
      {
        vector<string> vc;
        tokenize(vc,buffer);
        if (vc.size() == (unsigned)_ncols)
          _table.push_back(vc);
        else
          {
            stringstream errorMsg;
            errorMsg << " Could not parse line in type translation table types.txt -- incorect number of columns";
            errorMsg << " found " << vc.size() << " expected " << _ncols << ".";
            obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obInfo);
          }
      }
    _linecount++;
  }

  bool OBTypeTable::SetFromType(const char* from)
  {
    if (!_init)
      Init();

    string tmp = from;

    unsigned int i;
    for (i = 0;i < _colnames.size();++i)
      if (tmp == _colnames[i])
        {
          _from = i;
          return(true);
        }

    obErrorLog.ThrowError(__FUNCTION__, "Requested type column not found", obInfo);

    return(false);
  }

  bool OBTypeTable::SetToType(const char* to)
  {
    if (!_init)
      Init();

    string tmp = to;

    unsigned int i;
    for (i = 0;i < _colnames.size();++i)
      if (tmp == _colnames[i])
        {
          _to = i;
          return(true);
        }

    obErrorLog.ThrowError(__FUNCTION__, "Requested type column not found", obInfo);

    return(false);
  }

  //! Translates atom types (to, from), checking for size of destination
  //!  string and null-terminating as needed
  //! \deprecated Because there is no guarantee on the length of an atom type
  //!  you should consider using std::string instead
  bool OBTypeTable::Translate(char *to, const char *from)
  {
    if (!_init)
      Init();

    bool rval;
    string sto,sfrom;
    sfrom = from;
    rval = Translate(sto,sfrom);
    strncpy(to,(char*)sto.c_str(), sizeof(to) - 1);
    to[sizeof(to) - 1] = '\0';

    return(rval);
  }

  bool OBTypeTable::Translate(string &to, const string &from)
  {
    if (!_init)
      Init();

    if (from == "")
      return(false);

    if (_from >= 0 && _to >= 0 &&
        _from < (signed)_table.size() && _to < (signed)_table.size())
      {
        vector<vector<string> >::iterator i;
        for (i = _table.begin();i != _table.end();++i)
          if ((signed)(*i).size() > _from &&  (*i)[_from] == from)
            {
              to = (*i)[_to];
              return(true);
            }
      }

    // Throw an error, copy the string and return false
    obErrorLog.ThrowError(__FUNCTION__, "Cannot perform atom type translation: table cannot find requested types.", obWarning);
    to = from;
    return(false);
  }

  std::string OBTypeTable::Translate(const string &from)
  {
    if (!_init)
      Init();

    if (from.empty())
      return("");

    if (_from >= 0 && _to >= 0 &&
        _from < (signed)_table.size() && _to < (signed)_table.size())
      {
        vector<vector<string> >::iterator i;
        for (i = _table.begin();i != _table.end();++i)
          if ((signed)(*i).size() > _from &&  (*i)[_from] == from)
            {
              return (*i)[_to];
            }
      }

    // Throw an error, copy the string and return false
    obErrorLog.ThrowError(__FUNCTION__, "Cannot perform atom type translation: table cannot find requested types.", obWarning);
    return("");
  }

  std::string OBTypeTable::GetFromType()
  {
    if (!_init)
      Init();

    if (_from > 0 && _from < (signed)_table.size())
      return( _colnames[_from] );
    else
      return( _colnames[0] );
  }

  std::string OBTypeTable::GetToType()
  {
    if (!_init)
      Init();

    if (_to > 0 && _to < (signed)_table.size())
      return( _colnames[_to] );
    else
      return( _colnames[0] );
  }

  void Toupper(string &s)
  {
    unsigned int i;
    for (i = 0;i < s.size();++i)
      s[i] = toupper(s[i]);
  }

  void Tolower(string &s)
  {
    unsigned int i;
    for (i = 0;i < s.size();++i)
      s[i] = tolower(s[i]);
  }

  ///////////////////////////////////////////////////////////////////////
  OBResidueData::OBResidueData()
  {
    _init = false;
    _dir = BABEL_DATADIR;
    _envvar = "BABEL_DATADIR";
    _filename = "resdata.txt";
    _subdir = "data";
    _dataptr = ResidueData;
  }

  bool OBResidueData::AssignBonds(OBMol &mol,OBBitVec &bv)
  {
    if (!_init)
      Init();

    OBAtom *a1,*a2;
    OBResidue *r1,*r2;
    vector<OBAtom*>::iterator i,j;
    vector3 v;

    int bo;
    string skipres = ""; // Residue Number to skip
    string rname = "";
    //assign residue bonds
    for (a1 = mol.BeginAtom(i);a1;a1 = mol.NextAtom(i))
      {
        r1 = a1->GetResidue();
        if (r1 == NULL) // atoms may not have residues
          continue;

        if (skipres.length() && r1->GetNumString() == skipres)
          continue;

        if (r1->GetName() != rname)
          {
            skipres = SetResName(r1->GetName()) ? "" : r1->GetNumString();
            rname = r1->GetName();
          }
        //assign bonds for each atom
        for (j=i,a2 = mol.NextAtom(j);a2;a2 = mol.NextAtom(j))
          {
            r2 = a2->GetResidue();
            if (r2 == NULL) // atoms may not have residues
              continue;

            if (r1->GetNumString() != r2->GetNumString())
              break;
            if (r1->GetName() != r2->GetName())
              break;

            if ((bo = LookupBO(r1->GetAtomID(a1),r2->GetAtomID(a2))))
              {
                // Suggested by Liu Zhiguo 2007-08-13
                // for predefined residues, don't perceive connection
                // by distance
                //                v = a1->GetVector() - a2->GetVector();
                //                if (v.length_2() < 3.5) //check by distance
                  mol.AddBond(a1->GetIdx(),a2->GetIdx(),bo);
              }
          }
      }

    int hyb;
    string type;

    //types and hybridization
    rname = ""; // name of current residue
    skipres = ""; // don't skip any residues right now
    for (a1 = mol.BeginAtom(i);a1;a1 = mol.NextAtom(i))
      {
        if (a1->IsOxygen() && !a1->GetValence())
          {
            a1->SetType("O3");
            continue;
          }
        if (a1->IsHydrogen())
          {
            a1->SetType("H");
            continue;
          }

        //***valence rule for O-
        if (a1->IsOxygen() && a1->GetValence() == 1)
          {
            OBBond *bond;
            bond = (OBBond*)*(a1->BeginBonds());
            if (bond->GetBO() == 2)
              {
                a1->SetType("O2");
                a1->SetHyb(2);
              }
            else if (bond->GetBO() == 1)
              {
                // Leave the protonation/deprotonation to phmodel.txt
                a1->SetType("O3");
                a1->SetHyb(3);
                a1->SetFormalCharge(0);
              }
            continue;
          }
	
        r1 = a1->GetResidue();
        if (r1 == NULL) continue; // atoms may not have residues
        if (skipres.length() && r1->GetNumString() == skipres)
          continue;

        if (r1->GetName() != rname)
          {
            // if SetResName fails, skip this residue
            skipres = SetResName(r1->GetName()) ? "" : r1->GetNumString();
            rname = r1->GetName();
          }

        if (LookupType(r1->GetAtomID(a1),type,hyb))
          {
            a1->SetType(type);
            a1->SetHyb(hyb);
          }
        else // try to figure it out by bond order ???
          {}
      }

    return(true);
  }

  void OBResidueData::ParseLine(const char *buffer)
  {
    int bo;
    string s;
    vector<string> vs;

    if (buffer[0] == '#')
      return;

    tokenize(vs,buffer);
    if (!vs.empty())
      {
        if (vs[0] == "BOND")
          {
            s = (vs[1] < vs[2]) ? vs[1] + " " + vs[2] :
              vs[2] + " " + vs[1];
            bo = atoi(vs[3].c_str());
            _vtmp.push_back(pair<string,int> (s,bo));
          }

        if (vs[0] == "ATOM" && vs.size() == 4)
          {
            _vatmtmp.push_back(vs[1]);
            _vatmtmp.push_back(vs[2]);
            _vatmtmp.push_back(vs[3]);
          }

        if (vs[0] == "RES")
          _resname.push_back(vs[1]);

        if (vs[0]== "END")
          {
            _resatoms.push_back(_vatmtmp);
            _resbonds.push_back(_vtmp);
            _vtmp.clear();
            _vatmtmp.clear();
          }
      }
  }

  bool OBResidueData::SetResName(const string &s)
  {
    if (!_init)
      Init();

    unsigned int i;

    for (i = 0;i < _resname.size();++i)
      if (_resname[i] == s)
        {
          _resnum = i;
          return(true);
        }

    _resnum = -1;
    return(false);
  }

  int OBResidueData::LookupBO(const string &s)
  {
    if (_resnum == -1)
      return(0);

    unsigned int i;
    for (i = 0;i < _resbonds[_resnum].size();++i)
      if (_resbonds[_resnum][i].first == s)
        return(_resbonds[_resnum][i].second);

    return(0);
  }

  int OBResidueData::LookupBO(const string &s1, const string &s2)
  {
    if (_resnum == -1)
      return(0);
    string s;

    s = (s1 < s2) ? s1 + " " + s2 : s2 + " " + s1;

    unsigned int i;
    for (i = 0;i < _resbonds[_resnum].size();++i)
      if (_resbonds[_resnum][i].first == s)
        return(_resbonds[_resnum][i].second);

    return(0);
  }

  bool OBResidueData::LookupType(const string &atmid,string &type,int &hyb)
  {
    if (_resnum == -1)
      return(false);

    string s;
    vector<string>::iterator i;

    for (i = _resatoms[_resnum].begin();i != _resatoms[_resnum].end();i+=3)
      if (atmid == *i)
        {
          i++;
          type = *i;
          i++;
          hyb = atoi((*i).c_str());
          return(true);
        }

    return(false);
  }

  void OBGlobalDataBase::Init()
  {
    if (_init)
      return;
    _init = true;

    ifstream ifs;
    char charBuffer[BUFF_SIZE];

    // Set the locale for number parsing to avoid locale issues: PR#1785463
    obLocale.SetLocale();

    // Check return value from OpenDatafile
    // Suggestion from Zhiguo Liu
    string fn_open = OpenDatafile(ifs, _filename, _envvar);
     
    if (fn_open != "" && (ifs))
      {
        while(ifs.getline(charBuffer,BUFF_SIZE))
          ParseLine(charBuffer);
      }

    else
      // If all else fails, use the compiled in values
      if (_dataptr)
        {
          const char *p1,*p2;
          for (p1 = p2 = _dataptr;*p2 != '\0';++p2)
            if (*p2 == '\n')
              {
                strncpy(charBuffer, p1, (p2 - p1));
                charBuffer[(p2 - p1)] = '\0';
                ParseLine(charBuffer);
                p1 = ++p2;
              }
        }
      else
        {
          string s = "Unable to open data file '";
          s += _filename;
          s += "'";
          obErrorLog.ThrowError(__FUNCTION__, s, obWarning);
        }

    // return the locale to the original one
    obLocale.RestoreLocale();
    
    if (ifs)
      ifs.close();

    if (GetSize() == 0)
      {
        string s = "Cannot initialize database '";
        s += _filename;
        s += "' which may cause further errors.";
        obErrorLog.ThrowError(__FUNCTION__, "Cannot initialize database", obWarning);
      }
      
  }

} // end namespace OpenBabel

//! \file data.cpp
//! \brief Global data and resource file parsers.