File: mxml-file.c

package info (click to toggle)
mxml 4.0.4-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,672 kB
  • sloc: ansic: 4,246; sh: 3,389; makefile: 522; cpp: 178; xml: 56
file content (2275 lines) | stat: -rw-r--r-- 61,224 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
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
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
//
// File loading code for Mini-XML, a small XML file parsing library.
//
// https://www.msweet.org/mxml
//
// Copyright © 2003-2024 by Michael R Sweet.
//
// Licensed under Apache License v2.0.  See the file "LICENSE" for more
// information.
//

#ifndef _WIN32
#  include <unistd.h>
#endif // !_WIN32
#include "mxml-private.h"


//
// Local types...
//

typedef enum _mxml_encoding_e		// Character encoding
{
  _MXML_ENCODING_UTF8,			// UTF-8
  _MXML_ENCODING_UTF16BE,		// UTF-16 Big-Endian
  _MXML_ENCODING_UTF16LE		// UTF-16 Little-Endian
} _mxml_encoding_t;

typedef struct _mxml_stringbuf_s	// String buffer
{
  char		*buffer,		// Buffer
		*bufptr;		// Pointer into buffer
  size_t	bufsize;		// Size of buffer
  bool		bufalloc;		// Allocate buffer?
} _mxml_stringbuf_t;


//
// Macro to test for a bad XML character...
//

#define mxml_bad_char(ch) ((ch) < ' ' && (ch) != '\n' && (ch) != '\r' && (ch) != '\t')


//
// Local functions...
//

