File: read_xml.c

package info (click to toggle)
ggobi 2.1.9~20091212-3
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 19,340 kB
  • ctags: 5,083
  • sloc: ansic: 57,242; xml: 30,604; cpp: 833; makefile: 355; java: 225; perl: 201; sh: 122; python: 23
file content (2037 lines) | stat: -rw-r--r-- 54,575 bytes parent folder | download | duplicates (3)
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
 /* read_xml.c */
/*
 * ggobi
 * Copyright (C) AT&T, Duncan Temple Lang, Dianne Cook 1999-2005
 *
 * ggobi is free software; you may use, redistribute, and/or modify it
 * under the terms of the Common Public License, which is distributed
 * with the source code and displayed on the ggobi web site, 
 * www.ggobi.org.  For more information, contact the authors:
 *
 *   Deborah F. Swayne   dfs@research.att.com
 *   Di Cook             dicook@iastate.edu
 *   Duncan Temple Lang  duncan@wald.ucdavis.edu
 *   Andreas Buja        andreas.buja@wharton.upenn.edu
*/

#include <libxml/parserInternals.h>

/*
   This is a SAX based parser for reading a single input file
   formatted in XML for the DTD specified in ggobi.dtd.

   SAX is an event based parser. As different elements of the document
   are encountered by the parser on its input stream, it invokes
   user-specified callbacks. For our purposes, we currently need only
   handle 3 event types:
      1) the start of a tag
      2) the end of a tag  
      3) regular text data within a tag

   As with all event driven approaches, we can specify a user-level
   data object that can is passed to each event handler/callback.
   This is used to parameterize the particular call. In our case,
   we pass an XMLParserData * object (defined in read_xml.h).
   This basically stores what state in the document we currently have
   and indicates how to interpret the future callbacks, and also
   the ggobid structure which we are attempting to fill in.
   Additionally, it maintains a list of default settings that are 
   to be applied to each row, but which can be set generically in the
   top-level element (ggobidata).
  

   When we encounter the start of tag, we are given the tag name, the
   list of attributes for the tag instance and a reference to the
   parser instance XMLParserData object we specified at the start of the
   parsing. This handler is startXMLElement.  Here, we dispatch
   a call to the appropriate method based on the tag name. Generally,
   this either allocates storage space in the ggobid structure being
   filled in, or stores partial information needed to do this.
   Additionally, for the tag ggobidata, the attributes are processed
   to store the default values for record attributes. These are
   attributes such as color, glyph (size and type). 

   As each tag is encountered, we convert its type to an enumerated
   type and store this as the pending state. This is used to determine
   how to interpret ASCII text within an element.

   When we encounter the end of a tag/element,  the routine
   endXMLElement is called. We use this to increment counters indicating
   which record, variable or edge is next in the stream. These are 
   quasi-global variables that are parser-instance specific and a
   necessary consquence of the event-driven style of parsing.

   Finally, when ASCII text within an XML element is discovered by the
   parser, the routine characters() is called. We call different
   routines (setRecordsValues() and setVariableName()) based on the
   state of the parsing. This was set at the start of each tag/element
   in startXMLElement. 
 
 */

#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <gtk/gtk.h>
#include <glib/gprintf.h>

#include "read_xml.h"

#include "externs.h"

#include "GGobiAPI.h"


void setGGobiColorScheme (const xmlChar ** attrs, XMLParserData * data);

void startXMLElement (void *user_data, const xmlChar * name,
                      const xmlChar ** attrs);
void endXMLElement (void *user_data, const xmlChar * name);
void Characters (void *user_data, const xmlChar * ch, gint len);
void cumulateRecordData (XMLParserData * data, const xmlChar * ch, gint len);
gint getAutoLevelIndex (const char *const label, XMLParserData * data,
                        vartabled * el);
static gboolean setRecordValue (const char *tmp, GGobiData * d,
                                XMLParserData * data);
void resetRecordInfo (XMLParserData * data);
static void releaseCurrentDataInfo (XMLParserData * parserData);

/*
 The different XML element names we recognize in the input format.

 countervariable is an automatic convenience  variable that generates
 a new variable in the dataset that does not have corresponding entries
 in the input file. For each record, we generate a value which is the
 index in the dataset of that record (starting at 1).

 Along the same lines, we now have randomuniformvariable. This
 is another automatic variable whose values are generated by the
 act of reading the dataset. 
 I am not certain that this belongs here. It is not reproducible.
 It doesn't generalize to different distributions, or even transformations
 of the U(0, 1) distribution. Perhaps having this feature implemented via
 a plugin which uses the new_datad event signal to add variables to a dataset.
 There is a disconnect between what the author of the dataset wants and
 what the plugin knows. So, having this may well be necessary. 
 One can of course use a scripting language (e.g. R, Python, ...) to 
 create the dataset externall.
 
 One can have any number of randomuniformvariable elements in a dataset,
 which is different from the countervariable. This is implemented by 
 introducing a new variable type (like categorical, real, ...)
 in the vartyped enumeration in vartable.h. This means that we have
 to update code to handle this element in the switch statements
 and this is error-prone. (We can easily overlook some of the switch statements
 and get odd behavior). We would rather have the  vartabled data structure as
 a class and have methods for it. Switch statements are simply not extensible.
 For this case, we only have to update vartable_nbook.c.

*/
const gchar *const xmlDataTagNames[] = {
  "ggobidata",
  "data",                       /* DATASET */
  "description",
  "record",
  "records",
  "variables",
  "variable",
  "colormap",
  "color",
  /* variables */
  "realvariable",
  "categoricalvariable",
  "integervariable",
  "countervariable",
  "randomuniformvariable",
  "levels",
  "level",
  /* color scheme */
  "activeColorScheme",
  /* brushing attributes: color first; later, glyph type and size */
  "brush",
  /* data values */
  "real",
  "int",
  "string",
  "na",
  "quickHelp",
  "edges",
  "edge",
  ""
};


GSList *
read_xml (InputDescription * desc, ggobid * gg, GGobiPluginInfo * plugin)
{
  return (data_xml_read (desc, gg));
}

InputDescription *
read_xml_input_description (const char *const fileName,
                            const char *const modeName, ggobid * gg,
                            GGobiPluginInfo * info)
{
  InputDescription *desc;
  desc = (InputDescription *) g_malloc0 (sizeof (InputDescription));
  desc->fileName = g_strdup (fileName);
  /*
   * If fileName isn't the name of a readable file, append .xml and
   * try again -- but only if it doesn't already end in .xml.
   */
  if (file_is_readable (desc->fileName) == false) {
    gint len = strlen(desc->fileName);
    if (len-4 > 0 && strcmp(&desc->fileName[len-4], ".xml")) {
      g_free (desc->fileName);
      desc->fileName = g_malloc ((strlen (fileName) + 5) * sizeof (gchar));
      sprintf (desc->fileName, "%s.xml", fileName);
    }
  }

  desc->mode = isURL (fileName) ? url_data : xml_data;
  desc->desc_read_input = &read_xml;

  return (desc);
}



void
ggobi_XML_warning_handler (void *data, const gchar * msg, ...)
{
  va_list ap;
  xmlParserCtxtPtr p = (xmlParserCtxtPtr) ((XMLParserData *) data)->parser;

  va_start (ap, msg);
  fprintf (stderr, "Warning from XML parsing [%d, %d]: ",
           (int) p->input->line, (int) p->input->col);

  g_vfprintf (stderr, msg, ap);

  fflush (stderr);
}

