XCSoar /src/xmlParser.cpp

Language C++ Lines 2089
MD5 Hash 6cb0ec278345a9dba1f2b9f48139e680
Repository https://github.com/Plantain/XCSoar.git View Raw File View Project SPDX
   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
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
/*
 ****************************************************************************
 * <P> XML.c - implementation file for basic XML parser written in ANSI C++
 * for portability. It works by using recursion and a node tree for breaking
 * down the elements of an XML document.  </P>
 *
 * @version     V1.08
 *
 * @author      Frank Vanden Berghen
 * based on original implementation by Martyn C Brown
 *
 * NOTE:
 *
 *   If you add "#define APPROXIMATE_PARSING", on the first line of this file
 *   the parser will see the following XML-stream:
 *     <data name="n1">
 *     <data name="n2">
 *     <data name="n3" />
 *   as equivalent to the following XML-stream:
 *     <data name="n1" />
 *     <data name="n2" />
 *     <data name="n3" />
 *   This can be useful for badly-formed XML-streams but prevent the use
 *   of the following XML-stream:
 *     <data name="n1">
 *        <data name="n2">
 *            <data name="n3" />
 *        </data>
 *     </data>
 *
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 ****************************************************************************
 */

#if defined(WIN32)
#include <windows.h> // to have IsTextUnicode, MultiByteToWideChar, WideCharToMultiByte
                     // to handle unicode files
#endif

#include "xmlParser.h"
#include "Compatibility/string.h"

#include <assert.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>

bool XMLNode::GlobalError = false;

XMLNode XMLNode::emptyXMLNode;
XMLClear XMLNode::emptyXMLClear = { NULL, NULL, NULL };
XMLAttribute XMLNode::emptyXMLAttribute = { NULL, NULL };

inline int mmin(const int t1, const int t2) { return t1 < t2 ? t1 : t2; }

// Enumeration used to decipher what type a token is
typedef enum TokenTypeTag
{
    eTokenText = 0,
    eTokenQuotedText,
    eTokenTagStart,         /* "<"            */
    eTokenTagEnd,           /* "</"           */
    eTokenCloseTag,         /* ">"            */
    eTokenEquals,           /* "="            */
    eTokenDeclaration,      /* "<?"           */
    eTokenShortHandClose,   /* "/>"           */
    eTokenClear,
    eTokenError
} TokenTypeTag;

#define INDENTCHAR _T('\t')

typedef struct ClearTag
{
    LPCTSTR lpszOpen;
    LPCTSTR lpszClose;
} ClearTag;

// Main structure used for parsing XML
typedef struct XML
{
    LPCTSTR lpXML;
    int nIndex;
    enum XMLError error;
    LPCTSTR lpEndTag;
    int cbEndTag;
    LPCTSTR lpNewElement;
    int cbNewElement;
    int nFirst;
    ClearTag *pClrTags;
} XML;

typedef struct
{
    ClearTag *pClr;
    LPCTSTR pStr;
} NextToken;

// Enumeration used when parsing attributes
typedef enum Attrib
{
    eAttribName = 0,
    eAttribEquals,
    eAttribValue
} Attrib;

// Enumeration used when parsing elements to dictate whether we are currently
// inside a tag
typedef enum Status
{
    eInsideTag = 0,
    eOutsideTag
} Status;

static LPTSTR
toXMLString(LPTSTR dest, LPCTSTR source)
{
  LPTSTR dd = dest;
  while (*source) {
    switch (*source) {
    case '<':
      _tcscpy(dest, _T("&lt;"));
      dest += 4;
      break;
    case '>':
      _tcscpy(dest, _T("&gt;"));
      dest += 4;
      break;
    case '&':
      _tcscpy(dest, _T("&amp;"));
      dest += 5;
      break;
    case '\'':
      _tcscpy(dest, _T("&apos;"));
      dest += 6;
      break;
    case '"':
      _tcscpy(dest, _T("&quot;"));
      dest += 6;
      break;
    default:
      *dest = *source;
      dest++;
      break;
    }
    source++;
  }
  *dest = 0;
  return dd;
}

static int
lengthXMLString(LPCTSTR source)
{
  int r = 0;
  while (*source) {
    switch (*source) {
    case '<':
      r += 3;
      break;
    case '>':
      r += 3;
      break;
    case '&':
      r += 4;
      break;
    case '\'':
      r += 5;
      break;
    case '"':
      r += 5;
      break;
    }
    source++;
    r++;
  }
  return r;
}

LPTSTR
toXMLString(LPCTSTR source)
{
  LPTSTR dest = (LPTSTR)malloc((lengthXMLString(source) + 1) * sizeof(TCHAR));
  assert(dest);
  return toXMLString(dest, source);
}

LPTSTR
toXMLStringFast(LPTSTR *dest, int *destSz, LPCTSTR source)
{
  int l = lengthXMLString(source) + 1;
  if (l > *destSz) {
    *destSz = l;
    *dest = (LPTSTR)realloc(*dest, l * sizeof(TCHAR));
  }
  return toXMLString(*dest, source);
}

static LPTSTR
fromXMLString(LPCTSTR s, int lo)
{
  // This function is the opposite of the function "toXMLString". It decodes the escape
  // sequences &amp;, &quot;, &apos;, &lt;, &gt; and replace them by the characters
  // &,",',<,>. This function is used internally by the XML Parser. All the calls to
  // the XML library will always gives you back "decoded" strings.
  //
  // in: string (s) and length (lo) of string
  // out:  new allocated string converted from xml
  if (!s)
  return NULL;

  int ll = 0;
  LPTSTR d;
  LPCTSTR ss = s;
  while (((lo--) > 0) && (*s)) {
    if (*s == _T('&')) {
      s++;
      if (_tcsnicmp(s, _T("lt;"), 3) == 0) {
        s += 2;
        lo -= 3;
      } else if (_tcsnicmp(s, _T("gt;"), 3) == 0) {
        s += 2;
        lo -= 3;
      } else if (_tcsnicmp(s, _T("amp;"), 4) == 0) {
        s += 3;
        lo -= 4;
      } else if (_tcsnicmp(s, _T("apos;"), 5) == 0) {
        s += 4;
        lo -= 5;
      } else if (_tcsnicmp(s, _T("quot;"), 5) == 0) {
        s += 4;
        lo -= 5;
      } else {
        ll = 0;
        while (s[ll] && (s[ll] != _T(';')) && (ll < 10))
          ll++;
        ll++;
        d = (LPTSTR)malloc((ll + 1) * sizeof(TCHAR));
        assert(d);
        d[ll] = 0;
        while (ll--)
          d[ll] = s[ll];
#ifndef NDEBUG
#ifdef _UNICODE
        printf("unknown escape character: '&%S'",d);
#else
        printf("unknown escape character: '&%s'", d);
#endif
#endif
        free(d);
        XMLNode::GlobalError = true;
        return (LPTSTR)NULL;
      }
    }
    ll++;
    s++;
  }

  d = (LPTSTR)malloc((ll + 1) * sizeof(TCHAR));
  assert(d);
  TCHAR *result = d;
  while (ll--) {
    if (*ss == _T('&')) {
      ss++;
      if (_tcsnicmp(ss, _T("lt;" ), 3) == 0) {
        *(d++) = _T('<' );
        ss += 3;
      } else if (_tcsnicmp(ss, _T("gt;" ), 3) == 0) {
        *(d++) = _T('>' );
        ss += 3;
      } else if (_tcsnicmp(ss, _T("amp;" ), 4) == 0) {
        *(d++) = _T('&' );
        ss += 4;
      } else if (_tcsnicmp(ss, _T("apos;"), 5) == 0) {
        *(d++) = _T('\'');
        ss += 5;
      } else {
        *(d++) = _T('"' );
        ss += 5;
      }
    } else {
      *(d++) = *ss;
      ss++;
    }
  }
  *d = 0;
  return result;
}