static bool		mxml_add_char(mxml_options_t *options, int ch, char **ptr, char **buffer, size_t *bufsize);
static int		mxml_get_entity(mxml_options_t *options, mxml_io_cb_t io_cb, void *io_cbdata, _mxml_encoding_t *encoding, mxml_node_t *parent, int *line);
static int		mxml_getc(mxml_options_t *options, mxml_io_cb_t io_cb, void *io_cbdata, _mxml_encoding_t *encoding);
static inline int	mxml_isspace(int ch)
			{
			  return (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n');
			}
static mxml_node_t	*mxml_load_data(mxml_node_t *top, mxml_options_t *options, mxml_io_cb_t io_cb, void *io_cbdata);
static int		mxml_parse_element(mxml_options_t *options, mxml_io_cb_t io_cb, void *io_cbdata, mxml_node_t *node, _mxml_encoding_t *encoding, int *line);
static size_t		mxml_read_cb_fd(int *fd, void *buffer, size_t bytes);
static size_t		mxml_read_cb_file(FILE *fp, void *buffer, size_t bytes);
static size_t		mxml_read_cb_string(_mxml_stringbuf_t *sb, void *buffer, size_t bytes);
static double		mxml_strtod(mxml_options_t *options, const char *buffer, char **bufptr);
static size_t		mxml_io_cb_fd(int *fd, void *buffer, size_t bytes);
static size_t		mxml_io_cb_file(FILE *fp, void *buffer, size_t bytes);
static size_t		mxml_io_cb_string(_mxml_stringbuf_t *sb, void *buffer, size_t bytes);
static int		mxml_write_node(mxml_node_t *node, mxml_options_t *options, mxml_io_cb_t io_cb, void *io_cbdata, int col);
static int		mxml_write_string(const char *s, mxml_io_cb_t io_cb, void *io_cbdata, bool use_entities, int col);
static int		mxml_write_ws(mxml_node_t *node, mxml_options_t *options, mxml_io_cb_t io_cb, void *io_cbdata, mxml_ws_t ws, int col);


//
// 'mxmlLoadFd()' - Load a file descriptor into an XML node tree.
//
// This function loads the file descriptor `fd` into an XML node tree.  The
// nodes in the specified file are added to the specified node `top` - if `NULL`
// the XML file MUST be well-formed with a single parent processing instruction
// node like `<?xml version="1.0"?>` at the start of the file.
//
// Load options are provides via the `options` argument.  If `NULL`, all values
// will be loaded into `MXML_TYPE_TEXT` nodes.  Use the @link mxmlOptionsNew@
// function to create options when loading XML data.
//

mxml_node_t *				// O - First node or `NULL` if the file could not be read.
mxmlLoadFd(
    mxml_node_t    *top,		// I - Top node
    mxml_options_t *options,		// I - Options
    int            fd)			// I - File descriptor to read from
{
  // Range check input...
  if (fd < 0)
    return (NULL);

  // Read the XML data...
  return (mxml_load_data(top, options, (mxml_io_cb_t)mxml_read_cb_fd, &fd));
}


//
// 'mxmlLoadFile()' - Load a file into an XML node tree.
//
// This function loads the `FILE` pointer `fp` into an XML node tree.  The
// nodes in the specified file are added to the specified node `top` - if `NULL`
// the XML file MUST be well-formed with a single parent processing instruction
// node like `<?xml version="1.0"?>` at the start of the file.
//
// Load options are provides via the `options` argument.  If `NULL`, all values
// will be loaded into `MXML_TYPE_TEXT` nodes.  Use the @link mxmlOptionsNew@
// function to create options when loading XML data.
//

mxml_node_t *				// O - First node or `NULL` if the file could not be read.
mxmlLoadFile(
    mxml_node_t    *top,		// I - Top node
    mxml_options_t *options,		// I - Options
    FILE           *fp)			// I - File to read from
{
  // Range check input...
  if (!fp)
    return (NULL);

  // Read the XML data...
  return (mxml_load_data(top, options, (mxml_io_cb_t)mxml_read_cb_file, fp));
}


//
// 'mxmlLoadFilename()' - Load a file into an XML node tree.
//
// This function loads the named file `filename` into an XML node tree.  The
// nodes in the specified file are added to the specified node `top` - if `NULL`
// the XML file MUST be well-formed with a single parent processing instruction
// node like `<?xml version="1.0"?>` at the start of the file.
//
// Load options are provides via the `options` argument.  If `NULL`, all values
// will be loaded into `MXML_TYPE_TEXT` nodes.  Use the @link mxmlOptionsNew@
// function to create options when loading XML data.
//

mxml_node_t *				// O - First node or `NULL` if the file could not be read.
mxmlLoadFilename(
    mxml_node_t    *top,		// I - Top node
    mxml_options_t *options,		// I - Options
    const char     *filename)		// I - File to read from
{
  FILE		*fp;			// File pointer
  mxml_node_t	*ret;			// Node


  // Range check input...
  if (!filename)
    return (NULL);

  // Open the file...
  if ((fp = fopen(filename, "r")) == NULL)
    return (NULL);

  // Read the XML data...
  ret = mxml_load_data(top, options, (mxml_io_cb_t)mxml_read_cb_file, fp);

  // Close the file and return...
  fclose(fp);

  return (ret);
}


//
// 'mxmlLoadIO()' - Load an XML node tree using a read callback.
//
// This function loads data into an XML node tree using a read callback.  The
// nodes in the specified file are added to the specified node `top` - if `NULL`
// the XML file MUST be well-formed with a single parent processing instruction
// node like `<?xml version="1.0"?>` at the start of the file.
//
// Load options are provides via the `options` argument.  If `NULL`, all values
// will be loaded into `MXML_TYPE_TEXT` nodes.  Use the @link mxmlOptionsNew@
// function to create options when loading XML data.
//
// The read callback function `io_cb` is called to read a number of bytes from
// the source.  The callback data pointer `io_cbdata` is passed to the read
// callback with a pointer to a buffer and the maximum number of bytes to read,
// for example:
//
// ```c
// size_t my_io_cb(void *cbdata, void *buffer, size_t bytes)
// {
//   ... copy up to "bytes" bytes into buffer ...
//   ... return the number of bytes "read" or 0 on error ...
// }
// ```
//

mxml_node_t *				// O - First node or `NULL` if the file could not be read.
mxmlLoadIO(
    mxml_node_t    *top,		// I - Top node
    mxml_options_t *options,		// I - Options
    mxml_io_cb_t   io_cb,		// I - Read callback function
    void           *io_cbdata)		// I - Read callback data
{
  // Range check input...
  if (!io_cb)
    return (NULL);

  // Read the XML data...
  return (mxml_load_data(top, options, io_cb, io_cbdata));
}


//
// 'mxmlLoadString()' - Load a string into an XML node tree.
//
// This function loads the string into an XML node tree.  The nodes in the
// specified file are added to the specified node `top` - if `NULL` the XML file
// MUST be well-formed with a single parent processing instruction node like
// `<?xml version="1.0"?>` at the start of the file.
//
// Load options are provides via the `options` argument.  If `NULL`, all values
// will be loaded into `MXML_TYPE_TEXT` nodes.  Use the @link mxmlOptionsNew@
// function to create options when loading XML data.
//

mxml_node_t *				// O - First node or `NULL` if the string has errors.
mxmlLoadString(
    mxml_node_t    *top,		// I - Top node
    mxml_options_t *options,		// I - Options
    const char     *s)			// I - String to load
{
  _mxml_stringbuf_t	sb;		// String buffer


  // Range check input...
  if (!s)
    return (NULL);

  // Setup string buffer...
  sb.buffer   = (char *)s;
  sb.bufptr   = (char *)s;
  sb.bufsize  = strlen(s);
  sb.bufalloc = false;

  // Read the XML data...
  return (mxml_load_data(top, options, (mxml_io_cb_t)mxml_read_cb_string, &sb));
}


//
// 'mxmlSaveAllocString()' - Save an XML tree to an allocated string.
//
// This function saves the XML tree `node` to an allocated string.  The string
// should be freed using `free` (or the string free callback set using
// @link mxmlSetStringCallbacks@) when you are done with it.
//
// `NULL` is returned if the node would produce an empty string or if the string
// cannot be allocated.
//
// Save options are provides via the `options` argument.  If `NULL`, the XML
// output will be wrapped at column 72 with no additional whitespace.  Use the
// @link mxmlOptionsNew@ function to create options for saving XML data.
//

char *					// O - Allocated string or `NULL`
mxmlSaveAllocString(
    mxml_node_t    *node,		// I - Node to write
    mxml_options_t *options)		// I - Options
{
  _mxml_stringbuf_t	sb;		// String buffer


  // Setup a string buffer
  if ((sb.buffer = malloc(1024)) == NULL)
    return (NULL);

  sb.bufptr   = sb.buffer;
  sb.bufsize  = 1024;
  sb.bufalloc = true;

  // Write the top node...
  if (mxml_write_node(node, options, (mxml_io_cb_t)mxml_io_cb_string, &sb, 0) < 0)
  {
    free(sb.buffer);
    return (NULL);
  }

  // Nul-terminate the string...
  *(sb.bufptr) = '\0';

  // Return the allocated string...
  return (sb.buffer);
}


//
// 'mxmlSaveFd()' - Save an XML tree to a file descriptor.
//
// This function saves the XML tree `node` to a file descriptor.
//
// Save options are provides via the `options` argument.  If `NULL`, the XML
// output will be wrapped at column 72 with no additional whitespace.  Use the
// @link mxmlOptionsNew@ function to create options for saving XML data.
//

bool					// O - `true` on success, `false` on error.
mxmlSaveFd(mxml_node_t    *node,	// I - Node to write
           mxml_options_t *options,	// I - Options
           int            fd)		// I - File descriptor to write to
{
  int		col;			// Final column


  // Write the node...
  if ((col = mxml_write_node(node, options, (mxml_io_cb_t)mxml_io_cb_fd, &fd, 0)) < 0)
    return (false);

  // Make sure the file ends with a newline...
  if (col > 0)
  {
    if (write(fd, "\n", 1) < 0)
      return (false);
  }

  return (true);
}


//
// 'mxmlSaveFile()' - Save an XML tree to a file.
//
// This function saves the XML tree `node` to a stdio `FILE`.
//
// Save options are provides via the `options` argument.  If `NULL`, the XML
// output will be wrapped at column 72 with no additional whitespace.  Use the
// @link mxmlOptionsNew@ function to create options for saving XML data.
//

bool					// O - `true` on success, `false` on error.
mxmlSaveFile(
    mxml_node_t    *node,		// I - Node to write
    mxml_options_t *options,		// I - Options
    FILE           *fp)			// I - File to write to
{
  int		col;			// Final column


  // Write the node...
  if ((col = mxml_write_node(node, options, (mxml_io_cb_t)mxml_io_cb_file, fp, 0)) < 0)
    return (false);

  // Make sure the file ends with a newline...
  if (col > 0)
  {
    if (putc('\n', fp) < 0)
      return (false);
  }

  return (true);
}


//
// 'mxmlSaveFilename()' - Save an XML tree to a file.
//
// This function saves the XML tree `node` to a named file.
//
// Save options are provides via the `options` argument.  If `NULL`, the XML
// output will be wrapped at column 72 with no additional whitespace.  Use the
// @link mxmlOptionsNew@ function to create options for saving XML data.
//

bool					// O - `true` on success, `false` on error.
mxmlSaveFilename(
    mxml_node_t    *node,		// I - Node to write
    mxml_options_t *options,		// I - Options
    const char     *filename)		// I - File to write to
{
  bool		ret = true;		// Return value
  FILE		*fp;			// File pointer
  int		col;			// Final column


  // Open the file...
  if ((fp = fopen(filename, "w")) == NULL)
    return (false);

  // Write the node...
  if ((col = mxml_write_node(node, options, (mxml_io_cb_t)mxml_io_cb_file, fp, 0)) < 0)
  {
    ret = false;
  }
  else if (col > 0)
  {
    // Make sure the file ends with a newline...
    if (putc('\n', fp) < 0)
      ret = false;
  }

  fclose(fp);

  return (ret);
}


//
// 'mxmlSaveIO()' - Save an XML tree using a callback.
//
// This function saves the XML tree `node` using a write callback function
// `io_cb`.  The write callback is called with the callback data pointer
// `io_cbdata`, a buffer pointer, and the number of bytes to write, for
// example:
//
// ```c
// size_t my_io_cb(void *cbdata, const void *buffer, size_t bytes)
// {
//   ... write/copy bytes from buffer to the output ...
//   ... return the number of bytes written/copied or 0 on error ...
// }
// ```
//
// Save options are provides via the `options` argument.  If `NULL`, the XML
// output will be wrapped at column 72 with no additional whitespace.  Use the
// @link mxmlOptionsNew@ function to create options for saving XML data.
//

bool					// O - `true` on success, `false` on error.
mxmlSaveIO(
    mxml_node_t    *node,		// I - Node to write
    mxml_options_t *options,		// I - Options
    mxml_io_cb_t   io_cb,		// I - Write callback function
    void           *io_cbdata)		// I - Write callback data
{
  int		col;			// Final column


  // Range check input...
  if (!node || !io_cb)
    return (false);

  // Write the node...
  if ((col = mxml_write_node(node, options, io_cb, io_cbdata, 0)) < 0)
    return (false);

  if (col > 0)
  {
    // Make sure the file ends with a newline...
    if ((io_cb)(io_cbdata, "\n", 1) != 1)
      return (false);
  }

  return (true);
}


//
// 'mxmlSaveString()' - Save an XML node tree to a string.
//
// This function saves the XML tree `node` to a fixed-size string buffer.
//
// Save options are provides via the `options` argument.  If `NULL`, the XML
// output will be wrapped at column 72 with no additional whitespace.  Use the
// @link mxmlOptionsNew@ function to create options for saving XML data.
//

size_t					// O - Size of string
mxmlSaveString(
    mxml_node_t    *node,		// I - Node to write
    mxml_options_t *options,		// I - Options
    char           *buffer,		// I - String buffer
    size_t         bufsize)		// I - Size of string buffer
{
  _mxml_stringbuf_t	sb;		// String buffer


  // Setup the string buffer...
  sb.buffer   = buffer;
  sb.bufptr   = buffer;
  sb.bufsize  = bufsize;
  sb.bufalloc = false;

  // Write the node...
  if (mxml_write_node(node, options, (mxml_io_cb_t)mxml_io_cb_string, &sb, 0) < 0)
    return (false);

  // Nul-terminate the string...
  if (sb.bufptr < (sb.buffer + sb.bufsize))
    *(sb.bufptr) = '\0';

  // Return the number of characters...
  return ((size_t)(sb.bufptr - sb.buffer));
}


//
// 'mxml_add_char()' - Add a character to a buffer, expanding as needed.
//

static bool				// O  - `true` on success, `false` on error
mxml_add_char(mxml_options_t *options,	// I - Options
              int            ch,	// I  - Character to add
              char           **bufptr,	// IO - Current position in buffer
	      char           **buffer,	// IO - Current buffer
	      size_t         *bufsize)	// IO - Current buffer size
{
  char	*newbuffer;			// New buffer value


  if (*bufptr >= (*buffer + *bufsize - 4))
  {
    // Increase the size of the buffer...
    if (*bufsize < 1024)
      (*bufsize) *= 2;
    else
      (*bufsize) += 1024;

    if ((newbuffer = realloc(*buffer, *bufsize)) == NULL)
    {
      _mxml_error(options, "Unable to expand string buffer to %lu bytes.", (unsigned long)*bufsize);

      return (false);
    }

    *bufptr = newbuffer + (*bufptr - *buffer);
    *buffer = newbuffer;
  }

  if (ch < 0x80)
  {
    // Single byte ASCII...
    *(*bufptr)++ = ch;
  }
  else if (ch < 0x800)
  {
    // Two-byte UTF-8...
    *(*bufptr)++ = 0xc0 | (ch >> 6);
    *(*bufptr)++ = 0x80 | (ch & 0x3f);
  }
  else if (ch < 0x10000)
  {
    // Three-byte UTF-8...
    *(*bufptr)++ = 0xe0 | (ch >> 12);
    *(*bufptr)++ = 0x80 | ((ch >> 6) & 0x3f);
    *(*bufptr)++ = 0x80 | (ch & 0x3f);
  }
  else
  {
    // Four-byte UTF-8...
    *(*bufptr)++ = 0xf0 | (ch >> 18);
    *(*bufptr)++ = 0x80 | ((ch >> 12) & 0x3f);
    *(*bufptr)++ = 0x80 | ((ch >> 6) & 0x3f);
    *(*bufptr)++ = 0x80 | (ch & 0x3f);
  }

  return (true);
}


//
// 'mxml_get_entity()' - Get the character corresponding to an entity...
//

static int				// O  - Character value or `EOF` on error
mxml_get_entity(
    mxml_options_t   *options,		// I  - Options
    mxml_io_cb_t     io_cb,		// I  - Read callback function
    void             *io_cbdata,	// I  - Read callback data
    _mxml_encoding_t *encoding,		// IO - Character encoding
    mxml_node_t      *parent,		// I  - Parent node
    int              *line)		// IO - Current line number
{
  int	ch;				// Current character
  char	entity[64],			// Entity string
	*entptr;			// Pointer into entity


  // Read a HTML character entity of the form "&NAME;", "&#NUMBER;", or "&#xHEX"...
  entptr = entity;

  while ((ch = mxml_getc(options, io_cb, io_cbdata, encoding)) != EOF)
  {
    if (ch > 126 || (!isalnum(ch) && ch != '#'))
    {
      break;
    }
    else if (entptr < (entity + sizeof(entity) - 1))
    {
      *entptr++ = ch;
    }
    else
    {
      _mxml_error(options, "Entity name too long under parent <%s> on line %d.", mxmlGetElement(parent), *line);
      break;
    }
  }

  *entptr = '\0';

  if (ch != ';')
  {
    _mxml_error(options, "Character entity '%s' not terminated under parent <%s> on line %d.", entity, mxmlGetElement(parent), *line);

    if (ch == '\n')
      (*line)++;

    return (EOF);
  }

  if ((ch = _mxml_entity_value(options, entity)) < 0)
  {
    _mxml_error(options, "Entity '&%s;' not supported under parent <%s> on line %d.", entity, mxmlGetElement(parent), *line);
    return (EOF);
  }

  if (mxml_bad_char(ch))
  {
    _mxml_error(options, "Bad control character 0x%02x under parent <%s> on line %d not allowed by XML standard.", ch, mxmlGetElement(parent), *line);
    return (EOF);
  }

  return (ch);
}


//
// 'mxml_getc()' - Read a character from a file descriptor.
//

static int				// O  - Character or `EOF`
mxml_getc(mxml_options_t   *options,	// I  - Options
          mxml_io_cb_t     io_cb,	// I  - Read callback function
          void             *io_cbdata,	// I  - Read callback data
          _mxml_encoding_t *encoding)	// IO - Encoding
{
  int		ch;			// Current character
  unsigned char	buffer[4];		// Read buffer


  // Grab the next character...
  read_first_byte:

  if ((io_cb)(io_cbdata, buffer, 1) != 1)
    return (EOF);

  ch = buffer[0];

  switch (*encoding)
  {
    case _MXML_ENCODING_UTF8 :
        // Got a UTF-8 character; convert UTF-8 to Unicode and return...
	if (!(ch & 0x80))
	{
	  // ASCII
	  break;
        }
	else if (ch == 0xfe)
	{
	  // UTF-16 big-endian BOM?
	  if ((io_cb)(io_cbdata, buffer + 1, 1) != 1)
	    return (EOF);

	  if (buffer[1] != 0xff)
	    return (EOF);

          // Yes, switch to UTF-16 BE and try reading again...
	  *encoding = _MXML_ENCODING_UTF16BE;

	  goto read_first_byte;
	}
	else if (ch == 0xff)
	{
	  // UTF-16 little-endian BOM?
	  if ((io_cb)(io_cbdata, buffer + 1, 1) != 1)
	    return (EOF);

	  if (buffer[1] != 0xfe)
	    return (EOF);

          // Yes, switch to UTF-16 LE and try reading again...
	  *encoding = _MXML_ENCODING_UTF16LE;

	  goto read_first_byte;
	}
	else if ((ch & 0xe0) == 0xc0)
	{
	  // Two-byte value...
	  if ((io_cb)(io_cbdata, buffer + 1, 1) != 1)
	    return (EOF);

	  if ((buffer[1] & 0xc0) != 0x80)
	    return (EOF);

	  ch = ((ch & 0x1f) << 6) | (buffer[1] & 0x3f);

	  if (ch < 0x80)
	  {
	    _mxml_error(options, "Invalid UTF-8 sequence for character 0x%04x.", ch);
	    return (EOF);
	  }
	}
	else if ((ch & 0xf0) == 0xe0)
	{
	  // Three-byte value...
	  if ((io_cb)(io_cbdata, buffer + 1, 2) != 2)
	    return (EOF);

	  if ((buffer[1] & 0xc0) != 0x80 || (buffer[2] & 0xc0) != 0x80)
	    return (EOF);

	  ch = ((ch & 0x0f) << 12) | ((buffer[1] & 0x3f) << 6) | (buffer[2] & 0x3f);

	  if (ch < 0x800)
	  {
	    _mxml_error(options, "Invalid UTF-8 sequence for character 0x%04x.", ch);
	    return (EOF);
	  }

          // Ignore (strip) Byte Order Mark (BOM)...
	  if (ch == 0xfeff)
	    goto read_first_byte;
	}
	else if ((ch & 0xf8) == 0xf0)
	{
	  // Four-byte value...
	  if ((io_cb)(io_cbdata, buffer + 1, 3) != 3)
	    return (EOF);

	  if ((buffer[1] & 0xc0) != 0x80 || (buffer[2] & 0xc0) != 0x80 || (buffer[3] & 0xc0) != 0x80)
	    return (EOF);

	  ch = ((ch & 0x07) << 18) | ((buffer[1] & 0x3f) << 12) | ((buffer[2] & 0x3f) << 6) | (buffer[3] & 0x3f);

	  if (ch < 0x10000)
	  {
	    _mxml_error(options, "Invalid UTF-8 sequence for character 0x%04x.", ch);
	    return (EOF);
	  }
	}
	else
	{
	  return (EOF);
	}
	break;

    case _MXML_ENCODING_UTF16BE :
        // Read UTF-16 big-endian char...
	if ((io_cb)(io_cbdata, buffer + 1, 1) != 1)
	  return (EOF);

	ch = (ch << 8) | buffer[1];

        if (ch >= 0xd800 && ch <= 0xdbff)
	{
	  // Multi-word UTF-16 char...
          int lch;			// Lower bits

	  if ((io_cb)(io_cbdata, buffer + 2, 2) != 2)
	    return (EOF);

	  lch = (buffer[2] << 8) | buffer[3];

          if (lch < 0xdc00 || lch >= 0xdfff)
	    return (EOF);

          ch = (((ch & 0x3ff) << 10) | (lch & 0x3ff)) + 0x10000;
	}
	break;

    case _MXML_ENCODING_UTF16LE :
        // Read UTF-16 little-endian char...
	if ((io_cb)(io_cbdata, buffer + 1, 1) != 1)
	  return (EOF);

	ch |= buffer[1] << 8;

        if (ch >= 0xd800 && ch <= 0xdbff)
	{
	  // Multi-word UTF-16 char...
          int lch;			// Lower bits

	  if ((io_cb)(io_cbdata, buffer + 2, 2) != 2)
	    return (EOF);

	  lch = (buffer[3] << 8) | buffer[2];

          if (lch < 0xdc00 || lch >= 0xdfff)
	    return (EOF);

          ch = (((ch & 0x3ff) << 10) | (lch & 0x3ff)) + 0x10000;
	}
	break;
  }

  if (mxml_bad_char(ch))
  {
    _mxml_error(options, "Bad control character 0x%02x not allowed by XML standard.", ch);
    return (EOF);
  }

  return (ch);
}


//
// 'mxml_load_data()' - Load data into an XML node tree.
//

static mxml_node_t *			// O - First node or `NULL` if the XML could not be read.
mxml_load_data(
    mxml_node_t     *top,		// I - Top node
    mxml_options_t  *options,		// I - Options
    mxml_io_cb_t    io_cb,		// I - Read callback function
    void            *io_cbdata)		// I - Read callback data
{
  mxml_node_t	*node = NULL,		// Current node
		*first = NULL,		// First node added
		*parent = NULL;		// Current parent node
  int		line = 1,		// Current line number
		ch;			// Character from file
  bool		whitespace = false;	// Whitespace seen?
  char		*buffer,		// String buffer
		*bufptr;		// Pointer into buffer
  size_t	bufsize;		// Size of buffer
  mxml_type_t	type;			// Current node type
  _mxml_encoding_t encoding = _MXML_ENCODING_UTF8;
					// Character encoding
  static const char * const types[] =	// Type strings...
		{
		  "MXML_TYPE_CDATA",	// CDATA
		  "MXML_TYPE_COMMENT",	// Comment
		  "MXML_TYPE_DECLARATION",// Declaration
		  "MXML_TYPE_DIRECTIVE",// Processing instruction/directive
		  "MXML_TYPE_ELEMENT",	// XML element with attributes
		  "MXML_TYPE_INTEGER",	// Integer value
		  "MXML_TYPE_OPAQUE",	// Opaque string
		  "MXML_TYPE_REAL",	// Real value
		  "MXML_TYPE_TEXT",	// Text fragment
		  "MXML_TYPE_CUSTOM"	// Custom data
		};


  // Read elements and other nodes from the file...
  if ((buffer = malloc(64)) == NULL)
  {
    _mxml_error(options, "Unable to allocate string buffer.");
    return (NULL);
  }

  bufsize    = 64;
  bufptr     = buffer;
  parent     = top;
  first      = NULL;

  if (options && options->type_cb && parent)
    type = (options->type_cb)(options->type_cbdata, parent);
  else if (options && !options->type_cb)
    type = options->type_value;
  else
    type = MXML_TYPE_IGNORE;

  if ((ch = mxml_getc(options, io_cb, io_cbdata, &encoding)) == EOF)
  {
    free(buffer);
    return (NULL);
  }
  else if (ch != '<' && !top)
  {
    free(buffer);
    _mxml_error(options, "XML does not start with '<' (saw '%c').", ch);
    return (NULL);
  }

  do
  {
    if ((ch == '<' || (mxml_isspace(ch) && type != MXML_TYPE_OPAQUE && type != MXML_TYPE_CUSTOM)) && bufptr > buffer)
    {
      // Add a new value node...
      *bufptr = '\0';

      switch (type)
      {
	case MXML_TYPE_INTEGER :
            node = mxmlNewInteger(parent, strtol(buffer, &bufptr, 0));
	    break;

	case MXML_TYPE_OPAQUE :
            node = mxmlNewOpaque(parent, buffer);
	    break;

	case MXML_TYPE_REAL :
            node = mxmlNewReal(parent, mxml_strtod(options, buffer, &bufptr));
	    break;

	case MXML_TYPE_TEXT :
            node = mxmlNewText(parent, whitespace, buffer);
	    break;

	case MXML_TYPE_CUSTOM :
	    if (options && options->custload_cb)
	    {
	      // Use the callback to fill in the custom data...
              node = mxmlNewCustom(parent, /*data*/NULL, /*free_cb*/NULL, /*free_cbdata*/NULL);

	      if (!(options->custload_cb)(options->cust_cbdata, node, buffer))
	      {
	        _mxml_error(options, "Bad custom value '%s' in parent <%s> on line %d.", buffer, parent ? parent->value.element.name : "null", line);
		mxmlDelete(node);
		node = NULL;
	      }
	      break;
	    }

        default : // Ignore...
	    node = NULL;
	    break;
      }

      if (*bufptr)
      {
        // Bad integer/real number value...
        _mxml_error(options, "Bad %s value '%s' in parent <%s> on line %d.", type == MXML_TYPE_INTEGER ? "integer" : "real", buffer, parent ? parent->value.element.name : "null", line);
	break;
      }

      MXML_DEBUG("mxml_load_data: node=%p(%s), parent=%p\n", node, buffer, parent);

      bufptr     = buffer;
      whitespace = mxml_isspace(ch) && type == MXML_TYPE_TEXT;

      if (!node && type != MXML_TYPE_IGNORE)
      {
        // Print error and return...
	_mxml_error(options, "Unable to add value node of type %s to parent <%s> on line %d.", types[type], parent ? parent->value.element.name : "null", line);
	goto error;
      }

      if (options && options->sax_cb)
      {
        if (!(options->sax_cb)(options->sax_cbdata, node, MXML_SAX_EVENT_DATA))
          goto error;

        if (!mxmlRelease(node))
          node = NULL;
      }

      if (!first && node)
        first = node;
    }
    else if (mxml_isspace(ch) && type == MXML_TYPE_TEXT)
    {
      whitespace = true;
    }

    if (ch == '\n')
      line ++;

    // Add lone whitespace node if we have an element and existing whitespace...
    if (ch == '<' && whitespace && type == MXML_TYPE_TEXT)
    {
      if (parent)
      {
	node = mxmlNewText(parent, whitespace, "");

	if (options && options->sax_cb)
	{
	  if (!(options->sax_cb)(options->sax_cbdata, node, MXML_SAX_EVENT_DATA))
	    goto error;

	  if (!mxmlRelease(node))
	    node = NULL;
	}

	if (!first && node)
	  first = node;
      }

      whitespace = false;
    }

    if (ch == '<')
    {
      // Start of open/close tag...
      bufptr = buffer;

      while ((ch = mxml_getc(options, io_cb, io_cbdata, &encoding)) != EOF)
      {
        if (mxml_isspace(ch) || ch == '>' || (ch == '/' && bufptr > buffer))
        {
	  break;
	}
	else if (ch == '<')
	{
	  _mxml_error(options, "Bare < in element.");
	  goto error;
	}
	else if (ch == '&')
	{
	  if ((ch = mxml_get_entity(options, io_cb, io_cbdata, &encoding, parent, &line)) == EOF)
	    goto error;

	  if (!mxml_add_char(options, ch, &bufptr, &buffer, &bufsize))
	    goto error;
	}
	else if (ch < '0' && ch != '!' && ch != '-' && ch != '.' && ch != '/')
	{
	  goto error;
	}
	else if (!mxml_add_char(options, ch, &bufptr, &buffer, &bufsize))
	{
	  goto error;
	}
	else if (((bufptr - buffer) == 1 && buffer[0] == '?') || ((bufptr - buffer) == 3 && !strncmp(buffer, "!--", 3)) || ((bufptr - buffer) == 8 && !strncmp(buffer, "![CDATA[", 8)))
	{
	  break;
	}

	if (ch == '\n')
	  line ++;
      }

      *bufptr = '\0';

      if (!strcmp(buffer, "!--"))
      {
        // Gather rest of comment...
	while ((ch = mxml_getc(options, io_cb, io_cbdata, &encoding)) != EOF)
	{
	  if (ch == '>' && bufptr > (buffer + 4) && bufptr[-3] != '-' && bufptr[-2] == '-' && bufptr[-1] == '-')
	    break;
	  else if (!mxml_add_char(options, ch, &bufptr, &buffer, &bufsize))
	    goto error;

	  if (ch == '\n')
	    line ++;
	}

        // Error out if we didn't get the whole comment...
        if (ch != '>')
	{
	  // Print error and return...
	  _mxml_error(options, "Early EOF in comment node on line %d.", line);
	  goto error;
	}

        // Otherwise add this as an element under the current parent...
	bufptr[-2] = '\0';

        if (!parent && first)
	{
	  // There can only be one root element!
	  _mxml_error(options, "<%s--> cannot be a second root node after <%s> on line %d.", buffer, first->value.element.name, line);
          goto error;
	}

	if ((node = mxmlNewComment(parent, buffer + 3)) == NULL)
	{
	  // Just print error for now...
	  _mxml_error(options, "Unable to add comment node to parent <%s> on line %d.", parent ? parent->value.element.name : "null", line);
	  break;
	}

	MXML_DEBUG("mxml_load_data: node=%p(<%s-->), parent=%p\n", node, buffer, parent);

        if (options && options->sax_cb)
        {
          if (!(options->sax_cb)(options->sax_cbdata, node, MXML_SAX_EVENT_COMMENT))
	    goto error;

          if (!mxmlRelease(node))
            node = NULL;
        }

	if (node && !first)
	  first = node;
      }
      else if (!strcmp(buffer, "![CDATA["))
      {
        // Gather CDATA section...
	while ((ch = mxml_getc(options, io_cb, io_cbdata, &encoding)) != EOF)
	{
	  if (ch == '>' && !strncmp(bufptr - 2, "]]", 2))
	  {
	    // Drop terminator from CDATA string...
	    bufptr[-2] = '\0';
	    break;
	  }
	  else if (!mxml_add_char(options, ch, &bufptr, &buffer, &bufsize))
	  {
	    goto error;
	  }

	  if (ch == '\n')
	    line ++;
	}

        // Error out if we didn't get the whole comment...
        if (ch != '>')
	{
	  // Print error and return...
	  _mxml_error(options, "Early EOF in CDATA node on line %d.", line);
	  goto error;
	}

        // Otherwise add this as an element under the current parent...
	bufptr[-2] = '\0';

        if (!parent && first)
	{
	  // There can only be one root element!
	  _mxml_error(options, "<%s]]> cannot be a second root node after <%s> on line %d.", buffer, first->value.element.name, line);
          goto error;
	}

	if ((node = mxmlNewCDATA(parent, buffer + 8)) == NULL)
	{
	  // Print error and return...
	  _mxml_error(options, "Unable to add CDATA node to parent <%s> on line %d.", parent ? parent->value.element.name : "null", line);
	  goto error;
	}

	MXML_DEBUG("mxml_load_data: node=%p(<%s]]>), parent=%p\n", node, buffer, parent);

        if (options && options->sax_cb)
        {
          if (!(options->sax_cb)(options->sax_cbdata, node, MXML_SAX_EVENT_CDATA))
	    goto error;

          if (!mxmlRelease(node))
            node = NULL;
        }

	if (node && !first)
	  first = node;
      }
      else if (buffer[0] == '?')
      {
        // Gather rest of processing instruction...
	while ((ch = mxml_getc(options, io_cb, io_cbdata, &encoding)) != EOF)
	{
	  if (ch == '>' && bufptr > buffer && bufptr[-1] == '?')
	    break;
	  else if (!mxml_add_char(options, ch, &bufptr, &buffer, &bufsize))
	    goto error;

	  if (ch == '\n')
	    line ++;
	}

        // Error out if we didn't get the whole processing instruction...
        if (ch != '>')
	{
	  // Print error and return...
	  _mxml_error(options, "Early EOF in processing instruction node on line %d.", line);
	  goto error;
	}

        // Otherwise add this as an element under the current parent...
	bufptr[-1] = '\0';

        if (!parent && first)
	{
	  // There can only be one root element!
	  _mxml_error(options, "<%s?> cannot be a second root node after <%s> on line %d.", buffer, first->value.element.name, line);
          goto error;
	}

	if ((node = mxmlNewDirective(parent, buffer + 1)) == NULL)
	{
	  // Print error and return...
	  _mxml_error(options, "Unable to add processing instruction node to parent <%s> on line %d.", parent ? parent->value.element.name : "null", line);
	  goto error;
	}

	MXML_DEBUG("mxml_load_data: node=%p(<%s?>), parent=%p\n", node, buffer, parent);

        if (options && options->sax_cb)
        {
          if (!(options->sax_cb)(options->sax_cbdata, node, MXML_SAX_EVENT_DIRECTIVE))
	    goto error;

          if (strncmp(node->value.directive, "xml ", 4) && !mxmlRelease(node))
            node = NULL;
        }

        if (node)
	{
	  if (!first)
            first = node;

	  if (!parent)
	  {
	    parent = node;

	    if (options && options->type_cb)
	      type = (options->type_cb)(options->type_cbdata, parent);
	    else if (options)
	      type = options->type_value;
	    else
	      type = MXML_TYPE_TEXT;
	  }
	}
      }
      else if (buffer[0] == '!')
      {
        // Gather rest of declaration...
	do
	{
	  if (ch == '>')
	  {
	    break;
	  }
	  else
	  {
            if (ch == '&')
            {
	      if ((ch = mxml_get_entity(options, io_cb, io_cbdata, &encoding, parent, &line)) == EOF)
		goto error;
            }

	    if (!mxml_add_char(options, ch, &bufptr, &buffer, &bufsize))
	      goto error;
	  }

	  if (ch == '\n')
	    line ++;
	}
        while ((ch = mxml_getc(options, io_cb, io_cbdata, &encoding)) != EOF);

        // Error out if we didn't get the whole declaration...
        if (ch != '>')
	{
	  // Print error and return...
	  _mxml_error(options, "Early EOF in declaration node on line %d.", line);
	  goto error;
	}

        // Otherwise add this as an element under the current parent...
	*bufptr = '\0';

        if (!parent && first)
	{
	  // There can only be one root element!
	  _mxml_error(options, "<%s> cannot be a second root node after <%s> on line %d.", buffer, first->value.element.name, line);
          goto error;
	}

	if ((node = mxmlNewDeclaration(parent, buffer + 1)) == NULL)
	{
	  // Print error and return...
	  _mxml_error(options, "Unable to add declaration node to parent <%s> on line %d.", parent ? parent->value.element.name : "null", line);
	  goto error;
	}

	MXML_DEBUG("mxml_load_data: node=%p(<%s>), parent=%p\n", node, buffer, parent);

        if (options && options->sax_cb)
        {
          if (!(options->sax_cb)(options->sax_cbdata, node, MXML_SAX_EVENT_DECLARATION))
	    goto error;

          if (!mxmlRelease(node))
            node = NULL;
        }

        if (node)
	{
	  if (!first)
            first = node;

	  if (!parent)
	  {
	    parent = node;

	    if (options && options->type_cb)
	      type = (options->type_cb)(options->type_cbdata, parent);
	    else if (options)
	      type = options->type_value;
	    else
	      type = MXML_TYPE_TEXT;
	  }
	}
      }
      else if (buffer[0] == '/')
      {
        // Handle close tag...
	MXML_DEBUG("mxml_load_data: <%s>, parent=%p\n", buffer, parent);

        if (!parent || strcmp(buffer + 1, parent->value.element.name))
	{
	  // Close tag doesn't match tree; print an error for now...
	  _mxml_error(options, "Mismatched close tag <%s> under parent <%s> on line %d.", buffer, parent ? parent->value.element.name : "(null)", line);
          goto error;
	}

        // Keep reading until we see >...
        while (ch != '>' && ch != EOF)
	  ch = mxml_getc(options, io_cb, io_cbdata, &encoding);

        node   = parent;
        parent = parent->parent;

        if (options && options->sax_cb)
        {
          if (!(options->sax_cb)(options->sax_cbdata, node, MXML_SAX_EVENT_ELEMENT_CLOSE))
	    goto error;

          if (!mxmlRelease(node))
          {
            if (first == node)
	      first = NULL;

	    node = NULL;
	  }
        }

        // Ascend into the parent and set the value type as needed...
	if (options && options->type_cb && parent)
	  type = (options->type_cb)(options->type_cbdata, parent);
	else if (options && !options->type_cb)
	  type = options->type_value;
      }
      else
      {
        // Handle open tag...
        if (!parent && first)
	{
	  // There can only be one root element!
	  _mxml_error(options, "<%s> cannot be a second root node after <%s> on line %d.", buffer, first->value.element.name, line);
          goto error;
	}

        if ((node = mxmlNewElement(parent, buffer)) == NULL)
	{
	  // Just print error for now...
	  _mxml_error(options, "Unable to add element node to parent <%s> on line %d.", parent ? parent->value.element.name : "null", line);
	  goto error;
	}

        if (mxml_isspace(ch))
        {
	  MXML_DEBUG("mxml_load_data: node=%p(<%s...>), parent=%p\n", node, buffer, parent);

	  if ((ch = mxml_parse_element(options, io_cb, io_cbdata, node, &encoding, &line)) == EOF)
	    goto error;
        }
        else if (ch == '/')
	{
	  MXML_DEBUG("mxml_load_data: node=%p(<%s/>), parent=%p\n", node, buffer, parent);

	  if ((ch = mxml_getc(options, io_cb, io_cbdata, &encoding)) != '>')
	  {
	    _mxml_error(options, "Expected > but got '%c' instead for element <%s/> on line %d.", ch, buffer, line);
            mxmlDelete(node);
            node = NULL;
            goto error;
	  }

	  ch = '/';
	}

        if (options && options->sax_cb)
        {
          if (!(options->sax_cb)(options->sax_cbdata, node, MXML_SAX_EVENT_ELEMENT_OPEN))
	    goto error;
	}

        if (!first)
	  first = node;

	if (ch == EOF)
	  break;

        if (ch != '/')
	{
	  // Descend into this node, setting the value type as needed...
	  parent = node;

	  if (options && options->type_cb && parent)
	    type = (options->type_cb)(options->type_cbdata, parent);
	  else if (options && !options->type_cb)
	    type = options->type_value;
	  else
	    type = MXML_TYPE_TEXT;
	}
        else if (options && options->sax_cb)
        {
          if (!(options->sax_cb)(options->sax_cbdata, node, MXML_SAX_EVENT_ELEMENT_CLOSE))
	    goto error;

          if (!mxmlRelease(node))
          {
            if (first == node)
	      first = NULL;

	    node = NULL;
	  }
        }
      }

      bufptr  = buffer;
    }
    else if (ch == '&')
    {
      // Add character entity to current buffer...
      if ((ch = mxml_get_entity(options, io_cb, io_cbdata, &encoding, parent, &line)) == EOF)
	goto error;

      if (!mxml_add_char(options, ch, &bufptr, &buffer, &bufsize))
	goto error;
    }
    else if (type == MXML_TYPE_OPAQUE || type == MXML_TYPE_CUSTOM || !mxml_isspace(ch))
    {
      // Add character to current buffer...
      if (!mxml_add_char(options, ch, &bufptr, &buffer, &bufsize))
	goto error;
    }
  }
  while ((ch = mxml_getc(options, io_cb, io_cbdata, &encoding)) != EOF);

  // Free the string buffer - we don't need it anymore...
  free(buffer);

  // Find the top element and return it...
  if (parent)
  {
    node = parent;

    while (parent != top && parent->parent)
      parent = parent->parent;

    if (node != parent)
    {
      _mxml_error(options, "Missing close tag </%s> under parent <%s> on line %d.", mxmlGetElement(node), node->parent ? node->parent->value.element.name : "(null)", line);

      mxmlDelete(first);

      return (NULL);
    }
  }

  if (parent)
    return (parent);
  else
    return (first);

  // Common error return...
  error:

  mxmlDelete(first);

  free(buffer);

  return (NULL);
}


//
// 'mxml_parse_element()' - Parse an element for any attributes...
//

static int				// O  - Terminating character
mxml_parse_element(
    mxml_options_t   *options,		// I - Options
    mxml_io_cb_t     io_cb,		// I - Read callback function
    void             *io_cbdata,	// I - Read callback data
    mxml_node_t      *node,		// I  - Element node
    _mxml_encoding_t *encoding,		// IO - Encoding
    int              *line)		// IO - Current line number
{
  int		ch,			// Current character in file
		quote;			// Quoting character
  char		*name,			// Attribute name
		*value,			// Attribute value
		*ptr;			// Pointer into name/value
  size_t	namesize,		// Size of name string
		valsize;		// Size of value string


  // Initialize the name and value buffers...
  if ((name = malloc(64)) == NULL)
  {
    _mxml_error(options, "Unable to allocate memory for name.");
    return (EOF);
  }

  namesize = 64;

  if ((value = malloc(64)) == NULL)
  {
    free(name);
    _mxml_error(options, "Unable to allocate memory for value.");
    return (EOF);
  }

  valsize = 64;

  // Loop until we hit a >, /, ?, or EOF...
  while ((ch = mxml_getc(options, io_cb, io_cbdata, encoding)) != EOF)
  {
    MXML_DEBUG("mxml_parse_element: ch='%c'\n", ch);

    // Skip leading whitespace...
    if (mxml_isspace(ch))
    {
      if (ch == '\n')
        (*line)++;

      continue;
    }

    // Stop at /, ?, or >...
    if (ch == '/' || ch == '?')
    {
      // Grab the > character and print an error if it isn't there...
      quote = mxml_getc(options, io_cb, io_cbdata, encoding);

      if (quote != '>')
      {
        _mxml_error(options, "Expected '>' after '%c' for element %s, but got '%c' on line %d.", ch, mxmlGetElement(node), quote, *line);
        goto error;
      }

      break;
    }
    else if (ch == '<')
    {
      _mxml_error(options, "Bare < in element %s on line %d.", mxmlGetElement(node), *line);
      goto error;
    }
    else if (ch == '>')
    {
      break;
    }

    // Read the attribute name...
    ptr = name;
    if (!mxml_add_char(options, ch, &ptr, &name, &namesize))
      goto error;

    if (ch == '\"' || ch == '\'')
    {
      // Name is in quotes, so get a quoted string...
      quote = ch;

      while ((ch = mxml_getc(options, io_cb, io_cbdata, encoding)) != EOF)
      {
        if (ch == '&')
        {
	  if ((ch = mxml_get_entity(options, io_cb, io_cbdata, encoding, node, line)) == EOF)
	    goto error;
	}
	else if (ch == '\n')
	{
	  (*line)++;
	}

	if (!mxml_add_char(options, ch, &ptr, &name, &namesize))
	  goto error;

	if (ch == quote)
          break;
      }
    }
    else
    {
      // Grab an normal, non-quoted name...
      while ((ch = mxml_getc(options, io_cb, io_cbdata, encoding)) != EOF)
      {
	if (mxml_isspace(ch) || ch == '=' || ch == '/' || ch == '>' || ch == '?')
	{
	  if (ch == '\n')
	    (*line)++;
          break;
        }
	else
	{
          if (ch == '&')
          {
	    if ((ch = mxml_get_entity(options, io_cb, io_cbdata, encoding, node, line)) == EOF)
	      goto error;
          }

	  if (!mxml_add_char(options, ch, &ptr, &name, &namesize))
	    goto error;
	}
      }
    }

    *ptr = '\0';

    if (mxmlElementGetAttr(node, name))
    {
      _mxml_error(options, "Duplicate attribute '%s' in element %s on line %d.", name, mxmlGetElement(node), *line);
      goto error;
    }

    while (ch != EOF && mxml_isspace(ch))
    {
      ch = mxml_getc(options, io_cb, io_cbdata, encoding);

      if (ch == '\n')
        (*line)++;
    }

    if (ch == '=')
    {
      // Read the attribute value...
      while ((ch = mxml_getc(options, io_cb, io_cbdata, encoding)) != EOF && mxml_isspace(ch))
      {
        if (ch == '\n')
          (*line)++;
      }

      if (ch == EOF)
      {
        _mxml_error(options, "Missing value for attribute '%s' in element %s on line %d.", name, mxmlGetElement(node), *line);
        goto error;
      }

      if (ch == '\'' || ch == '\"')
      {
        // Read quoted value...
        quote = ch;
	ptr   = value;

        while ((ch = mxml_getc(options, io_cb, io_cbdata, encoding)) != EOF)
        {
	  if (ch == quote)
	  {
	    break;
	  }
	  else
	  {
	    if (ch == '&')
	    {
	      if ((ch = mxml_get_entity(options, io_cb, io_cbdata, encoding, node, line)) == EOF)
	        goto error;
	    }
	    else if (ch == '\n')
	    {
	      (*line)++;
	    }

	    if (!mxml_add_char(options, ch, &ptr, &value, &valsize))
	      goto error;
	  }
	}

        *ptr = '\0';
      }
      else
      {
        // Read unquoted value...
	ptr      = value;
	if (!mxml_add_char(options, ch, &ptr, &value, &valsize))
	  goto error;

	while ((ch = mxml_getc(options, io_cb, io_cbdata, encoding)) != EOF)
	{
	  if (mxml_isspace(ch) || ch == '=' || ch == '/' || ch == '>')
	  {
	    if (ch == '\n')
	      (*line)++;

            break;
          }
	  else
	  {
	    if (ch == '&')
	    {
	      if ((ch = mxml_get_entity(options, io_cb, io_cbdata, encoding, node, line)) == EOF)
	        goto error;
	    }

	    if (!mxml_add_char(options, ch, &ptr, &value, &valsize))
	      goto error;
	  }
	}

        *ptr = '\0';
      }

      // Set the attribute with the given string value...
      mxmlElementSetAttr(node, name, value);
      MXML_DEBUG("mxml_parse_element: %s=\"%s\"\n", name, value);
    }
    else
    {
      _mxml_error(options, "Missing value for attribute '%s' in element %s on line %d.", name, mxmlGetElement(node), *line);
      goto error;
    }

    // Check the end character...
    if (ch == '/' || ch == '?')
    {
      // Grab the > character and print an error if it isn't there...
      quote = mxml_getc(options, io_cb, io_cbdata, encoding);

      if (quote != '>')
      {
        _mxml_error(options, "Expected '>' after '%c' for element %s, but got '%c' on line %d.", ch, mxmlGetElement(node), quote, *line);
        ch = EOF;
      }

      break;
    }
    else if (ch == '>')
      break;
  }

  // Free the name and value buffers and return...
  free(name);
  free(value);

  return (ch);

  // Common error return point...
  error:

  free(name);
  free(value);

  return (EOF);
}


//
// 'mxml_read_cb_fd()' - Read bytes from a file descriptor.
//

static size_t				// O - Bytes read
mxml_read_cb_fd(int    *fd,		// I - File descriptor
                void   *buffer,		// I - Buffer
                size_t bytes)		// I - Bytes to read
{
#if _WIN32
  int		rbytes;			// Bytes read


  rbytes = read(*fd, buffer, bytes);

#else
  ssize_t	rbytes;			// Bytes read


  while ((rbytes = read(*fd, buffer, bytes)) < 0)
  {
    if (errno != EINTR && errno != EAGAIN)
      break;
  }
#endif // _WIN32

  if (rbytes < 0)
    return (0);
  else
    return ((size_t)rbytes);
}


//
// 'mxml_read_cb_file()' - Read bytes from a file pointer.
//

static size_t				// O - Bytes read
mxml_read_cb_file(FILE   *fp,		// I - File pointer
                  void   *buffer,	// I - Buffer
                  size_t bytes)		// I - Bytes to read
{
  if (feof(fp))
    return (0);
  else
    return (fread(buffer, 1, bytes, fp));
}


//
// 'mxml_read_cb_string()' - Read bytes from a string.
//

static size_t				// O - Bytes read
mxml_read_cb_string(
    _mxml_stringbuf_t *sb,		// I - String buffer
    void              *buffer,		// I - Buffer
    size_t            bytes)		// I - Bytes to read
{
  size_t	remaining;		// Remaining bytes in buffer


  if ((remaining = sb->bufsize - (size_t)(sb->bufptr - sb->buffer)) < bytes)
    bytes = remaining;

  if (bytes > 0)
  {
    // Copy bytes from string...
    memcpy(buffer, sb->bufptr, bytes);
    sb->bufptr += bytes;
  }

  return (bytes);
}


//
// 'mxml_strtod()' - Convert a string to a double without respect to the locale.
//

static double				// O - Real number
mxml_strtod(mxml_options_t *options,	// I - Options
            const char     *buffer,	// I - String
            char           **bufend)	// O - End of number in string
{
  const char	*bufptr;		// Pointer into buffer
  char		temp[64],		// Temporary buffer
		*tempptr;		// Pointer into temporary buffer


  // See if the locale has a special decimal point string...
  if (!options || !options->loc)
    return (strtod(buffer, bufend));

  // Copy leading sign, numbers, period, and then numbers...
  tempptr                = temp;
  temp[sizeof(temp) - 1] = '\0';
  bufptr                 = buffer;

  if (*bufptr == '-' || *bufptr == '+')
    *tempptr++ = *bufptr++;

  while (*bufptr && isdigit(*bufptr & 255))
  {
    if (tempptr < (temp + sizeof(temp) - 1))
    {
      *tempptr++ = *bufptr++;
    }
    else
    {
      *bufend = (char *)bufptr;
      return (0.0);
    }
  }

  if (*bufptr == '.')
  {
    // Convert decimal point to locale equivalent...
    size_t	declen = strlen(options->loc->decimal_point);
					// Length of decimal point
    bufptr ++;

    if (declen <= (sizeof(temp) - (size_t)(tempptr - temp)))
    {
      memcpy(tempptr, options->loc->decimal_point, declen);
      tempptr += declen;
    }
    else
    {
      *bufend = (char *)bufptr;
      return (0.0);
    }
  }

  // Copy any remaining characters...
  while (*bufptr && isdigit(*bufptr & 255))
  {
    if (tempptr < (temp + sizeof(temp) - 1))
      *tempptr++ = *bufptr++;
    else
      break;
  }

  *bufend = (char *)bufptr;

  if (*bufptr)
    return (0.0);

  // Nul-terminate the temporary string and convert the string...
  *tempptr = '\0';

  return (strtod(temp, NULL));
}


//
// 'mxml_io_cb_fd()' - Write bytes to a file descriptor.
//

static size_t				// O - Bytes written
mxml_io_cb_fd(int    *fd,		// I - File descriptor
                 void   *buffer,	// I - Buffer
                 size_t bytes)		// I - Bytes to write
{
#if _WIN32
  int		wbytes;			// Bytes written


  wbytes = write(*fd, buffer, bytes);

#else
  ssize_t	wbytes;			// Bytes written


  while ((wbytes = write(*fd, buffer, bytes)) < 0)
  {
    if (errno != EINTR && errno != EAGAIN)
      break;
  }
#endif // _WIN32

  if (wbytes < 0)
    return (0);
  else
    return ((size_t)wbytes);
}


//
// 'mxml_io_cb_file()' - Write bytes to a file pointer.
//

static size_t				// O - Bytes written
mxml_io_cb_file(FILE   *fp,		// I - File pointer
                   void   *buffer,	// I - Buffer
                   size_t bytes)	// I - Bytes to write
{
  return (fwrite(buffer, 1, bytes, fp));
}


//
// 'mxml_io_cb_string()' - Write bytes to a string buffer.
//

static size_t				// O - Bytes written
mxml_io_cb_string(
    _mxml_stringbuf_t *sb,		// I - String buffer
    void              *buffer,		// I - Buffer
    size_t            bytes)		// I - Bytes to write
{
  size_t	remaining;		// Remaining bytes


  // Expand buffer as needed...
  if ((sb->bufptr + bytes) >= (sb->buffer + sb->bufsize - 1) && sb->bufalloc)
  {
    // Reallocate buffer
    char	*temp;			// New buffer pointer
    size_t	newsize;		// New bufsize

    newsize = (size_t)(sb->bufptr - sb->buffer) + bytes + 257;
    if ((temp = realloc(sb->buffer, newsize)) == NULL)
      return (0);

    sb->bufptr  = temp + (sb->bufptr - sb->buffer);
    sb->buffer  = temp;
    sb->bufsize = newsize;
  }

  // Copy what we can...
  if (sb->bufptr >= (sb->buffer + sb->bufsize - 1))
    return (0);			// No more room
  else if ((remaining = (sb->bufsize - (size_t)(sb->bufptr - sb->buffer) - 1)) < bytes)
    bytes = remaining;

  memcpy(sb->bufptr, buffer, bytes);
  sb->bufptr += bytes;

  return (bytes);
}


//
// 'mxml_write_node()' - Save an XML node to a file.
//

static int				// O - Column or -1 on error
mxml_write_node(
    mxml_node_t    *node,		// I - Node to write
    mxml_options_t *options,		// I - Options
    mxml_io_cb_t   io_cb,		// I - Write callback function
    void           *io_cbdata,		// I - Write callback data
    int            col)			// I - Current column
{
  mxml_node_t	*current,		// Current node
		*next;			// Next node
  size_t	i,			// Looping var
		width;			// Width of attr + value
  _mxml_attr_t	*attr;			// Current attribute
  char		s[255],			// Temporary string
		*data;			// Custom data string
  const char	*text;			// Text string
  bool		whitespace;		// Whitespace before text string?


  // Loop through this node and all of its children...
  for (current = node; current && col >= 0; current = next)
  {
    // Print the node value...
    MXML_DEBUG("mxml_write_node: current=%p(%d)\n", current, current->type);

    switch (mxmlGetType(current))
    {
      case MXML_TYPE_CDATA :
	  col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_BEFORE_OPEN, col);
	  col = mxml_write_string("<![CDATA[", io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_string(mxmlGetCDATA(current), io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_string("]]>", io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_AFTER_OPEN, col);
          break;

      case MXML_TYPE_COMMENT :
	  col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_BEFORE_OPEN, col);
	  col = mxml_write_string("<!--", io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_string(mxmlGetComment(current), io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_string("-->", io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_AFTER_OPEN, col);
          break;

      case MXML_TYPE_DECLARATION :
	  col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_BEFORE_OPEN, col);
	  col = mxml_write_string("<!", io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_string(mxmlGetDeclaration(current), io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_string(">", io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_AFTER_OPEN, col);
          break;

      case MXML_TYPE_DIRECTIVE :
	  col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_BEFORE_OPEN, col);
	  col = mxml_write_string("<?", io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_string(mxmlGetDirective(current), io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_string("?>", io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_AFTER_OPEN, col);
          break;

      case MXML_TYPE_ELEMENT :
	  col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_BEFORE_OPEN, col);
	  col = mxml_write_string("<", io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_string(mxmlGetElement(current), io_cb, io_cbdata, /*use_entities*/true, col);

	  for (i = current->value.element.num_attrs, attr = current->value.element.attrs; i > 0 && col >= 0; i --, attr ++)
	  {
	    width = strlen(attr->name);

	    if (attr->value)
	      width += strlen(attr->value) + 3;

	    if (options && options->wrap > 0 && (col + (int)width) > options->wrap)
	      col = mxml_write_string("\n", io_cb, io_cbdata, /*use_entities*/false, col);
	    else
	      col = mxml_write_string(" ", io_cb, io_cbdata, /*use_entities*/false, col);

	    col = mxml_write_string(attr->name, io_cb, io_cbdata, /*use_entities*/true, col);

	    if (attr->value)
	    {
	      col = mxml_write_string("=\"", io_cb, io_cbdata, /*use_entities*/false, col);
	      col = mxml_write_string(attr->value, io_cb, io_cbdata, /*use_entities*/true, col);
	      col = mxml_write_string("\"", io_cb, io_cbdata, /*use_entities*/false, col);
	    }
	  }

	  col = mxml_write_string(current->child ? ">" : "/>", io_cb, io_cbdata, /*use_entities*/false, col);
	  col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_AFTER_OPEN, col);
	  break;

      case MXML_TYPE_INTEGER :
	  if (current->prev)
	  {
	    // Add whitespace separator...
	    if (options && options->wrap > 0 && col > options->wrap)
	      col = mxml_write_string("\n", io_cb, io_cbdata, /*use_entities*/false, col);
	    else
	      col = mxml_write_string(" ", io_cb, io_cbdata, /*use_entities*/false, col);
	  }

          // Write integer...
	  snprintf(s, sizeof(s), "%ld", current->value.integer);
	  col = mxml_write_string(s, io_cb, io_cbdata, /*use_entities*/true, col);
	  break;

      case MXML_TYPE_OPAQUE :
	  col = mxml_write_string(mxmlGetOpaque(current), io_cb, io_cbdata, /*use_entities*/true, col);
	  break;

      case MXML_TYPE_REAL :
	  if (current->prev)
	  {
	    // Add whitespace separator...
	    if (options && options->wrap > 0 && col > options->wrap)
	      col = mxml_write_string("\n", io_cb, io_cbdata, /*use_entities*/false, col);
	    else
	      col = mxml_write_string(" ", io_cb, io_cbdata, /*use_entities*/false, col);
	  }

          // Write real number...
	  snprintf(s, sizeof(s), "%g", current->value.real);

          if (options && options->loc)
          {
            char	*sptr;		// Pointer into string

	    if ((sptr = strstr(s, options->loc->decimal_point)) != NULL)
	    {
	      // Convert locale decimal point to "."
	      if (options->loc_declen > 1)
	        memmove(sptr + 1, sptr + options->loc_declen, strlen(sptr + options->loc_declen) + 1);

	      *sptr = '.';
	    }
          }

	  col = mxml_write_string(s, io_cb, io_cbdata, /*use_entities*/true, col);
	  break;

      case MXML_TYPE_TEXT :
          text = mxmlGetText(current, &whitespace);

	  if (whitespace && col > 0)
	  {
	    // Add whitespace separator...
	    if (options && options->wrap > 0 && col > options->wrap)
	      col = mxml_write_string("\n", io_cb, io_cbdata, /*use_entities*/false, col);
	    else
	      col = mxml_write_string(" ", io_cb, io_cbdata, /*use_entities*/false, col);
	  }

	  col = mxml_write_string(text, io_cb, io_cbdata, /*use_entities*/true, col);
	  break;

      case MXML_TYPE_CUSTOM :
	  if (!options || !options->custsave_cb)
	    return (-1);

	  if ((data = (options->custsave_cb)(options->cust_cbdata, current)) == NULL)
	    return (-1);

	  col = mxml_write_string(data, io_cb, io_cbdata, /*use_entities*/true, col);

	  free(data);
	  break;

      default : // Should never happen
	  return (-1);
    }

    // Figure out the next node...
    if ((next = mxmlGetFirstChild(current)) == NULL)
    {
      if (current == node)
      {
        // Don't traverse to sibling node if we are at the "root" node...
        next = NULL;
      }
      else
      {
        // Try the next sibling, and continue traversing upwards as needed...
	while ((next = mxmlGetNextSibling(current)) == NULL)
	{
	  if (current == node || !mxmlGetParent(current))
	    break;

	  // Declarations and directives have no end tags...
	  current = mxmlGetParent(current);

	  if (mxmlGetType(current) == MXML_TYPE_ELEMENT)
	  {
	    col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_BEFORE_CLOSE, col);
	    col = mxml_write_string("</", io_cb, io_cbdata, /*use_entities*/false, col);
	    col = mxml_write_string(mxmlGetElement(current), io_cb, io_cbdata, /*use_entities*/true, col);
	    col = mxml_write_string(">", io_cb, io_cbdata, /*use_entities*/false, col);
	    col = mxml_write_ws(current, options, io_cb, io_cbdata, MXML_WS_AFTER_CLOSE, col);
	  }

	  if (current == node)
	    break;
	}
      }
    }
  }

  return (col);
}


//
// 'mxml_write_string()' - Write a string, escaping & and < as needed.
//

static int				// O - New column or `-1` on error
mxml_write_string(
    const char      *s,			// I - String to write
    mxml_io_cb_t    io_cb,		// I - Write callback function
    void            *io_cbdata,		// I - Write callback data
    bool            use_entities,	// I - Escape special characters?
    int             col)		// I - Current column
{
  const char	*frag,			// Start of current string fragment
		*ptr,			// Pointer into string
		*ent;			// Entity, if any
  size_t	fraglen;		// Length of fragment


  MXML_DEBUG("mxml_write_string(io_cb=%p, io_cbdata=%p, s=\"%s\", use_entities=%s, col=%d)\n", io_cb, io_cbdata, s, use_entities ? "true" : "false", col);

  if (col < 0)
    return (-1);

  for (frag = ptr = s; *ptr; ptr ++)
  {
    if (use_entities && (ent = _mxml_entity_string(*ptr)) != NULL)
    {
      size_t entlen = strlen(ent);	// Length of entity

      if (ptr > frag)
      {
        // Write current fragment
        fraglen = (size_t)(ptr - frag);

	if ((io_cb)(io_cbdata, (char *)frag, fraglen) != fraglen)
	  return (-1);
      }

      frag = ptr + 1;

      // Write entity
      if ((io_cb)(io_cbdata, (char *)ent, entlen) != entlen)
        return (-1);

      col ++;
    }
    else if (*ptr == '\r' || *ptr == '\n')
    {
      // CR or LF resets column
      col = 0;
    }
    else if (*ptr == '\t')
    {
      // Tab indents column
      col = col - (col % MXML_TAB) + MXML_TAB;
    }
    else
    {
      // All other characters are 1 column wide
      col ++;
    }
  }

  if (ptr > frag)
  {
    // Write final fragment
    fraglen = (size_t)(ptr - frag);

    if ((io_cb)(io_cbdata, (char *)frag, fraglen) != fraglen)
      return (-1);
  }

  return (col);
}


//
// 'mxml_write_ws()' - Do whitespace callback...
//

static int				// O - New column or `-1` on error
mxml_write_ws(
    mxml_node_t    *node,		// I - Current node
    mxml_options_t *options,		// I - Options
    mxml_io_cb_t   io_cb,		// I - Write callback function
    void           *io_cbdata,		// I - Write callback data
    mxml_ws_t      ws,			// I - Whitespace value
    int            col)			// I - Current column
{
  const char	*s;			// Whitespace string


  if (options && options->ws_cb && (s = (options->ws_cb)(options->ws_cbdata, node, ws)) != NULL)
    col = mxml_write_string(s, io_cb, io_cbdata, /*use_entities*/false, col);

  return (col);
}