void
ggobi_XML_error_handler (void *data, const gchar * msg, ...)
{
  va_list ap;
  xmlParserCtxtPtr p = (xmlParserCtxtPtr) ((XMLParserData *) data)->parser;

  fprintf (stderr, "Error in XML parsing [line %d, column %d]: ",
           (int) p->input->line, (int) p->input->col);

  va_start (ap, msg);
  g_vfprintf (stderr, msg, ap);

  fflush (stderr);
}


/*
  We also need a version that takes a FILE*
  and reads from it. This is so that we can
  handle reading from standard input.

  The DOM style parsing can be initiated very simply.

  xmlDocPtr doc;
    doc = xmlParseFile(name);
 */



GSList *
data_xml_read (InputDescription * desc, ggobid * gg)
{
  xmlSAXHandlerPtr xmlParserHandler;
  xmlParserCtxtPtr ctx =
    (xmlParserCtxtPtr) g_malloc (sizeof (xmlParserCtxtPtr));
  XMLParserData data;
  gchar *name = g_strdup (desc->fileName);  /* find_xml_file(desc->fileName, NULL, gg); */
  GSList *dlist;

  if (name == NULL)
    return (false);

  xmlParserHandler = (xmlSAXHandlerPtr) g_malloc0 (sizeof (xmlSAXHandler));
  /* Make certain this is initialized so that we don't have any references
     to unwanted routines!
   */

  xmlParserHandler->startElement = startXMLElement;
  xmlParserHandler->endElement = endXMLElement;
  xmlParserHandler->characters = Characters;

  xmlParserHandler->error = ggobi_XML_error_handler;
  xmlParserHandler->warning = ggobi_XML_warning_handler;

  initParserData (&data, xmlParserHandler, gg);

  ctx = xmlCreateFileParserCtxt (name);
  if (ctx == NULL) {
    xml_warning ("File error:", name, "Can't open file ", &data);
    g_free (name);
    return (false);
  }

  ctx->validate = 1;

  ctx->userData = &data;
  data.parser = ctx;
  data.input = desc;
  ctx->sax = xmlParserHandler;
  data.dlist = NULL;

  xmlParseDocument (ctx);

  dlist = ((XMLParserData *) (ctx->userData))->dlist;

  ctx->sax = NULL;
  xmlFreeParserCtxt (ctx);

  g_free (xmlParserHandler);
  g_free (name);

#ifdef XXX
  {
    GSList *l;
    GGobiData *d;
    ok = true;
    for (l = gg->d; l; l = l->next) {
      d = (GGobiData *) l->data;
      /* ok &= (d->ncols > 0 && d->nrows > 0); */
      /*-- a simple edge set has no variables --*/
      ok &= (d->nrows > 0);
    }
  }
#endif

  return (dlist);
}

void
initParserData (XMLParserData * data, xmlSAXHandlerPtr handler, ggobid * gg)
{
  data->gg = gg;
  data->current_record = 0;
  data->current_variable = 0;
  data->current_element = 0;
  data->current_data = NULL;

  data->current_color = 0;
  data->reading_colormap_file_p = false;
  data->state = UNKNOWN;
  data->terminateStrings_p = true;
  data->NA_identifier = NULL;

  data->idTable = NULL;
  data->handlers = handler;
  data->defaults.color = -1;
  data->defaults.glyphType = sessionOptions->info->glyph.type;
  data->defaults.glyphSize = sessionOptions->info->glyph.size;
  data->defaults.edgeWidth = -1;  /*-- this has no home in ggobi --*/
  data->defaults.hidden = false;

  /*
   * I don't think we plan to support this feature, so I'm ifdef'ing
   * out some buggy code later on in the file. dfs
  */
  data->recordLabelsVariable = -1;

  data->recordString = NULL;
  data->recordStringLength = 0;

  data->autoLevels = NULL;

  data->idNamesTable = NULL;
}

void
startXMLElement (void *user_data, const xmlChar * name,
                 const xmlChar ** attrs)
{
  XMLParserData *data = (XMLParserData *) user_data;
  enum xmlDataState type = tagType (name, false);

  switch (type) {
  case COLORSCHEME:
    setGGobiColorScheme (attrs, data);
    break;
  case VARIABLES:
    allocVariables (attrs, data);
    break;
  case VARIABLE:
  case REAL_VARIABLE:
  case INTEGER_VARIABLE:
  case CATEGORICAL_VARIABLE:
  case UNIFORM_VARIABLE:
    newVariable (attrs, data, name);
    break;
  case COUNTER_VARIABLE:
    newVariable (attrs, data, name);
    data->counterVariableIndex = data->current_variable;
    break;

  case CATEGORICAL_LEVELS:
    categoricalLevels (attrs, data);
    break;
  case CATEGORICAL_LEVEL:
    setLevelIndex (attrs, data);
    break;

  case RECORDS:
    setDatasetInfo (attrs, data);
    break;
  case TOP:
    setGeneralInfo (attrs, data);
    break;
  case EDGE:
  case RECORD:
    newRecord (attrs, data);
    break;
  case COLORMAP:
    /*setColorMap(attrs, data); *//* requires some thought ... */
    break;
  case BRUSHSTYLE:
    setBrushStyle (attrs, data);
    break;
  case COLOR:
    /*setColormapEntry(attrs, data); *//* ditto .... */
    break;
  case DESCRIPTION:
    /* description text pending */
    break;
  case EDGES:
  case DATASET:
    setDataset (attrs, data, type);
    break;

  case REAL:
  case INTEGER:
  case STRING:
  case NA:
    if (data->recordString) {
      setRecordValues (data, data->recordString, data->recordStringLength,
                       -1);
      if (type != NA && type != STRING)
        data->current_element++;
      resetRecordInfo (data);
    }
    break;
  case QUICK_HELP:
    break;
  default:
    fprintf (stderr, "Unrecognized XML state %s\n", name);
    fflush (stderr);
    break;
  }

  data->state = type;
}

void
setGGobiColorScheme (const xmlChar ** attrs, XMLParserData * data)
{
  const gchar *tmp;

  tmp = getAttribute (attrs, "file");
  if (tmp) {
    /* process this file to append its color schemes into the global list. */
    read_colorscheme ((gchar *) tmp, &data->gg->colorSchemes);
  }

  tmp = getAttribute (attrs, "name");
  if (tmp) {
    /* resolve the color scheme by name */

    colorschemed *scheme;
    scheme = findColorSchemeByName (data->gg->colorSchemes, tmp);
    if (scheme) {
      data->gg->activeColorScheme = scheme;
      colorscheme_init (scheme);
    }
    else
      ggobi_XML_error_handler (data,
                               "Invalid colorscheme name %s. No such scheme.\n",
                               tmp);
  }
  else {
    ggobi_XML_error_handler (data, "No colorscheme name specified\n");
  }
}