static char
myTagCompare(LPCTSTR cclose, LPCTSTR copen)
{
  // !!!! WARNING strange convention&:
  // return 0 if equals
  // return 1 if different
  if (!cclose)
    return 1;
  int l = (int)_tcslen(cclose);
  if (_tcsnicmp(cclose, copen, l) != 0)
    return 1;

  const TCHAR c = copen[l];
  if ((c == _T('\n')) ||
      (c == _T(' ')) ||
      (c == _T('\t')) ||
      (c == _T('\r')) ||
      (c == _T('/')) ||
      (c == _T('<')) ||
      (c == _T('>')) ||
      (c == _T('=')))
    return 0;

  return 1;
}

// update "order" information when deleting a content of a XMLNode
void
XMLNode::removeOrderElement(XMLNodeData *d, XMLElementType t, int index)
{
  int j = (int)((index << 2) + t), i = 0, n = nElement(d) + 1, *o = d->pOrder;
  while ((o[i] != j) && (i < n))
    i++;
  n--;
  memmove(o + i, o + i + 1, (n - i) * sizeof(int));
  for (; i < n; i++)
    if ((o[i] & 3) == (int)t)
      o[i] -= 4;
  // We should normally do:
  // d->pOrder=(int)realloc(d->pOrder,n*sizeof(int));
  // but we skip reallocation because it's too time consuming.
  // Anyway, at the end, it will be free'd completely at once.
}

// Obtain the next character from the string.
static inline TCHAR
getNextChar(XML *pXML)
{
  TCHAR ch = pXML->lpXML[pXML->nIndex];
  if (ch != 0)
    pXML->nIndex++;
  return ch;
}

// Find next non-white space character.
static TCHAR
FindNonWhiteSpace(XML *pXML)
{
  TCHAR ch = 0; // VENTA3 fix initialize
  int nExit = FALSE;

  assert(pXML);

    // Iterate through characters in the string until we find a NULL or a
  // non-white space character
  while ((nExit == FALSE) && ((ch = getNextChar(pXML)) != 0)) {
    switch (ch) {
    // Ignore white space
    case _T('\n'):
    case _T(' '):
    case _T('\t'):
    case _T('\r'):
      continue;
    default:
      nExit = TRUE;
    }
  }
  return ch;
}

// Find the next token in a string.
// pcbToken contains the number of characters that have been read.
static NextToken
GetNextToken(XML *pXML, int *pcbToken, enum TokenTypeTag *pType)
{
  NextToken result;
  LPCTSTR lpXML;
  TCHAR ch;
  TCHAR chTemp;
  int nSize;
  int nFoundMatch;
  int nExit;
  int n;
  LPCTSTR lpszOpen;
  int cbOpen;
  int nIsText = FALSE;

  result.pClr = NULL; // avoid compiler warning for uninitialised variable

  // Find next non-white space character
  ch = FindNonWhiteSpace(pXML);

  if (ch) {
    // Cache the current string pointer
    lpXML = pXML->lpXML;
    result.pStr = &lpXML[pXML->nIndex - 1];

    // First check whether the token is in the clear tag list (meaning it
    // does not need formatting).
    n = 0;

    while (TRUE) {
      // Obtain the name of the open part of the clear tag
      lpszOpen = pXML->pClrTags[n].lpszOpen;

      if (lpszOpen) {
        // Compare the open tag with the current token
        cbOpen = (int)_tcslen(lpszOpen);
        // if (myTagCompare(lpszOpen, result.pStr) == 0)
        if (_tcsnicmp(lpszOpen, result.pStr, cbOpen) == 0) {
          result.pClr = &pXML->pClrTags[n];
          pXML->nIndex += (int)(_tcslen(lpszOpen) - 1);
          *pType = eTokenClear;
          return result;
        }
        n++;
      } else
        break;
    }
    // If we didn't find a clear tag then check for standard tokens
    chTemp = 0;
    lpXML = pXML->lpXML;

    switch (ch) {
    // Check for quotes
    case _T('\''):
    case _T('\"'):
      // Type of token
      *pType = eTokenQuotedText;
      chTemp = ch;
      n = pXML->nIndex;

      // Set the size
      nSize = 1;
      nFoundMatch = FALSE;

      // Search through the string to find a matching quote
      while (((ch = getNextChar(pXML))) != 0) {
        nSize++;
        if (ch == chTemp) {
          nFoundMatch = TRUE;
          break;
        }
        if (ch == _T('<'))
          break;
      }

      // If we failed to find a matching quote
      if (nFoundMatch == FALSE) {
        pXML->nIndex = n - 1;
        ch = getNextChar(pXML);
        nIsText = TRUE;
        break;
      }

      //  4.02.2002
      if (FindNonWhiteSpace(pXML)) {
        pXML->nIndex--;
      }

      break;

    // Equals (used with attribute values)
    case _T('='):
      nSize = 1;
      *pType = eTokenEquals;
      break;

    // Close tag
    case _T('>'):
      nSize = 1;
      *pType = eTokenCloseTag;
      break;

    // Check for tag start and tag end
    case _T('<'):

      // Peek at the next character to see if we have an end tag '</',
      // or an xml declaration '<?'
      chTemp = pXML->lpXML[pXML->nIndex];

      // If we have a tag end...
      if (chTemp == _T('/')) {
        // Set the type and ensure we point at the next character
        getNextChar(pXML);
        *pType = eTokenTagEnd;
        nSize = 2;
      }

      // If we have an XML declaration tag
      else if (chTemp == _T('?')) {

        // Set the type and ensure we point at the next character
        getNextChar(pXML);
        *pType = eTokenDeclaration;
        nSize = 2;
      }

      // Otherwise we must have a start tag
      else {
        *pType = eTokenTagStart;
        nSize = 1;
      }
      break;

    // Check to see if we have a short hand type end tag ('/>').
    case _T('/'):

            // Peek at the next character to see if we have a short end tag '/>'
      chTemp = pXML->lpXML[pXML->nIndex];

      // If we have a short hand end tag...
      if (chTemp == _T('>')) {
        // Set the type and ensure we point at the next character
        getNextChar(pXML);
        *pType = eTokenShortHandClose;
        nSize = 2;
        break;
      }

      // If we haven't found a short hand closing tag then drop into the
      // text process

      // Other characters
    default:
      nIsText = TRUE;
    }

    // If this is a TEXT node
    if (nIsText) {
      // Indicate we are dealing with text
      *pType = eTokenText;
      nSize = 1;
      nExit = FALSE;

      while ((nExit == FALSE) && ((ch = getNextChar(pXML)) != 0)) {
        switch (ch) {
        // Break when we find white space
        case _T('\n'):
        case _T(' '):
        case _T('\t'):
        case _T('\r'):
          nExit = TRUE;
          break;

        // If we find a slash then this maybe text or a short hand end tag.
        case _T('/'):

          // Peek at the next character to see it we have short hand end tag
          chTemp = pXML->lpXML[pXML->nIndex];

          // If we found a short hand end tag then we need to exit the loop
          if (chTemp == _T('>')) {
            pXML->nIndex--; //  03.02.2002
            nExit = TRUE;
          } else {
            nSize++;
          }
          break;

        // Break when we find a terminator and decrement the index and
        // column count so that we are pointing at the right character
        // the next time we are called.
        case _T('<'):
        case _T('>'):
        case _T('='):
          pXML->nIndex--;
          nExit = TRUE;
          break;

        case 0:
          nExit = TRUE;
          break;

        default:
          nSize++;
        }
      }
    }
    *pcbToken = nSize;
  } else {
    // If we failed to obtain a valid character
    *pcbToken = 0;
    *pType = eTokenError;
    result.pStr = NULL;
  }

  return result;
}

// Parse XML errors into a user friendly string.
LPCTSTR XMLNode::getError(XMLError error)
{
  switch (error) {
  case eXMLErrorNone:
    return _T("No error");
  case eXMLErrorEmpty:
    return _T("No XML data");
  case eXMLErrorFirstNotStartTag:
    return _T("First token not start tag");
  case eXMLErrorMissingTagName:
    return _T("Missing start tag name");
  case eXMLErrorMissingEndTagName:
    return _T("Missing end tag name");
  case eXMLErrorNoMatchingQuote:
    return _T("Unmatched quote");
  case eXMLErrorUnmatchedEndTag:
    return _T("Unmatched end tag");
  case eXMLErrorUnexpectedToken:
    return _T("Unexpected token found");
  case eXMLErrorInvalidTag:
    return _T("Invalid tag found");
  case eXMLErrorNoElements:
    return _T("No elements found");
  case eXMLErrorFileNotFound:
    return _T("File not found");
  }

  return _T("Unknown");
}


XMLNode XMLNode::createRoot(LPCTSTR lpszName)
{
  return XMLNode(NULL, lpszName, false);
}

XMLNode::XMLNode(XMLNode *pParent, LPCTSTR lpszName, int isDeclaration)
{
  d = (XMLNodeData*)malloc(sizeof(XMLNodeData));
  assert(d);
  d->ref_count = 1;

  d->lpszName = lpszName;

  d->nChild = 0;
  d->nText = 0;
  d->nClear = 0;
  d->nAttribute = 0;

  d->isDeclaration = isDeclaration;

  d->pParent = pParent;
  d->pChild = NULL;
  d->pText = NULL;
  d->pClear = NULL;
  d->pAttribute = NULL;
  d->pOrder = NULL;
}

const int memoryIncrease = 50;

static void *
myRealloc(void *p, int newsize, int memInc, int sizeofElem)
{
  int blocks = newsize / memInc + 1;
  if (p == NULL) {
    void* v = malloc(blocks * memInc * sizeofElem);
    assert(v);
    return v;
  }
  if ((newsize % memInc) == 0) {
    p = realloc(p, blocks * memInc * sizeofElem);
    assert(p);
  }
  return p;
}

void
XMLNode::addToOrder(int index, int type)
{
  int n = nElement();
  d->pOrder = (int*)myRealloc(d->pOrder, n + 1, memoryIncrease * 3, sizeof(int));
  assert(d->pOrder);
  d->pOrder[n] = (index << 2) + type;
}

// Add a child node to the given element.
XMLNode
XMLNode::AddChild(LPCTSTR lpszName, int isDeclaration)
{
  if (!lpszName)
    return emptyXMLNode;
  int nc = d->nChild;
  d->pChild = (XMLNode*)myRealloc(d->pChild, (nc + 1), memoryIncrease,
                                  sizeof(XMLNode));
  assert(d->pChild);
  d->pChild[nc].d = NULL;
  d->pChild[nc] = XMLNode(this, lpszName, isDeclaration);
  addToOrder(nc, eNodeChild);
  d->nChild++;
  return d->pChild[nc];
}

// Add an attribute to an element.
XMLAttribute *
XMLNode::AddAttribute(LPCTSTR lpszName, LPCTSTR lpszValuev)
{
  if (!lpszName)
    return &emptyXMLAttribute;

  int na = d->nAttribute;
  d->pAttribute = (XMLAttribute*)myRealloc(d->pAttribute, (na + 1),
                                           memoryIncrease, sizeof(XMLAttribute));
  XMLAttribute *pAttr = d->pAttribute + na;
  pAttr->lpszName = lpszName;
  pAttr->lpszValue = lpszValuev;
  addToOrder(na, eNodeAttribute);
  d->nAttribute++;
  return pAttr;
}

// Add text to the element.
LPCTSTR XMLNode::AddText(LPCTSTR lpszValue)
{
  if (!lpszValue)
    return NULL;

  int nt = d->nText;
  d->pText = (LPCTSTR*)myRealloc(d->pText, (nt + 1), memoryIncrease,
                                 sizeof(LPTSTR));
  d->pText[nt] = lpszValue;
  addToOrder(nt, eNodeText);
  d->nText++;
  return d->pText[nt];
}

// Add clear (unformatted) text to the element.
XMLClear *XMLNode::AddClear(LPCTSTR lpszValue, LPCTSTR lpszOpen, LPCTSTR lpszClose)
{
  if (!lpszValue)
    return &emptyXMLClear;

  int nc = d->nClear;
  d->pClear = (XMLClear *)myRealloc(d->pClear, (nc + 1), memoryIncrease,
                                    sizeof(XMLClear));
  XMLClear *pNewClear = d->pClear + nc;
  pNewClear->lpszValue = lpszValue;
  pNewClear->lpszOpenTag = lpszOpen;
  pNewClear->lpszCloseTag = lpszClose;
  addToOrder(nc, eNodeClear);
  d->nClear++;
  return pNewClear;
}

// Trim the end of the text to remove white space characters.
static void
FindEndOfText(LPCTSTR lpszToken, int *pcbText)
{
  TCHAR ch;
  int cbText;
  assert(lpszToken);
  assert(pcbText);
  cbText = (*pcbText) - 1;
  while (1) {
    assert(cbText >= 0);
    ch = lpszToken[cbText];
    switch (ch) {
    case _T('\r'):
    case _T('\n'):
    case _T('\t'):
    case _T(' '):
      cbText--;
      break;
    default:
      *pcbText = cbText + 1;
      return;
    }
  }
}