gint
setLevelIndex (const xmlChar ** attrs, XMLParserData * data)
{
  const gchar *tmp = getAttribute (attrs, "value");
  gint itmp;
  GGobiData *d = getCurrentXMLData (data);
  vartabled *el = vartable_element_get(data->current_variable, d);

  data->current_level++; /*-- current_level here ranges from 0 to nlevels-1 --*/

/*-- dfs: placeholder for proper debugging --*/
  if (data->current_level >= el->nlevels) {
/*XXX Put in a more terminal error! */
    ggobi_XML_error_handler (data, "trouble: adding too many levels to %s\n",
                             ggobi_data_get_col_name(d, data->current_variable));
  }
/* */

  itmp = data->current_level;
  if (tmp != NULL) {
    itmp = strToInteger (tmp);
    if (itmp < 0)
      g_printerr ("trouble: levels must be >= 0\n");
  }
  el->level_values[data->current_level] = itmp;

  return (data->current_level);
}

/*
 * If the user hasn't supplied level names and values, fill in
 * default values:  Level 0 .... Level (nlevels-1)
*/
void
completeCategoricalLevels (XMLParserData * data)
{
  GGobiData *d = getCurrentXMLData (data);
  vartabled *el = vartable_element_get (data->current_variable, d);
  gint min = 1;

  if (data->current_level == -1) {
    gint k;

    if (el->lim_specified_p)
      min = (gint) el->lim_specified.min;

    /*-- Alert the user what we're about to do --*/
    g_print ("Supplying default level values for \"%s\" ranging from %d:%d\n",
             ggobi_data_get_col_name(d, data->current_variable), min, min + el->nlevels - 1);
    for (k = 0; k < el->nlevels; k++) {
      el->level_values[k] = min + k;
      if (el->level_names[k]) g_free(el->level_names[k]);
      el->level_names[k] = g_strdup_printf ("L%d", k + 1);
    }
  }
}


//FIXME: need new vartable function: load from xml
void
categoricalLevels (const xmlChar ** attrs, XMLParserData * data)
{
  GGobiData *d = getCurrentXMLData (data);
  vartabled *el = vartable_element_get (data->current_variable, d);
  gint i;

  const gchar *tmp = getAttribute (attrs, "count");

  if (tmp != NULL) {
    el->nlevels = strToInteger (tmp);
    if (el->nlevels > 0) {
      el->level_values = (gint *) g_malloc (el->nlevels * sizeof (gint));
      el->level_counts = (gint *) g_malloc (el->nlevels * sizeof (gint));
      el->level_names = (gchar **) g_malloc (el->nlevels * sizeof (gchar *));
      for (i = 0; i < el->nlevels; i++) {
        el->level_counts[i] = 0;
        el->level_names[i] = NULL;
      }
    }
    else {
      el->level_values = NULL;
      el->level_counts = NULL;
      el->level_names = NULL;
    }
  }

  data->current_level = -1;     /* We'll increment the first one. */

  if (el->nlevels < 1) {
    fprintf (stderr, "Levels for %s mis-specified\n", el->collab);
    fflush (stderr);
  }
}

void
addLevel (XMLParserData * data, const gchar * c, gint len)
{
  GGobiData *d = getCurrentXMLData (data);
  vartabled *el = vartable_element_get (data->current_variable, d);
  gint lev = data->current_level;

  gchar *val = g_strdup (c);

/*XXX check not off by one! If so, probably increment
  data->current_level. */
  if (data->current_level >= el->nlevels)
    g_printerr ("trouble: adding too many levels to %s\n", el->collab);

  /*
   * This is a kludge, I admit, but if a level name includes special
   * characters (such as &), the string is somehow fed into this
   * routine in pieces.  This section of code glues the separate
   * pieces back together again.  -- dfs
  */
  if (el->level_names[lev]) {
    gchar *tmp = g_strdup(el->level_names[lev]);
    g_free(el->level_names[lev]);
    el->level_names[lev] = g_strdup_printf ("%s%s", tmp, val);
    g_free(tmp);
  } else
    el->level_names[lev] = g_strdup(val);

  g_free (val);
}

void
resetRecordInfo (XMLParserData * data)
{
  if (data->recordString)
    g_free (data->recordString);

  data->recordString = NULL;
  data->recordStringLength = 0;
}

void
resolveEdgeIds (XMLParserData * parserData)
{

}

void
resolveAllEdgeIds (XMLParserData * parserData)
{

}

gint
edgecompare (const void *val1, const void *val2)
{
  const SortableEndpoints *e1 = (const SortableEndpoints *) val1;
  const SortableEndpoints *e2 = (const SortableEndpoints *) val2;
  gint acomp, bcomp;

  acomp = strcmp (e1->a, e2->a);
  bcomp = strcmp (e1->b, e2->b);

  if (acomp < 0 || (acomp == 0 && bcomp < 0))
    return (-1);
  else if (acomp == 0 && bcomp == 0)
    return (0);
  else
    return (1);
}

void
setEdgePartners (XMLParserData * parserData)
{
  GGobiData *e = getCurrentXMLData (parserData);
  SortableEndpoints *ep;
  gint i, k, n;
  gboolean dups = false;

  if (e->edge.n <= 0)
    return;

  n = 2 * e->edge.n;
  ep = (SortableEndpoints *)
    g_malloc (n * sizeof (SortableEndpoints));

  /*-- Assume that we have no edges from i to i --*/

  /*
   * Before setting partners, check for duplicate edges.  If we find
   * one, bail out -- we don't handle them correctly, and we don't
   * want them around.
   */

  for (i = 0, k = 0; i < e->edge.n; i++) {
    if (e->edge.sym_endpoints[i].a == NULL || 
        e->edge.sym_endpoints[i].b == NULL)
    {
      g_critical ("Not as many edges as expected in '%s': Edge %d is missing\n",
		  e->name, i);
      exit(0);
    }

    ep[k].a = g_strdup ((gchar *) e->edge.sym_endpoints[i].a);
    ep[k].b = g_strdup ((gchar *) e->edge.sym_endpoints[i].b);
    ep[k].jcase = i;
    k++;
  }
  qsort ((gchar *) ep, e->edge.n, sizeof (SortableEndpoints), edgecompare);

  for (i = 1; i < e->edge.n; i++) {
    k = i - 1;
    if (strcmp (ep[i].a, ep[k].a) == 0 && strcmp (ep[i].b, ep[k].b) == 0) {
      g_critical ("Found duplicate edge from %s to %s",
                  (gchar *) e->edge.sym_endpoints[ep[i].jcase].a,
                  (gchar *) e->edge.sym_endpoints[ep[i].jcase].b);
      dups = true;
    }
  }
  if (dups)
    g_error ("Duplicate edges found");


  /*-- If there are no dups, add the reverse of each edge and re-sort --*/
  for (i = 0, k = e->edge.n; i < e->edge.n; i++) {
    ep[k].a = g_strdup ((gchar *) e->edge.sym_endpoints[i].b);
    ep[k].b = g_strdup ((gchar *) e->edge.sym_endpoints[i].a);
    ep[k].jcase = i;
    k++;
  }
  qsort ((gchar *) ep, n, sizeof (SortableEndpoints), edgecompare);


  for (i = 1; i < n; i++) {
    k = i - 1;
    if (strcmp (ep[i].a, ep[k].a) == 0 && strcmp (ep[i].b, ep[k].b) == 0) {
      e->edge.sym_endpoints[ep[i].jcase].jpartner = ep[k].jcase;
      e->edge.sym_endpoints[ep[k].jcase].jpartner = ep[i].jcase;
    }
  }

  for (i = 0; i < n; i++) {
    g_free (ep[i].a);
    g_free (ep[i].b);
  }
  g_free (ep);
}