// Duplicate a given string.
LPTSTR
stringDup(LPCTSTR lpszData, int cbData)
{
  if (lpszData == NULL)
    return NULL;

  LPTSTR lpszNew;
  if (cbData == 0)
    cbData = (int)_tcslen(lpszData);
  lpszNew = (LPTSTR)malloc((cbData + 1) * sizeof(TCHAR));
  assert(lpszNew);
  if (lpszNew) {
    memcpy(lpszNew, lpszData, (cbData) * sizeof(TCHAR));
    lpszNew[cbData] = (TCHAR)NULL;
  }
  return lpszNew;
}

// Parse a clear (unformatted) type node.
int
XMLNode::ParseClearTag(void *px, void *pa)
{
  XML *pXML = (XML *)px;
  ClearTag *pClear = (ClearTag *)pa;
  int cbTemp = 0;
  LPCTSTR lpszTemp;
  LPCTSTR lpszXML = &pXML->lpXML[pXML->nIndex];

  // Find the closing tag
  lpszTemp = _tcsstr(lpszXML, pClear->lpszClose);

  // Iterate through the tokens until we find the closing tag.
  if (lpszTemp) {
    // Cache the size and increment the index
    cbTemp = (int)(lpszTemp - lpszXML);

    pXML->nIndex += cbTemp;
    pXML->nIndex += (int)_tcslen(pClear->lpszClose);

    // Add the clear node to the current element
    AddClear(stringDup(lpszXML, cbTemp), pClear->lpszOpen, pClear->lpszClose);
    return TRUE;
  }

  // If we failed to find the end tag
  pXML->error = eXMLErrorUnmatchedEndTag;
  return FALSE;
}

// Recursively parse an XML element.
int
XMLNode::ParseXMLElement(void *pa)
{
  XML *pXML = (XML *)pa;
  int cbToken;
  enum TokenTypeTag type;
  NextToken token;
  LPCTSTR lpszTemp = NULL;
  int cbTemp;
  int nDeclaration;
  LPCTSTR lpszText = NULL;
  XMLNode pNew;
  enum Status status; // inside or outside a tag
  enum Attrib attrib = eAttribName;

  assert(pXML);

  // If this is the first call to the function
  if (pXML->nFirst) {
    // Assume we are outside of a tag definition
    pXML->nFirst = FALSE;
    status = eOutsideTag;
  } else {
    // If this is not the first call then we should only be called when inside a tag.
    status = eInsideTag;
  }

  // Iterate through the tokens in the document
  while (TRUE) {
    // Obtain the next token
    token = GetNextToken(pXML, &cbToken, &type);

    if (type != eTokenError) {
      // Check the current status
      switch (status) {
      // If we are outside of a tag definition
      case eOutsideTag:

        // Check what type of token we obtained
        switch (type) {
        // If we have found text or quoted text
        case eTokenText:
        case eTokenQuotedText:
        case eTokenEquals:
          if (!lpszText)
            lpszText = token.pStr;

          break;

        // If we found a start tag '<' and declarations '<?'
        case eTokenTagStart:
        case eTokenDeclaration:
          // Cache whether this new element is a declaration or not
          nDeclaration = type == eTokenDeclaration;

          // If we have node text then add this to the element
          if (lpszText) {
            cbTemp = (int)(token.pStr - lpszText);
            FindEndOfText(lpszText, &cbTemp);
            AddText(stringDup(lpszText, cbTemp));
            lpszText = NULL;
          }

          // Find the name of the tag
          token = GetNextToken(pXML, &cbToken, &type);

          // Return an error if we couldn't obtain the next token or
          // it wasnt text
          if (type != eTokenText) {
            pXML->error = eXMLErrorMissingTagName;
            return FALSE;
          }

          // If we found a new element which is the same as this
          // element then we need to pass this back to the caller..

#ifdef APPROXIMATE_PARSING
          if (d->lpszName && myTagCompare(d->lpszName, token.pStr) == 0) {
            // Indicate to the caller that it needs to create a
            // new element.
            pXML->lpNewElement = token.pStr;
            pXML->cbNewElement = cbToken;
            return TRUE;
          } else
#endif
          {
            // If the name of the new element differs from the name of
            // the current element we need to add the new element to
            // the current one and recurse
            pNew = AddChild(stringDup(token.pStr, cbToken), nDeclaration);

            while (!pNew.isEmpty()) {
              // Callself to process the new node.  If we return
              // FALSE this means we dont have any more
              // processing to do...

              if (!pNew.ParseXMLElement(pXML)) {
                d->pOrder = (int*)myRealloc(d->pOrder, nElement(),
                                            memoryIncrease * 3, sizeof(int));
                d->pChild = (XMLNode*)myRealloc(d->pChild, d->nChild,
                                                memoryIncrease, sizeof(XMLNode));
                if (d->nAttribute > 0)
                  d->pAttribute = (XMLAttribute*)myRealloc(d->pAttribute,
                                                           d->nAttribute,
                                                           memoryIncrease,
                                                           sizeof(XMLAttribute));
                if (d->nText > 0)
                  d->pText = (LPCTSTR*)myRealloc(d->pText, d->nText,
                                                 memoryIncrease, sizeof(LPTSTR));
                if (d->nClear > 0)
                  d->pClear = (XMLClear *)myRealloc(d->pClear, d->nClear,
                                                    memoryIncrease,
                                                    sizeof(XMLClear));
                return FALSE;
              } else {
                // If the call to recurse this function
                // evented in a end tag specified in XML then
                // we need to unwind the calls to this
                // function until we find the appropriate node
                // (the element name and end tag name must
                // match)
                if (pXML->cbEndTag) {
                  // If we are back at the root node then we
                  // have an unmatched end tag
                  if (!d->lpszName) {
                    pXML->error = eXMLErrorUnmatchedEndTag;
                    return FALSE;
                  }

                  // If the end tag matches the name of this
                  // element then we only need to unwind
                  // once more...

                  if (myTagCompare(d->lpszName, pXML->lpEndTag) == 0) {
                    pXML->cbEndTag = 0;
                  }

                  return TRUE;
                } else if (pXML->cbNewElement) {
                  // If the call indicated a new element is to
                  // be created on THIS element.

                  // If the name of this element matches the
                  // name of the element we need to create
                  // then we need to return to the caller
                  // and let it process the element.

                  if (myTagCompare(d->lpszName, pXML->lpNewElement) == 0)
                    return TRUE;

                  // Add the new element and recurse
                  pNew = AddChild(stringDup(pXML->lpNewElement,
                                            pXML->cbNewElement), FALSE);
                  pXML->cbNewElement = 0;
                } else {
                  // If we didn't have a new element to create
                  pNew = emptyXMLNode;
                }
              }
            }
          }
          break;

        // If we found an end tag
        case eTokenTagEnd:

          // If we have node text then add this to the element
          if (lpszText) {
            cbTemp = (int)(token.pStr - lpszText);
            FindEndOfText(lpszText, &cbTemp);
            AddText(fromXMLString(lpszText, cbTemp));
            lpszText = NULL;
          }

          // Find the name of the end tag
          token = GetNextToken(pXML, &cbTemp, &type);

          // The end tag should be text
          if (type != eTokenText) {
            pXML->error = eXMLErrorMissingEndTagName;
            return FALSE;
          }
          lpszTemp = token.pStr;

          // After the end tag we should find a closing tag
          token = GetNextToken(pXML, &cbToken, &type);
          if (type != eTokenCloseTag) {
            pXML->error = eXMLErrorMissingEndTagName;
            return FALSE;
          }

          // We need to return to the previous caller.  If the name
          // of the tag cannot be found we need to keep returning to
          // caller until we find a match
          if (myTagCompare(d->lpszName, lpszTemp) != 0) {
            pXML->lpEndTag = lpszTemp;
            pXML->cbEndTag = cbTemp;
          }

          // Return to the caller
          return TRUE;

        // If we found a clear (unformatted) token
        case eTokenClear:
          // If we have node text then add this to the element
          if (lpszText) {
            cbTemp = (int)(token.pStr - lpszText);
            FindEndOfText(lpszText, &cbTemp);
            AddText(stringDup(lpszText, cbTemp));
            lpszText = NULL;
          }

          if (!ParseClearTag(pXML, token.pClr)) {
            return FALSE;
          }
          break;

        // Errors...
        case eTokenCloseTag: /* '>'         */
        case eTokenShortHandClose: /* '/>'        */
          pXML->error = eXMLErrorUnexpectedToken;
          return FALSE;
        default:
          break;
        }
        break;

      // If we are inside a tag definition we need to search for attributes
      case eInsideTag:
        // Check what part of the attribute (name, equals, value) we
        // are looking for.
        switch (attrib) {
        // If we are looking for a new attribute
        case eAttribName:
          // Check what the current token type is
          switch (type) {
          // If the current type is text...
          // Eg.  'attribute'
          case eTokenText:
            // Cache the token then indicate that we are next to
            // look for the equals
            lpszTemp = token.pStr;
            cbTemp = cbToken;
            attrib = eAttribEquals;
            break;

          // If we found a closing tag...
          // Eg.  '>'
          case eTokenCloseTag:
            // We are now outside the tag
            status = eOutsideTag;
            break;

          // If we found a short hand '/>' closing tag then we can
          // return to the caller
          case eTokenShortHandClose:
            return TRUE;

          // Errors...
          case eTokenQuotedText: /* '"SomeText"'   */
          case eTokenTagStart: /* '<'            */
          case eTokenTagEnd: /* '</'           */
          case eTokenEquals: /* '='            */
          case eTokenDeclaration: /* '<?'           */
          case eTokenClear:
            pXML->error = eXMLErrorUnexpectedToken;
            return FALSE;
          default:
            break;
          }
          break;

        // If we are looking for an equals
        case eAttribEquals:
          // Check what the current token type is
          switch (type) {
          // If the current type is text...
          // Eg.  'Attribute AnotherAttribute'
          case eTokenText:
            // Add the unvalued attribute to the list
            AddAttribute(stringDup(lpszTemp, cbTemp), NULL);
            // Cache the token then indicate.  We are next to
            // look for the equals attribute
            lpszTemp = token.pStr;
            cbTemp = cbToken;
            break;

          // If we found a closing tag 'Attribute >' or a short hand
          // closing tag 'Attribute />'
          case eTokenShortHandClose:
          case eTokenCloseTag:
            // If we are a declaration element '<?' then we need
            // to remove extra closing '?' if it exists
            if (d->isDeclaration && (lpszTemp[cbTemp - 1]) == _T('?'))
              cbTemp--;

            if (cbTemp)
              // Add the unvalued attribute to the list
              AddAttribute(stringDup(lpszTemp, cbTemp), NULL);

            // If this is the end of the tag then return to the caller
            if (type == eTokenShortHandClose)
              return TRUE;

            // We are now outside the tag
            status = eOutsideTag;
            break;

          // If we found the equals token...
          // Eg.  'Attribute ='
          case eTokenEquals:
            // Indicate that we next need to search for the value
            // for the attribute
            attrib = eAttribValue;
            break;

          // Errors...
          case eTokenQuotedText: /* 'Attribute "InvalidAttr"'*/
          case eTokenTagStart: /* 'Attribute <'            */
          case eTokenTagEnd: /* 'Attribute </'           */
          case eTokenDeclaration: /* 'Attribute <?'           */
          case eTokenClear:
            pXML->error = eXMLErrorUnexpectedToken;
            return FALSE;
          default:
            break;
          }
          break;

        // If we are looking for an attribute value
        case eAttribValue:
          // Check what the current token type is
          switch (type) {
          // If the current type is text or quoted text...
          // Eg.  'Attribute = "Value"' or 'Attribute = Value' or
          // 'Attribute = 'Value''.
          case eTokenText:
          case eTokenQuotedText:
            // If we are a declaration element '<?' then we need
            // to remove extra closing '?' if it exists
            if (d->isDeclaration && (token.pStr[cbToken - 1]) == _T('?')) {
              cbToken--;
            }

            if (cbTemp) {
              // Add the valued attribute to the list
              if (type == eTokenQuotedText) {
                token.pStr++;
                cbToken -= 2;
              }
              AddAttribute(stringDup(lpszTemp, cbTemp), fromXMLString(
                  token.pStr, cbToken));
            }

            // Indicate we are searching for a new attribute
            attrib = eAttribName;
            break;

          // Errors...
          case eTokenTagStart: /* 'Attr = <'          */
          case eTokenTagEnd: /* 'Attr = </'         */
          case eTokenCloseTag: /* 'Attr = >'          */
          case eTokenShortHandClose: /* "Attr = />"         */
          case eTokenEquals: /* 'Attr = ='          */
          case eTokenDeclaration: /* 'Attr = <?'         */
          case eTokenClear:
            pXML->error = eXMLErrorUnexpectedToken;
            return FALSE;
            break;
          default:
            break;
          }
        }
      }
    }
    // If we failed to obtain the next token
    else
      return FALSE;
  }
}

// Count the number of lines and columns in an XML string.
static void
CountLinesAndColumns(LPCTSTR lpXML, int nUpto, XMLResults *pResults)
{
  TCHAR ch;
  int n;

  assert(lpXML);
  assert(pResults);

  pResults->nLine = 1;
  pResults->nColumn = 1;
  for (n = 0; n < nUpto; n++) {
    ch = lpXML[n];
    assert(ch);
    if (ch == _T('\n')) {
      pResults->nLine++;
      pResults->nColumn = 1;
    } else
      pResults->nColumn++;
  }
}

/**
 * Parses the given XML String (lpszXML) and returns the main XMLNode
 * @param lpszXML XML String
 * @param tag (?)
 * @param pResults XMLResult object to write in on error or success
 * @return The main XMLNode or empty XMLNode on error
 */