void
endXMLElement (void *user_data, const xmlChar * name)
{
  XMLParserData *data = (XMLParserData *) user_data;
  enum xmlDataState type = tagType (name, true);

  switch (type) {
  case EDGES:
    resolveEdgeIds (data);
  case DATASET:
    {
      GGobiData *d = getCurrentXMLData (data);

      if (data->current_record < d->nrows) {
        g_error ("There are fewer records than declared for '%s': %d < %d.",
                 d->name, data->current_record, d->nrows);
      }

      setEdgePartners (data);
      releaseCurrentDataInfo (data);

      data->dlist = g_slist_append (data->dlist, d);

    }
    break;

  case EDGE:
    if (data->current_element < data->current_data->ncols) {
      ggobi_XML_error_handler (data, "Not enough elements\n");
    }
    data->current_record++;
    break;
  case RECORD:
    /* This processes every element in the record, and it will
       become confused and complain if we don't feed d->ncols
       elements to it.  I believe it also handles the </record>
       tag in the case where record elements have been individually
       tagged, and it does that without confusion. */
    setRecordValues (data, data->recordString, data->recordStringLength, -1);
    data->current_record++;
    resetRecordInfo (data);
    break;
  case NA:
    ggobi_data_set_missing(getCurrentXMLData(data), data->current_record, data->current_element);
    data->current_element++;
    break;
  case REAL:
  case INTEGER:
  case STRING:
    /* This is the individual setRecordValue(), i.e. with no 's' at the end. */
    setRecordValue ((const char *) data->recordString, data->current_data,
                    data);
    data->current_element++;
    break;
  case VARIABLE:
  case REAL_VARIABLE:
  case CATEGORICAL_VARIABLE:
  case COUNTER_VARIABLE:
  case INTEGER_VARIABLE:
  case UNIFORM_VARIABLE:
    data->current_variable++;
    break;
  case COLOR:
    data->current_color++;
    break;
  case COLORMAP:
    break;
  case CATEGORICAL_LEVELS:
    completeCategoricalLevels (data);
    break;
  case CATEGORICAL_LEVEL:
    break;
  case TOP:
    /* resolve all the edges */
    resolveAllEdgeIds (data);
    break;
  default:
    data = NULL;                /* just any code so we can stop. */
    break;
  }

  if (data) {
    resetRecordInfo (data);
    data->state = UNKNOWN;
  }
}


XmlTagType
tagType (const xmlChar * name, gboolean endTag)
{
  gint n = sizeof (xmlDataTagNames) / sizeof (xmlDataTagNames)[0] - 1;
  gint i;
  const gchar *tmp = (const gchar *) name;
  /*
     if(endTag) {
     tmp++;
     }
   */

  for (i = 0; i < n; i++) {
    if (strcmp (tmp, xmlDataTagNames[i]) == 0) {
      return ((enum xmlDataState) i);
    }
  }

  return (UNKNOWN);
}


/*
  Called when data within an element is found by the parser.
  Note that the parser does not have to give us all the data
  in one go (although it usually does). Instead,
  it can make several calls to this routine for the same
  element instances. E.g 
    <text>
      a few words
     and another sentence
    </text>
   may result in two calls - one for each sentence.

   This is important to handle as it means that we must be prepared
   to read values within a record across different calls and remember
   which variable/column we last completed for this record.
   This is the current_element field in XMLParserData. 
   Additionally, if a variable name is split across multiple calls
   we must append subsequent calls to the initial value.
  

   Additionally, new lines and leading and trailing white space 
   are not removed. Hence, we must do this ourselves. We use
   skipWhiteSpace to move to first non-whitespace character in the
   string.

   Also, the text is given to us as a a sequence of bytes rather than
   a non-terminated string. Thus, we are told the number of bytes
   rather than being able to use strlen to compute the length of the
   string.
   If the flag terminateStrings is set in the XMLParserData instance,
   this routine takes care of copying the data into a regularly
   NULL-terminated string so that the routines to which the data
   is passed can work with it more easily.
 */
void
Characters (void *user_data, const xmlChar * ch, gint len)
{
  gchar *tmp = NULL;
  gint dlen = len;
  const xmlChar *c;
  XMLParserData *data = (XMLParserData *) user_data;

  c = (const xmlChar *) skipWhiteSpace (ch, &dlen);
  if (dlen < 1 || c[0] == '\n')
    return;

  if (data->terminateStrings_p) {
    tmp = g_strndup((gchar *)c, dlen);
    c = (const xmlChar *) tmp;
  }

  switch (data->state) {
  case NA:
  case RECORD:
  case REAL:
  case STRING:
  case INTEGER:
  case UNKNOWN:
    /* Now we call
       setRecordValues (data, c, dlen); 
       after gathering the entire string for the record so that we
       don't get bizarre splits such as  "1.3 1.4 1"  followed by ".4..."
     */
    cumulateRecordData (data, c, dlen);
    break;
  case VARIABLE:
  case CATEGORICAL_VARIABLE:
  case REAL_VARIABLE:
  case UNIFORM_VARIABLE:
    setVariableName (data, c, dlen);
    break;
  case COLOR:
    break;
  case CATEGORICAL_LEVEL:
    addLevel (data, (const gchar *) c, dlen);
    break;
  default:
    break;
  }

  if (data->terminateStrings_p) {
    g_free (tmp);
  }
}

const xmlChar *
skipWhiteSpace (const xmlChar * ch, gint * len)
{
  const xmlChar *tmp = ch;
  while (*len >= 0) {
    if (*len == 0 || (tmp[0] != ' ' && tmp[0] != '\t' && tmp[0] != '\n'))
      break;
    tmp++;
    (*len)--;
  }

  return (tmp);
}

void
cumulateRecordData (XMLParserData * data, const xmlChar * ch, gint len)
{
  data->recordString = (xmlChar *) g_realloc (data->recordString,
                                              (len +
                                               data->recordStringLength +
                                               1) * sizeof (xmlChar));
  memcpy (data->recordString + data->recordStringLength, ch,
          len * sizeof (xmlChar));
  data->recordStringLength += len;
  data->recordString[data->recordStringLength] = '\0';

  return;
}



/**
  Called in response to a ggobidata tag which contains
  the different datasets. The count element here is the
  number of datasets to expect.
 */
gboolean
setGeneralInfo (const xmlChar ** attrs, XMLParserData * data)
{
  const gchar *tmp = getAttribute (attrs, "count");

  if (tmp != NULL) {
    data->expectedDatasetCount = strToInteger (tmp);
  }

  tmp = getAttribute (attrs, "ids");

  return (true);
}


gboolean
setDatasetInfo (const xmlChar ** attrs, XMLParserData * data)
{
  const gchar *tmp = getAttribute (attrs, "count");
  GGobiData *d = getCurrentXMLData (data);

  if (tmp == NULL) {
    g_error ("No count attribute");
  }

  d->nrows = strToInteger (tmp);
  d->nrows_in_plot = d->nrows;  /*-- for now --*/

  rowlabels_alloc (d);
  br_glyph_ids_alloc (d);
  br_glyph_ids_init (d);

  d->edge.n = 0;

  br_color_ids_alloc (d);
  br_color_ids_init (d);

  setDefaultDatasetValues (attrs, data);

  if (tmp) {
    arrayf_alloc (&d->raw, d->nrows, d->ncols);
    arrays_alloc (&d->missing, d->nrows, d->ncols);
    br_hidden_alloc (d);
    br_hidden_init (d);
  }

  data->current_variable = 0;
  data->current_record = 0;
  data->current_variable = 0;
  data->current_element = 0;

  data->idTable = NULL;

  return (true);
}