XMLNode
XMLNode::parseString(LPCTSTR lpszXML, XMLResults *pResults)
{
  // If String is empty
  if (!lpszXML) {
    // If XMLResults object exists
    if (pResults) {
      // -> Save the error type
      pResults->error = eXMLErrorNoElements;
      pResults->nLine = 0;
      pResults->nColumn = 0;
    }

    // -> Return empty XMLNode
    return emptyXMLNode;
  }

  static struct ClearTag tags[] = {
      { _T("<![CDATA["), _T("]]>") },
      { _T("<PRE>"),     _T("</PRE>") },
      { _T("<Script>"),  _T("</Script>") },
      { _T("<!--"),      _T("-->") },
      { _T("<!DOCTYPE"), _T(">") },
      { NULL,            NULL }
  };

  enum XMLError error;
  XMLNode xnode(NULL, NULL, FALSE);
  struct XML xml = { NULL, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE, NULL };

  xml.lpXML = lpszXML;
  xml.pClrTags = tags;

  // Fill the XMLNode xnode with the parsed data of xml
  // note: xnode is now the document node, not the main XMLNode
  xnode.ParseXMLElement(&xml);
  error = xml.error;

  // If the document node does not have childnodes
  if (xnode.nChildNode() < 1) {
    // If XMLResults object exists
    if (pResults) {
      // -> Save the error type
      pResults->error = eXMLErrorNoElements;
      pResults->nLine = 0;
      pResults->nColumn = 0;
    }

    // -> Return empty XMLNode
    return emptyXMLNode;
  } else {
    // Set the document's first childnode as new main node
    xnode = xnode.getChildNode(0);
  }

  // If the new main node is the xml declaration
  // -> try to take the first childnode again
  if (xnode.isDeclaration()) {
    // If the declaration does not have childnodes
    if (xnode.nChildNode() < 1) {
      // If XMLResults object exists
      if (pResults) {
        // -> Save the error type
        pResults->error = eXMLErrorNoElements;
        pResults->nLine = 0;
        pResults->nColumn = 0;
      }

      // -> Return empty XMLNode
      return emptyXMLNode;
    } else {
      // Set the declaration's first childnode as new main node
      xnode = xnode.getChildNode(0);
    }
  }

  // If error occurred -> set node to empty
  if (error != eXMLErrorNone)
    xnode = emptyXMLNode;

  // If an XMLResults object exists
  // -> save the result (error/success)
  if (pResults) {
    pResults->error = error;

    // If we have an error
    if (error != eXMLErrorNone) {
      // Find which line and column it starts on and
      // save it in the XMLResults object
      CountLinesAndColumns(xml.lpXML, xml.nIndex, pResults);
    }
  }

  // Return the node (empty, main or child of main that equals tag)
  return xnode;
}

/**
* Opens the file given by the filepath in lpszXML and returns the main node.
* (Includes error handling)
 * @param filename Filepath to the XML file to parse
 * @param tag (?)
 * @param pResults Pointer to the XMLResults object to fill on error or success
 * @return The main XMLNode or an empty node on error
 */
XMLNode
XMLNode::parseFile(const char *filename, XMLResults *pResults)
{
  // Open the file for reading
  FILE *f = fopen(filename, "rb");

  // If file can't be read
  if (f == NULL) {
    // If XMLResults object exists
    if (pResults) {
      // -> Save the error type into it
      pResults->error = eXMLErrorFileNotFound;
      pResults->nLine = 0;
      pResults->nColumn = 0;
    }

    // -> Return empty XMLNode
    return emptyXMLNode;
  }

  // Get filelength (l)
  fseek(f, 0, SEEK_END);
  int l = ftell(f);

  // Read the whole(!) file into a buffer string
  fseek(f, 0, SEEK_SET);
  char *raw = new char[l + 1];
  fread(raw, l, 1, f);

  // Close the file
  fclose(f);

  TCHAR *text;
#ifdef _UNICODE
  text = new TCHAR[l + 1];
  l = MultiByteToWideChar(CP_ACP, // code page
                          MB_PRECOMPOSED, // character-type options
                          raw, // string to map
                          l, // number of bytes in string
                          text, // wide-character buffer
                          l); // size of buffer
  delete[] raw;

  if (l <= 0) {
    /* conversion has failed */
    delete[] text;
    return emptyXMLNode;
  }
#else
  text = raw;
#endif

  // Terminate the buffer string
  text[l] = 0;

  // Parse the string and get the main XMLNode
  XMLNode x = parseString(text, pResults);

  // Free the buffer memory
  delete[] text;

  // Return the main XMLNode
  return x;
}

/**
 * Opens the file given by the filepath in lpszXML and returns the main node.
 * (Includes error handling)
 * @param lpszXML Filepath to the XML file to parse
 * @param tag (?)
 * @return The main XMLNode
 */
XMLNode
XMLNode::openFileHelper(const char *lpszXML)
{
  XMLResults pResults;
  XMLNode::GlobalError = false;

  // Parse the file and get the main XMLNode
  XMLNode xnode = XMLNode::parseFile(lpszXML, &pResults);

  // If error appeared
  if (pResults.error != eXMLErrorNone) {

    // In debug mode -> Log error to stdout
#ifndef NDEBUG
    printf("XML Parsing error inside file '%s'.\n"
#ifdef _UNICODE
           "Error: %S\n"
#else
           "Error: %s\n"
#endif
           "At line %i, column %i.\n", lpszXML,
           XMLNode::getError(pResults.error), pResults.nLine, pResults.nColumn);
#endif

    // Remember Error
    XMLNode::GlobalError = true;
  }

  // Return the parsed node or empty node on error
  return xnode;
}

XMLNodeContents
XMLNode::enumContents(int i)
{
  XMLNodeContents c;
  if (!d) {
    c.type = eNodeNULL;
    return c;
  }
  c.type = (XMLElementType)(d->pOrder[i] & 3);
  i = (d->pOrder[i]) >> 2;
  switch (c.type) {
  case eNodeChild:
    c.child = d->pChild[i];
    break;
  case eNodeAttribute:
    c.attrib = d->pAttribute[i];
    break;
  case eNodeText:
    c.text = d->pText[i];
    break;
  case eNodeClear:
    c.clear = d->pClear[i];
    break;
  default:
    break;
  }
  return c;
}

void *
XMLNode::enumContent(XMLNodeData *pEntry, int i, XMLElementType *nodeType)
{
  XMLElementType j = (XMLElementType)(pEntry->pOrder[i] & 3);
  *nodeType = j;
  i = (pEntry->pOrder[i]) >> 2;
  switch (j) {
  case eNodeChild:
    return pEntry->pChild[i].d;
  case eNodeAttribute:
    return pEntry->pAttribute + i;
  case eNodeText:
    return (void*)(pEntry->pText[i]);
  case eNodeClear:
    return pEntry->pClear + i;
  default:
    break;
  }
  return NULL;
}

int
XMLNode::nElement(XMLNodeData *pEntry)
{
  return pEntry->nChild + pEntry->nText + pEntry->nClear + pEntry->nAttribute;
}

static inline void
charmemset(LPTSTR dest, TCHAR c, int l)
{
  while (l--)
    *(dest++) = c;
}