gboolean
setDefaultDatasetValues (const xmlChar ** attrs, XMLParserData * data)
{
  const gchar *tmp = getAttribute (attrs, "missingValue");
  if (tmp != NULL) {
    data->NA_identifier = g_strdup (tmp);
  }

  setGlyph (attrs, data, -1);
  setColor (attrs, data, -1);
  setHidden (attrs, data, -1);
  return (true);
}

gint
strToInteger (const gchar * tmp)
{
  gint value;

  value = atoi (tmp);

  return (value);
}


const gchar *
getAttribute (const xmlChar ** attrs, gchar * name)
{
  const xmlChar **tmp = attrs;
  while (tmp && tmp[0]) {
    if (strcmp (name, (const gchar *) tmp[0]) == 0)
      return ((const gchar *) tmp[1]);
    tmp += 2;
  }

  return (NULL);
}

gboolean
newRecord (const xmlChar ** attrs, XMLParserData * data)
{
  readXMLRecord (attrs, data);

  return (true);
}

gboolean
setHidden (const xmlChar ** attrs, XMLParserData * data, gint i)
{
  const gchar *tmp;
  GGobiData *d = getCurrentXMLData (data);

  tmp = getAttribute (attrs, "hidden");
  if (tmp) {
    gboolean hidden = asLogical (tmp);

    if (i < 0) {
      data->defaults.hidden = hidden;
    }
    else
      d->hidden.els[i] = d->hidden_now.els[i] = d->hidden_prev.els[i] =
        hidden;
  }

  return (tmp != NULL);
}

gboolean
asLogical (const gchar * sval)
{
  guint i;
  gboolean val = false;
  const gchar *const trues[] = { "T", "true", "True", "1" };
  for (i = 0; i < sizeof (trues) / sizeof (trues[0]); i++) {
    if (strcmp (sval, trues[i]) == 0)
      return (true);
  }

  return (val);
}

gboolean
setColor (const xmlChar ** attrs, XMLParserData * data, gint i)
{
  const gchar *tmp;
  gint value = data->defaults.color;
  GGobiData *d = getCurrentXMLData (data);
  colorschemed *scheme = data->gg->activeColorScheme;

  tmp = getAttribute (attrs, "color");
  if (tmp) {
    value = strToInteger (tmp);
  }

/*
 * this is testing against MAXNCOLORS, but it should test against the
 * current scheme
*/
  /*if(value < 0 || value > MAXNCOLORS) { */
  if (value < 0 || value >= scheme->n) {
    if (tmp)
      xml_warning ("color", tmp, "Out of range", data);
  }
  else {
    if (i < 0)
      data->defaults.color = value;
    else
      d->color.els[i] = d->color_now.els[i] = d->color_prev.els[i] = value;
  }

  return (value != -1);
}

gboolean
setGlyph (const xmlChar ** attrs, XMLParserData * data, gint i)
{
  const gchar *tmp;
  gint value;
  GGobiData *d = getCurrentXMLData (data);

/*
 * glyphSize  0:7
*/
  value = data->defaults.glyphSize;
  tmp = getAttribute (attrs, "glyphSize");
  if (tmp) {
    value = strToInteger (tmp);
  }

  if (value < 0 || value >= NGLYPHSIZES) {
    if (tmp)
      xml_warning ("glyphSize", tmp, "Out of range", data);
  }
  else {
    if (i < 0) {
      data->defaults.glyphSize = value;
    }
    else {
      /*
       * note that even if defaults.glyphSize was set below, during
       * the 'glyph' section, the values for record i are assigned here.
       */
      d->glyph.els[i].size = d->glyph_now.els[i].size
        = d->glyph_prev.els[i].size = value;
    }
  }

/*
 * glyphType  0:6
*/
  value = data->defaults.glyphType;
  tmp = getAttribute (attrs, "glyphType");
  if (tmp) {
    /*
     * make sure this attribute is an integer; if someone puts a
     * string here, like "plus" or "fc", value = 0 and the mistake
     * isn't caught later when value is tested.
     */
    value = mapGlyphName (tmp);
    if (value == UNKNOWN_GLYPH) {
      if (tmp[0] < '0' || tmp[0] > '6') {
        g_error ("%s is an illegal value for glyphType; it must be on [0,6]",
                 tmp);
      }

      value = strToInteger (tmp);
    }
  }
  if (value < 0 || value >= NGLYPHTYPES) {
    if (tmp)
      xml_warning ("glyphType", tmp, "Out of range", data);
  }
  else {
    if (i < 0) {
      data->defaults.glyphType = value;
    }
    else {
      /*
       * note that even if defaults.glyphType was set below, during
       * the 'glyph' section, the values for record i are assigned here.
       */
      d->glyph.els[i].type = d->glyph_now.els[i].type =
        d->glyph_prev.els[i].type = value;
    }
  }

/*
 * glyph:  strings like "plus 3" or "."
*/
  tmp = getAttribute (attrs, "glyph");
  if (tmp != NULL) {
    const gchar *next;
    gint j;
    next = tmp;
    next = strtok ((gchar *) tmp, " ");
    j = 0;
    while (next) {
      if (j == 0) {             /* type */
        value = mapGlyphName (next);
        if (i < 0) {
          data->defaults.glyphType = value;
        }
        else {
          d->glyph.els[i].type = d->glyph_now.els[i].type =
            d->glyph_prev.els[i].type = value;
        }
      }
      else {                    /* size */
        value = strToInteger (next);
        if (i < 0) {
          if (value >= 0 && value < NGLYPHTYPES) {
            data->defaults.glyphSize = value;
          }
          else {
            xml_warning ("File error:", next, "glyph improperly specified",
                         data);
          }
        }
        else {
          d->glyph.els[i].size = d->glyph_now.els[i].size =
            d->glyph_prev.els[i].size = value;
        }
      }
      j++;
      next = strtok (NULL, " ");
    }
  }

  return (value != -1);
}


void
xml_warning (const gchar * attribute, const gchar * value, const gchar * msg,
             XMLParserData * data)
{
  g_printerr ("Incorrect data (record %d)\n", data->current_record);
  g_printerr ("\t%s %s: value = %s\n", attribute, msg, value);
}

static vartabled *
applyRandomUniforms (GGobiData * d, XMLParserData * data)
{
  vartabled *vt = NULL;
  while (data->current_element < d->raw.ncols
         && (vt = vartable_element_get (data->current_element, d))
         && vt->vartype == uniform) {
    d->raw.vals[data->current_record][data->current_element] = randvalue ();
    vt = vartable_element_get (++(data->current_element), d);
  }

  return (vt);
}

static gboolean
setRecordValue (const char *tmp, GGobiData * d, XMLParserData * data)
{
  gdouble value;
  vartabled *vt;

  /* If we have a counter variable in this dataset, check whether the
     cursor is at that. */
  if (data->counterVariableIndex > -1 &&
      data->current_element == data->counterVariableIndex) {
    d->raw.vals[data->current_record][data->current_element] =
      data->current_record + 1;
    data->current_element++;
  }

  /* If reading past the last column or row, stop */
  if (data->current_record >= d->raw.nrows ||
      data->current_element >= d->raw.ncols) {
    g_printerr ("Row %d (counting from 1) has too many elements\n",
                data->current_record + 1);
    data->current_element = 0;
    return (false);
  }

/*  vt = vartable_element_get (data->current_element, d); */
  vt = applyRandomUniforms (d, data);
  if (!vt)
    return (true);

  /*
   * this is a missing value if 
   *  1. the file does not specify a string and this string is either
   *     "na", "NA", or ".", or
   *  2. the file specifies a string for NA and this is that string
   */
  if ((data->NA_identifier == NULL &&
       (strcmp (tmp, "na") == 0 ||
        strcmp (tmp, "NA") == 0 ||
        strcmp (tmp, ".") == 0)) ||
      (data->NA_identifier && strcmp (tmp, data->NA_identifier) == 0)) {
    ggobi_data_set_missing(d, data->current_record, data->current_element);    
  }
  else {

    value = asNumber (tmp);

    if (vt->vartype == categorical) {
      if (data->autoLevels && data->autoLevels[data->current_element]) {
        value = getAutoLevelIndex (tmp, data, vt);
        vt->level_counts[(gint) value]++;
      }
      else {
        gint level = checkLevelValue (vt, value);
        if (level == -1) {
          ggobi_XML_error_handler (data,
                                   "incorrect level in record %d, variable `%s', dataset `%s' in the XML input file\n",
                                   (int) data->current_record + 1, vt->collab,
                                   data->current_data->name ? data->
                                   current_data->name : "");
        }
        else {
          vt->level_counts[level]++;
        }
      }
    }
    else if (data->state == STRING) {
      ggobi_XML_error_handler (data,
                               "<string> element for non categorical variable (%s) in record %d\n",
                               vt->collab, (int) data->current_record + 1);
      value = 0;
    }

    d->raw.vals[data->current_record][data->current_element] = value;
  }

  /* If the dataset is using one of the variables as the row labels,
     then resolve the name.
   */
  /*
   *  I don't think we plan to support this, and it's buggy to boot -- dfs
   */
#if RECORD_LABELS_VARIABLE
  if (data->recordLabelsVariable == data->current_element) {
    gchar *tmp1;
    /* If this is a categorical, look up the level id. */
    gchar buf[100];
    if (ggobi_data_is_missing(d, data->current_record, data->current_element)) {
      /* sprintf(buf, "%s", "NA"); */
      tmp1 = g_strdup ("NA");
    }
    else {
      if (vt && vt->vartype == categorical) {
        /* To be correct, we need to match the level_values and find the
           corresponding entry. */
        tmp1 = g_strchomp((gchar *) GGobi_getLevelName (vt, value));
        if (tmp1)
          tmp1 = g_strdup (tmp1);
      }
      else {
        sprintf (buf, "%f", value);
        tmp1 = g_strdup (buf);
      }
    }
    g_array_insert_val (d->rowlab, data->current_record, tmp1);
    g_free (tmp1);
  }
#endif

  return (true);
}

/*
  Read the values for this record from free-formatted text. The entries
  are white-space delimited. They should not have quotes or anything
  that needs to be escaped.
*/
gboolean
setRecordValues (XMLParserData * data, const xmlChar * line, gint len,
                 gint ncols)
{
  const gchar *tmp;
  GGobiData *d = getCurrentXMLData (data);

  if (ncols == -1) {
    ncols = d->ncols;
  }

  if (!line) {
    applyRandomUniforms (d, data);
    return (false);
  }
  tmp = strtok ((gchar *) line, " \t\n");

  while (tmp && (tmp < (gchar *) (line + len))) {
    /*
       g_printerr("current element %d token %s\n", data->current_element,
       tmp);
     */
    if (setRecordValue (tmp, d, data) == false)
      return (false);
    data->current_element++;
    tmp = strtok (NULL, " \t\n");
    /*    printf("%d %d \n",data->current_record,ncols); */
  }
  if (data->current_element < ncols) {
    ggobi_XML_error_handler (data, "Not enough elements\n");
    /*    printf("%d %d \n",data->current_record,data->current_element); */
    /*
       g_printerr ("Record %d has insufficient elements: %d < %d\n",
       data->current_record, data->current_element,
       d->ncols);
     */
  }


  applyRandomUniforms (d, data);
  return (true);
}

/*
  Convert the specified string to a numeric value.
  This is now done in a locale-insensitive way, so all input that uses this
  function needs to use the C locale (ie decimal points are '.')
 */
gdouble
asNumber (const char *sval)
{
  return (g_ascii_strtod (sval, NULL));
}




/*
   Read the declaration of a variable, gathering its information
   from the specified attributes.
   This includes its name, transformation name, etc.

   Called in response to a <variable>, <realvariable> or
   <categoricalvariable> tag.
 */

gboolean
newVariable (const xmlChar ** attrs, XMLParserData * data,
             const xmlChar * tagName)
{
  const gchar *tmp, *tmp1;
  GGobiData *d = getCurrentXMLData (data);
  vartabled *el;

  if (data->current_variable >= d->ncols) {
    g_printerr
      ("Too many variables (%d) given number given in the <variables count='%d'> element for dataset %s\n",
       data->current_variable, d->raw.ncols, d->name);
    return (false);
  }

  el = vartable_element_get (data->current_variable, d);

  data->variable_transform_name_as_attribute = false;

  tmp = getAttribute (attrs, "name");
  ggobi_data_set_col_name(d, data->current_variable, (gchar*) tmp);

  tmp = getAttribute (attrs, "nickname");
  if (tmp != NULL) el->nickname = g_strdup (tmp);

  /*
   * I don't think we plan to support this, so I'm ifdef-ing out
   * some buggy code elsewhere in the file -- dfs
   */
#if RECORD_LABELS_VARIABLE
  tmp = getAttribute (attrs, "recordLabel");
  if (tmp != NULL) {
    data->recordLabelsVariable = data->current_variable;
  }
#endif

  tmp = getAttribute (attrs, "min");
  tmp1 = getAttribute (attrs, "max");
  if (tmp && tmp1) {
    gdouble mn, mx;
    mn = asNumber (tmp);
    mx = asNumber (tmp1);
    el->lim_specified.min = mn < mx ? mn : mx;
    el->lim_specified.max = mn > mx ? mn : mx;
    /* ? */
    el->lim_specified_tform.min = el->lim_specified.min;
    el->lim_specified_tform.max = el->lim_specified.max;

    if (mn > mx) {
      g_printerr ("Minimum is greater than maximum for variable %s\n",
                  el->collab);
    }
    el->lim_specified_p = true;
  }


  if (strcmp ((const char *) tagName, "categoricalvariable") == 0) {
    el->vartype = categorical;

    /* Mark this as being a variable for which we must compute the levels. */
    if ((tmp = getAttribute (attrs, "levels")) && strcmp (tmp, "auto") == 0) {
      if (data->autoLevels == NULL) {
        data->autoLevels = (GHashTable **)
          g_malloc0 (sizeof (GHashTable *) * data->current_data->ncols);
      }
      /* glib-2.0 provides a g_hash_table_new_full with which we can
         specify the `free' routine for elements. This should simplify
         (slightly) releaseCurrentDataInfo(). */
      data->autoLevels[data->current_variable] = g_hash_table_new (g_str_hash,
                                                                   g_str_equal);
    }
  }
  else if (strcmp ((const char *) tagName, "integervariable") == 0) {
    el->vartype = integer;
  }
  else if (strcmp ((const char *) tagName, "countervariable") == 0) {
    el->vartype = counter;
  }
  else if (strcmp ((const char *) tagName, "randomuniformvariable") == 0) {
    el->vartype = uniform;
  }                             /* real by default */


  tmp = getAttribute (attrs, "time");
  if (tmp && (strcmp (tmp, "yes") == 0 || strcmp (tmp, "true") == 0)) {
    el->isTime = true;
  }


  return (true);
}