// Creates an user friendly XML string from a given element with
// appropriate white space and carriage returns.
//
// This recurses through all subnodes then adds contents of the nodes to the
// string.
int
XMLNode::CreateXMLStringR(XMLNodeData *pEntry, LPTSTR lpszMarker, int nFormat)
{
  int nResult = 0;
  int cb;
  int cbElement;
  int nIndex;
  int nChildFormat = -1;
  int bHasChildren = FALSE;
  int i;
  XMLAttribute * pAttr;

  assert(pEntry);

#define LENSTR(lpsz) (lpsz ? _tcslen(lpsz) : 0)

  // If the element has no name then assume this is the head node.
  cbElement = (int)LENSTR(pEntry->lpszName);

  if (cbElement) {
    // "<elementname "
    cb = nFormat == -1 ? 0 : nFormat;

    if (lpszMarker) {
      if (cb)
        charmemset(lpszMarker, INDENTCHAR, sizeof(TCHAR) * cb);
      nResult = cb;
      lpszMarker[nResult++] = _T('<');
      if (pEntry->isDeclaration)
        lpszMarker[nResult++] = _T('?');
      _tcscpy(&lpszMarker[nResult], pEntry->lpszName);
      nResult += cbElement;
      lpszMarker[nResult++] = _T(' ');

    } else {
      nResult += cbElement + 2 + cb;
      if (pEntry->isDeclaration)
        nResult++;
    }

    // Enumerate attributes and add them to the string
    nIndex = pEntry->nAttribute;
    pAttr = pEntry->pAttribute;
    for (i = 0; i < nIndex; i++) {
      // "Attrib
      cb = (int)LENSTR(pAttr->lpszName);
      if (cb) {
        if (lpszMarker)
          _tcscpy(&lpszMarker[nResult], pAttr->lpszName);
        nResult += cb;
        // "Attrib=Value "
        cb = (int)lengthXMLString(pAttr->lpszValue);
        if (cb) {
          if (lpszMarker) {
            lpszMarker[nResult] = _T('=');
            lpszMarker[nResult + 1] = _T('"');
            toXMLString(&lpszMarker[nResult + 2], pAttr->lpszValue);
            lpszMarker[nResult + cb + 2] = _T('"');
          }
          nResult += cb + 3;
        }
        if (lpszMarker)
          lpszMarker[nResult] = _T(' ');
        nResult++;
      }
      pAttr++;
    }

    bHasChildren = (pEntry->nAttribute != nElement(pEntry));
    if (pEntry->isDeclaration) {
      if (lpszMarker) {
        lpszMarker[nResult - 1] = _T('?');
        lpszMarker[nResult] = _T('>');
      }
      nResult++;
      if (nFormat != -1) {
        if (lpszMarker)
          lpszMarker[nResult] = _T('\n');
        nResult++;
      }
    } else
    // If there are child nodes we need to terminate the start tag
    if (bHasChildren) {
      if (lpszMarker)
        lpszMarker[nResult - 1] = _T('>');
      if (nFormat != -1) {
        if (lpszMarker)
          lpszMarker[nResult] = _T('\n');
        nResult++;
      }
    } else
      nResult--;
  }

  // Calculate the child format for when we recurse.  This is used to
  // determine the number of spaces used for prefixes.
  if (nFormat != -1) {
    if (cbElement)
      nChildFormat = nFormat + 1;
    else
      nChildFormat = nFormat;
  }

  // Enumerate through remaining children
  nIndex = nElement(pEntry);
  XMLElementType nodeType;
  void *pChild;
  for (i = 0; i < nIndex; i++) {
    pChild = enumContent(pEntry, i, &nodeType);
    switch (nodeType) {
    // Text nodes
    case eNodeText:
      // "Text"
      cb = (int)lengthXMLString((LPTSTR)pChild);
      if (cb) {
        if (nFormat != -1) {
          if (lpszMarker) {
            charmemset(&lpszMarker[nResult], INDENTCHAR,
                       sizeof(TCHAR) * (nFormat + 1));
            toXMLString(&lpszMarker[nResult + nFormat + 1], (LPTSTR)pChild);
            lpszMarker[nResult + nFormat + 1 + cb] = _T('\n');
          }
          nResult += cb + nFormat + 2;
        } else {
          if (lpszMarker)
            toXMLString(&lpszMarker[nResult], (LPTSTR)pChild);
          nResult += cb;
        }
      }
      break;

    // Clear type nodes
    case eNodeClear:
      // "OpenTag"
      cb = (int)LENSTR(((XMLClear*)pChild)->lpszOpenTag);
      if (cb) {
        if (nFormat != -1) {
          if (lpszMarker) {
            charmemset(&lpszMarker[nResult], INDENTCHAR,
                       sizeof(TCHAR) * (nFormat + 1));
            _tcscpy(&lpszMarker[nResult + nFormat + 1],
                    ((XMLClear*)pChild)->lpszOpenTag);
          }
          nResult += cb + nFormat + 1;
        } else {
          if (lpszMarker)
            _tcscpy(&lpszMarker[nResult], ((XMLClear*)pChild)->lpszOpenTag);
          nResult += cb;
        }
      }

      // "OpenTag Value"
      cb = (int)LENSTR(((XMLClear*)pChild)->lpszValue);
      if (cb) {
        if (lpszMarker)
          _tcscpy(&lpszMarker[nResult], ((XMLClear*)pChild)->lpszValue);
        nResult += cb;
      }

      // "OpenTag Value CloseTag"
      cb = (int)LENSTR(((XMLClear*)pChild)->lpszCloseTag);
      if (cb) {
        if (lpszMarker)
          _tcscpy(&lpszMarker[nResult], ((XMLClear*)pChild)->lpszCloseTag);
        nResult += cb;
      }

      if (nFormat != -1) {
        if (lpszMarker)
          lpszMarker[nResult] = _T('\n');
        nResult++;
      }
      break;

      // Element nodes
    case eNodeChild:

      // Recursively add child nodes
      nResult += CreateXMLStringR((XMLNodeData*)pChild,
                                  lpszMarker ? lpszMarker + nResult : 0,
                                  nChildFormat);
      break;

    default:
      break;
    }
  }

  if ((cbElement) && (!pEntry->isDeclaration)) {
    // If we have child entries we need to use long XML notation for
    // closing the element - "<elementname>blah blah blah</elementname>"
    if (bHasChildren) {
      // "</elementname>\0"
      if (lpszMarker) {
        if (nFormat != -1) {
          if (nFormat) {
            charmemset(&lpszMarker[nResult], INDENTCHAR, sizeof(TCHAR)
                * nFormat);
            nResult += nFormat;
          }
        }

        _tcscpy(&lpszMarker[nResult], _T("</"));
        nResult += 2;
        _tcscpy(&lpszMarker[nResult], pEntry->lpszName);
        nResult += cbElement;

        if (nFormat == -1) {
          _tcscpy(&lpszMarker[nResult], _T(">"));
          nResult++;
        } else {
          _tcscpy(&lpszMarker[nResult], _T(">\n"));
          nResult += 2;
        }
      } else {
        if (nFormat != -1)
          nResult += cbElement + 4 + nFormat;
        else
          nResult += cbElement + 3;
      }
    } else {
      // If there are no children we can use shorthand XML notation -
      // "<elementname/>"
      // "/>\0"
      if (lpszMarker) {
        if (nFormat == -1) {
          _tcscpy(&lpszMarker[nResult], _T("/>"));
          nResult += 2;
        } else {
          _tcscpy(&lpszMarker[nResult], _T("/>\n"));
          nResult += 3;
        }
      } else {
        nResult += nFormat == -1 ? 2 : 3;
      }
    }
  }

  return nResult;
}