/*
   Reads the number of variables in the dataset from the attributes
   and allocates space for them in the ggobid structure.
   At this point, we have the number of records and variables
   and can initialize the data areas of the ggobid structure.

    Called in response to a <variables> tag. (Note the plural.)
 */
gboolean
allocVariables (const xmlChar ** attrs, XMLParserData * data)
{
  const gchar *tmp = getAttribute (attrs, "count");
  GGobiData *d = getCurrentXMLData (data);

  if (tmp == NULL) {
    g_error ("No count for variables attribute\n");
  }

  d->ncols = strToInteger (tmp);


  /* The following is unlikely to happen as we have not got the count
     of the number of rows at this stage. But we leave it here just
     in case there are datasets for which the input gives the count
     in the top-level tag. */
  if (d->nrows > 0 && d->ncols > 0) {
    arrayf_alloc (&d->raw, d->nrows, d->ncols);
    arrays_alloc (&d->missing, d->nrows, d->ncols);
    br_hidden_alloc (d);
  }


  vartable_alloc (d);
  vartable_init (d);


  return (true);
}


/*
  Reads the text in name and assigns it as the name of the
  variable currently being read within the 
  <variable> tag. The index for the variable is stored in 
  data->current_variable.

   Called when parsing free-formatted text within a <variable> tag.
 */
gboolean
setVariableName (XMLParserData * data, const xmlChar * name, gint len)
{
  gchar *tmp = (gchar *) g_malloc (sizeof (gchar) * (len + 1));
  GGobiData *d = getCurrentXMLData (data);
  vartabled *el = vartable_element_get (data->current_variable, d);
  gchar *lbl = g_strdup_printf ("Var %d", data->current_variable);

  tmp[len] = '\0';
  memcpy (tmp, name, len);

  /* Handle the case where we have multiple calls to the characters
     handler for the same variable because the data is split
   */
  if (el->collab != NULL) {
    /* need to append tmp to the existing value. */
  }

  el->collab = tmp;

  /* Note that if we do have multiple calls to this for the same
     variable then we cannot handle the case where the 
     user does not specify the transformation variable
     unless we use a flag in XMLParserData. This is
     variable_transform_name_as_attribute.
   */
  /* problem: this is never NULL, it's either 'Var n' or something specified */
  /*if (el->collab_tform == NULL) { */
  if (strcmp (el->collab_tform, lbl) == 0) {
    el->collab_tform = g_strdup (tmp);
  }

  g_free (lbl);
  g_free (tmp);

  return (true);
}

/*----------------------------------------------------------------------*/


/*
 Prints the attributes.
 For debugging.
*/
void
showAttributes (const xmlChar ** attrs)
{
  const xmlChar **tmp;
  tmp = attrs;
  while (tmp && tmp[0]) {
    g_printerr ("\t %s=%s\n", tmp[0], tmp[1]);
    tmp += 2;
  }
}

void
freeLevelHashEntry (gpointer key, gpointer value, gpointer data)
{
  g_free (value);
  if (data)
    g_free (key);
}

static void
releaseCurrentDataInfo (XMLParserData * parserData)
{
  if (!parserData->current_data)
    return;

/*
   if(parserData->idTable && parserData->usesStringIds == false) {
      g_hash_table_foreach(parserData->idTable,
        (GHFunc) freeLevelHashEntry, parserData);
      g_hash_table_destroy(parserData->idTable); 
   }
*/

  if (parserData->autoLevels) {
    int i;
    for (i = 0; i < parserData->current_data->ncols; i++) {
      if (parserData->autoLevels[i]) {
        /* don't free the keys (so pass NULL as third argument) 
           since these are used in the level_names array. */
        g_hash_table_foreach (parserData->autoLevels[i],
                              (GHFunc) freeLevelHashEntry, NULL);
        g_hash_table_destroy (parserData->autoLevels[i]);
      }
    }
    parserData->autoLevels = NULL;
  }
}


gboolean
setDataset (const xmlChar ** attrs, XMLParserData * parserData,
            enum xmlDataState type)
{
  GGobiData *data = ggobi_data_new (0, 0);
  const gchar *name, *nickname;

  name = getAttribute (attrs, "name");
  nickname = getAttribute (attrs, "nickname");
  ggobi_data_set_name(data, (gchar *) name, (gchar *) nickname);

  parserData->current_data = data;
  parserData->counterVariableIndex = -1;

  if (type == EDGES) {
    setDatasetInfo (attrs, parserData);
  }

  return (true);
}


GGobiData *
getCurrentXMLData (XMLParserData * parserData)
{
  GGobiData *data = parserData->current_data;
  if (data == NULL) {
    data = ggobi_data_new (0, 0);
    parserData->current_data = data;
  }
  if (data->input == NULL)
    data->input = parserData->input;
  return (data);
}


void
setEdge (gint start, gint end, gint i, GGobiData * d)
{
  /*-- if encountering the first edge, allocate endpoints array --*/
  if (d->edge.n == 0)
    edges_alloc (d->nrows, d);
}

gboolean
readXMLRecord (const xmlChar ** attrs, XMLParserData * data)
{
  GGobiData *d = getCurrentXMLData (data);
  const gchar *tmp;
  gchar *stmp;
  gint i = data->current_record;

  if (i == d->nrows) {
    g_error ("There are more records than declared for '%s'; exiting.",
             d->name);
  }

  data->current_element = 0;

  tmp = getAttribute (attrs, "label");
  if (!tmp) {
    if (data->recordLabelsVariable > -1) {
      /* Wait until we have read the specific values! */
    }
    else {
      /* Length is to hold the current record number as a string. */
      stmp = g_malloc (sizeof (gchar) * 10);
      g_snprintf (stmp, 9, "%d", i);
    }
  }
  else
    stmp = g_strdup (tmp);

  g_array_insert_val (d->rowlab, data->current_record, stmp);

  setColor (attrs, data, i);
  setGlyph (attrs, data, i);
  setHidden (attrs, data, i);

/*
 * Probably something's missing here:  if any record has an
 * id, then does every record need one?  I think so.  -- dfs
 */

  tmp = getAttribute (attrs, "id");
  if (tmp) {
    guint *ptr;
    /*int value; */
    gchar *dupTmp;
    /* No need to check since this will either be the first and hence
       NULL or already created, so can use an else for this condition. */
    if (data->idTable == NULL) {
      data->idTable = g_hash_table_new (g_str_hash, g_str_equal);
      d->idTable = data->idTable;
      d->rowIds = (gchar **) g_malloc0 (sizeof (gchar *) * d->nrows);
    }
    else {
      if (g_hash_table_lookup (data->idTable, tmp))
        ggobi_XML_error_handler (data,
                                 "duplicated id in record %d of dataset %s\n",
                                 data->current_record + 1,
                                 data->current_data->name);
    }

    ptr = (guint *) g_malloc (sizeof (guint));
    ptr[0] = i;
    g_hash_table_insert (data->idTable, dupTmp = intern (data, tmp), ptr);
    d->rowIds[i] = dupTmp;
  }

/*
 * Probably something's missing here:  if edges should be
 * present, then every record should have a source and an
 * endpoint, and there's no validation going on now. --dfs
*/

  /* Read the edge source and destination pair if, present. */
  tmp = getAttribute (attrs, "source");
  if (tmp != (const gchar *) NULL) {
    const gchar *dest;
    dest = getAttribute (attrs, "destination");
    if (!dest) {
      xml_warning ("edge specification error:", tmp,
                   "source but no destination attribute for record.", data);
      return (true);
    }
    if (strcmp (tmp, dest) == 0) {
      xml_warning ("edge specification error:", tmp,
                   "source is the same as destination for record.", data);
      return (true);
    }

    if (d->edge.sym_endpoints == NULL) {
      d->edge.n = d->nrows;
      d->edge.sym_endpoints = (SymbolicEndpoints *)
        g_malloc (sizeof (SymbolicEndpoints) * d->edge.n);
    }

    d->edge.sym_endpoints[data->current_record].a = intern (data, tmp);
    d->edge.sym_endpoints[data->current_record].b = intern (data, dest);
    d->edge.sym_endpoints[data->current_record].jpartner = -1;
  }

  return (true);
}