#undef LENSTR

// Create an XML string from the head element.
// @param       XMLElement * pHead      - head element
// @param       int nFormat             - 0 if no formatting is required
//                                        otherwise nonzero for formatted text
//                                        with carriage returns and indentation.
// @param       int *pnSize             - [out] pointer to the size of the
//                                        returned string not including the
//                                        NULL terminator.
//
// @return      LPTSTR                  - Allocated XML string, you must free
//                                        this with free().
LPTSTR
XMLNode::createXMLString(int nFormat, int *pnSize)
{
  if (!d) {
    if (pnSize)
      *pnSize = 0;
    return NULL;
  }

  LPTSTR lpszResult = NULL;
  int cbStr;

  // Recursively Calculate the size of the XML string
  nFormat = nFormat ? 0 : -1;
  cbStr = CreateXMLStringR(d, 0, nFormat);
  assert(cbStr);
  // Alllocate memory for the XML string + the NULL terminator and
  // create the recursively XML string.
  lpszResult = (LPTSTR)malloc((cbStr + 1) * sizeof(TCHAR));
  assert(lpszResult);
  CreateXMLStringR(d, lpszResult, nFormat);
  if (pnSize)
    *pnSize = cbStr;
  return lpszResult;
}

XMLNode::~XMLNode()
{
  destroyCurrentBuffer(d);
}

void
XMLNode::destroyCurrentBuffer(XMLNodeData *d)
{
  if (!d)
    return;

  (d->ref_count)--;

  if (d->ref_count == 0) {
    int i = 0;

    if (d->pParent) {
      XMLNode *pa = d->pParent->d->pChild;
      while (((void*)(pa[i].d)) != ((void*)d))
        i++;
      d->pParent->d->nChild--;
      memmove(pa + i, pa + i + 1, (d->pParent->d->nChild - i) * sizeof(XMLNode));
      removeOrderElement(d->pParent->d, eNodeChild, i);
    }

    for (i = 0; i < d->nChild; i++) {
      d->pChild[i].d->pParent = NULL;
      destroyCurrentBuffer(d->pChild[i].d);
    }
    free(d->pChild);
    for (i = 0; i < d->nText; i++)
      free((void*)d->pText[i]);
    free(d->pText);
    for (i = 0; i < d->nClear; i++)
      free((void*)d->pClear[i].lpszValue);
    free(d->pClear);
    for (i = 0; i < d->nAttribute; i++) {
      free((void*)d->pAttribute[i].lpszName);
      if (d->pAttribute[i].lpszValue)
        free((void*)d->pAttribute[i].lpszValue);
    }
    free(d->pAttribute);
    free(d->pOrder);
    free((void*)d->lpszName);
    free(d);
  }
}

XMLNode&
XMLNode::operator=(const XMLNode& A)
{
  // shallow copy
  if (this != &A) {
    destroyCurrentBuffer(d);
    d = A.d;
    if (d)
      (d->ref_count)++;
  }
  return *this;
}

XMLNode::XMLNode(const XMLNode &A)
{
  // shallow copy
  d = A.d;
  if (d)
    (d->ref_count)++;
}

int
XMLNode::nChildNode(LPCTSTR name) const
{
  if (!d)
    return 0;

  int i, j = 0, n = d->nChild;
  XMLNode *pc = d->pChild;
  for (i = 0; i < n; i++) {
    if (_tcsicmp(pc->d->lpszName, name) == 0)
      j++;
    pc++;
  }

  return j;
}

XMLNode
XMLNode::getChildNode(LPCTSTR name, int *j)
{
  if (!d)
    return emptyXMLNode;

  int i = 0, n = d->nChild;
  if (j)
    i = *j;
  XMLNode *pc = d->pChild + i;
  for (; i < n; i++) {
    if (_tcsicmp(pc->d->lpszName, name) == 0) {
      if (j)
        *j = i + 1;
      return *pc;
    }
    pc++;
  }

  return emptyXMLNode;
}

XMLNode
XMLNode::getChildNode(LPCTSTR name, int j)
{
  if (!d)
    return emptyXMLNode;

  int i = 0;
  while (j-- > 0)
    getChildNode(name, &i);

  return getChildNode(name, &i);
}

// Find an attribute on an node.
LPCTSTR XMLNode::getAttribute(LPCTSTR lpszAttrib, int *j) const
{
  if (!d)
    return NULL;

  int i = 0, n = d->nAttribute;
  if (j)
    i = *j;

  XMLAttribute *pAttr = d->pAttribute + i;
  for (; i < n; i++) {
    if (_tcsicmp(pAttr->lpszName, lpszAttrib) == 0) {
      if (j)
        *j = i + 1;
      return pAttr->lpszValue;
    }
    pAttr++;
  }

  return NULL;
}

char
XMLNode::isAttributeSet(LPCTSTR lpszAttrib) const
{
  if (!d)
    return FALSE;

  int i, n = d->nAttribute;
  XMLAttribute *pAttr = d->pAttribute;
  for (i = 0; i < n; i++) {
    if (_tcsicmp(pAttr->lpszName, lpszAttrib) == 0) {
      return TRUE;
    }
    pAttr++;
  }

  return FALSE;
}

LPCTSTR XMLNode::getAttribute(LPCTSTR name, int j) const
{
  if (!d)
    return NULL;

  int i = 0;
  while (j-- > 0)
    getAttribute(name, &i);

  return getAttribute(name, &i);
}

LPCTSTR
XMLNode::getName() const
{
  if (!d)
    return NULL;

  return d->lpszName;
}

int
XMLNode::nText() const
{
  if (!d)
    return 0;

  return d->nText;
}

int
XMLNode::nChildNode() const
{
  if (!d)
    return 0;

  return d->nChild;
}

int
XMLNode::nAttribute() const
{
  if (!d)
    return 0;

  return d->nAttribute;
}

int
XMLNode::nClear() const
{
  if (!d)
    return 0;

  return d->nClear;
}

XMLClear
XMLNode::getClear(int i)
{
  if (!d)
    return emptyXMLClear;
  if (i >= d->nClear)
    return emptyXMLClear;

  return d->pClear[i];
}

XMLAttribute
XMLNode::getAttribute(int i)
{
  if (!d)
    return emptyXMLAttribute;
  if (i >= d->nAttribute)
    return emptyXMLAttribute;

  return d->pAttribute[i];
}

LPCTSTR
XMLNode::getText(int i) const
{
  if (!d)
    return NULL;
  if (i >= d->nText)
    return NULL;

  return d->pText[i];
}

XMLNode
XMLNode::getChildNode(int i)
{
  if (!d)
    return emptyXMLNode;
  if (i >= d->nChild)
    return emptyXMLNode;

  return d->pChild[i];
}

char
XMLNode::isDeclaration()
{
  if (!d)
    return (char)0;

  return d->isDeclaration;
}

char
XMLNode::isEmpty()
{
  return (d == NULL);
}

int
XMLNode::nElement()
{
  if (!d)
    return 0;

  return d->nChild + d->nText + d->nClear + d->nAttribute;
}
Back to Top