gchar *
intern (XMLParserData * data, const char *el)
{
  gchar *ans;

  if (data->idNamesTable == NULL) {
    data->idNamesTable = g_hash_table_new (g_str_hash, g_str_equal);
  }

  ans = g_hash_table_lookup (data->idNamesTable, el);
  if (!ans) {
    ans = g_strdup (el);
    g_hash_table_insert (data->idNamesTable, ans, ans);
  }
  return (ans);
}


gboolean
setBrushStyle (const xmlChar ** attrs, XMLParserData * data)
{
  const gchar *tmp;
  gint value;
  gboolean retval = true;

  tmp = getAttribute (attrs, "color");
  if (tmp != NULL) {
    colorschemed *scheme = data->gg->activeColorScheme;
    value = strToInteger (tmp);
    if (value >= 0 && value < scheme->n) {
      data->gg->color_id = value;
    }
    else {
      xml_warning ("File error:", tmp, "brushing color improperly specified",
                   data);
      return false;
    }
  }

/*
 * glyphType  0:6
*/
  tmp = getAttribute (attrs, "glyphType");
  if (tmp != NULL) {
    /*
     * make sure this attribute is an integer; if someone puts a
     * string here, like "plus" or "fc", value = 0 and the mistake
     * isn't caught later when value is tested.
     */
    if (tmp[0] < '0' || tmp[0] > '6') {
      xml_warning ("brushing glyphType", tmp, "Must be on [0,6]\n", data);
      return false;
    }
    value = mapGlyphName (tmp);
    if (value == UNKNOWN_GLYPH)
      value = strToInteger (tmp);

    if (value < 0 || value >= NGLYPHTYPES) {
      xml_warning ("glyphType", tmp, "Out of range", data);
      return false;
    }
    else {
      data->gg->glyph_id.type = value;
    }
  }

/*
 * glyphSize  0:7
*/
  tmp = getAttribute (attrs, "glyphSize");
  if (tmp != NULL) {
    value = strToInteger (tmp);

    if (value < 0 || value >= NGLYPHSIZES) {
      xml_warning ("glyphSize", tmp, "Out of range", data);
    }
    else {
      data->gg->glyph_id.size = value;
    }
  }


  tmp = getAttribute (attrs, "glyph");
  if (tmp != NULL) {
    const gchar *next;
    gint j;
    next = tmp;
    next = strtok ((gchar *) tmp, " ");
    j = 0;
    while (next) {
      if (j == 0) {             /* type */
        value = mapGlyphName (next);
        data->gg->glyph_id.type = value;
      }
      else {                    /* size */
        value = strToInteger (next);
        if (value >= 0 && value < NGLYPHTYPES) {
          data->gg->glyph_id.size = value;
        }
        else {
          xml_warning ("File error:", next,
                       "brushing glyph improperly specified", data);
          retval = false;
        }
      }
      j++;
      next = strtok (NULL, " ");
    }
  }

  return retval;
}


gint
getAutoLevelIndex (const char *const label, XMLParserData * data,
                   vartabled * el)
{
  GHashTable *tbl = data->autoLevels[data->current_element];
  gpointer val;
  gint index = -1;
  gint i;
  val = g_hash_table_lookup (tbl, (gconstpointer) label);

  if (!val) {
    gint *itmp;
    gint n = el->nlevels + 1;
    if (n == 1) {
      el->level_values = (gint *) g_malloc (sizeof (gint) * n);
      el->level_counts = (gint *) g_malloc (sizeof (gint) * n);
      el->level_names = (gchar **) g_malloc (sizeof (gchar *) * n);
      for (i = 0; i < el->nlevels; i++)
        el->level_counts[i] = 0;
    }
    else {
      el->level_values =
        (gint *) g_realloc (el->level_values, sizeof (gint) * n);
      el->level_counts =
        (gint *) g_realloc (el->level_counts, sizeof (gint) * n);
      el->level_names =
        (gchar **) g_realloc (el->level_names, sizeof (gchar *) * n);
    }
    el->level_counts[n - 1] = 0;
    el->level_values[n - 1] = n - 1;
    el->level_names[n - 1] = g_strdup (label);

    itmp = (gint *) g_malloc (sizeof (gint));
    *itmp = index = n - 1;
    g_hash_table_insert (tbl, el->level_names[n - 1], itmp);
    el->nlevels++;
  }
  else
    index = *((gint *) val);

  return (index);
}

/* Routines for walking the hash table and getting all the row labels
   into an array. */

static void
getLabel (gpointer key, gpointer val, gchar ** labels)
{
  if (val) {
    labels[*(guint *) val] = (gchar *) key;
  }
}

gchar **
getRowLabsFromTable (GHashTable * tbl, gchar ** names)
{
  if (!names)
    names = (gchar **) g_malloc (sizeof (gchar *) * g_hash_table_size (tbl));

  g_hash_table_foreach (tbl, (GHFunc) getLabel, names);

  return (names);
}

gboolean
isXMLFile (const gchar * fileName, ggobid * gg, GGobiPluginInfo * info)
{

  FILE *f;
  gint c;
  gchar *tmp;

  if (isURL (fileName))
    return (true);


  tmp = strrchr (fileName, '.');

  if (!tmp) {
    gchar buf[256];
    sprintf (buf, "%s.xml", fileName);
    if (isXMLFile (buf, gg, info))
      return (true);
  }

  if (tmp && (strcmp (tmp, ".xmlz") == 0 || strcmp (tmp, ".gz") == 0)) {
    /* desc->canVerify = false; */
    return (true);
  }


  f = fopen (fileName, "r");
  if (f == NULL)
    return (false);

/*  desc->canVerify = true; */
  while ((c = getc (f)) != EOF) {
    if (c == ' ' || c == '\t' || c == '\n')
      continue;
    if (c == '<') {
      gchar buf[10];
      fgets (buf, 5, f);
      fclose (f);
      if (strcmp (buf, "?xml") == 0) {
        return (true);
      }
      else
        return (false);
    }
  }

  return (false);
}