File: dataio.c

package info (click to toggle)
gretl 0.99.2-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 7,304 kB
  • ctags: 3,210
  • sloc: ansic: 43,338; sh: 6,567; makefile: 807; perl: 529
file content (3256 lines) | stat: -rw-r--r-- 81,220 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
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
/*
 *  Copyright (c) by Ramu Ramanathan and Allin Cottrell
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include "libgretl.h"
#include "internal.h"
#include <zlib.h>
#include <ctype.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>

#include <libxml/xmlmemory.h>
#include <libxml/parser.h>

#define QUOTE '\''

static int prepZ (double ***pZ, const DATAINFO *pdinfo);
static int writelbl (const char *lblfile, const int *list, 
		     const DATAINFO *pdinfo);
static int writehdr (const char *hdrfile, const int *list, 
		     const DATAINFO *pdinfo, const int opt);
static double obs_float (const DATAINFO *pdinfo, const int end);
static int write_xmldata (const char *fname, const int *list, 
			  double **Z, const DATAINFO *pdinfo, 
			  int opt, PATHS *ppaths);
static int xmlfile (const char *fname);

static char STARTCOMMENT[3] = "(*";
static char ENDCOMMENT[3] = "*)";

/**
 * free_Z:
 * @Z: data matrix.
 * @pdinfo: data information struct.
 *
 * Do a deep free on the data matrix.
 * 
 */

void free_Z (double **Z, DATAINFO *pdinfo)
{
    int i;

    for (i=0; i<pdinfo->v; i++)
	free(Z[i]);
    free(Z);
}

/**
 * clear_datainfo:
 * @pdinfo: data information struct.
 * @code: either CLEAR_FULL or CLEAR_SUBSAMPLE.
 *
 * Free the allocated content of a data information struct.
 * 
 */

void clear_datainfo (DATAINFO *pdinfo, int code)
{
    int i;

    if (pdinfo->S != NULL) {
	for (i=0; i<pdinfo->n; i++) 
	   free(pdinfo->S[i]); 
	free(pdinfo->S);
	pdinfo->S = NULL;
	pdinfo->markers = 0;
    } 
    /* if this is not a sub-sample datainfo, free varnames and labels */
    if (code == CLEAR_FULL) {
	if (pdinfo->varname != NULL) {
	    for (i=0; i<pdinfo->v; i++) 
		free(pdinfo->varname[i]); 
	    free(pdinfo->varname);
	    pdinfo->varname = NULL;
	}
	if (pdinfo->label != NULL) {
	    for (i=0; i<pdinfo->v; i++) 
		free(pdinfo->label[i]); 
	    free(pdinfo->label);
	    pdinfo->label = NULL;
	}
	if (pdinfo->descrip) {
	    free(pdinfo->descrip);
	    pdinfo->descrip = NULL;
	}
	if (pdinfo->vector) {
	    free(pdinfo->vector);
	    pdinfo->vector = NULL;
	}
    }
}

/* ......................................................... */

static void dataset_dates_defaults (DATAINFO *pdinfo)
{
    strcpy(pdinfo->stobs, "1");
    sprintf(pdinfo->endobs, "%d", pdinfo->n);
    pdinfo->sd0 = 1.0;
    pdinfo->pd = 1;
    pdinfo->time_series = 0;
    pdinfo->extra = 0; 
}

/* ......................................................... */

static int skipcomments (FILE *fp, const char *str)
/* Skips past comments in .hdr file.  Returns 
   0 if comments found, otherwise 1.
*/
{
    char commentword[MAXLEN];  /* should be big enough to accommodate
			          strings among the comments? */
    commentword[0] = '\0';
    if (strncmp(str, STARTCOMMENT, 2) == 0) {
        while (strcmp(commentword, ENDCOMMENT)) {
            fscanf(fp, "%s", commentword);
        }
        return 0;
    } else return 1;
}

/* ................................................. */

static int comment_lines (FILE *fp, char **pbuf)
{
    char s[MAXLEN], *mybuf = NULL;
    int count = 0, bigger = 1, bufsize;

    if (fgets(s, MAXLEN-1, fp) == NULL) return 0;
    if (!strncmp(s, STARTCOMMENT, 2)) {
	*pbuf = malloc(20 * MAXLEN);
	if (*pbuf == NULL) return -1;
	**pbuf = '\0';
	do {
	    if (fgets(s, MAXLEN-1, fp) == NULL) break;
	    if (!strncmp(s, ENDCOMMENT, 2)) break;
	    count++;
	    if (count > 20*bigger) {
		bigger++;
		bufsize = 20 * MAXLEN * bigger;
		mybuf = realloc(*pbuf, bufsize);
		if (mybuf == NULL) return -1;
		else *pbuf = mybuf;
	    }
	    strcat(*pbuf, s);
	} while (s != NULL);
    }
    return count;
}

/* ................................................. */

static int dataset_allocate_markers (DATAINFO *pdinfo)
{
    int i;

    pdinfo->S = malloc(pdinfo->n * sizeof(char *));
    if (pdinfo->S == NULL) return 1; 
    for (i=0; i<pdinfo->n; i++) {
	pdinfo->S[i] = malloc(9);
	if (pdinfo->S[i] == NULL) {
	    free(pdinfo->S);
	    return 1; 
	}
    }
    return 0;
}

/* ................................................. */

static int dataset_allocate_varnames (DATAINFO *pdinfo)
{
    int i, v = pdinfo->v;
    
    pdinfo->varname = malloc(v * sizeof(char *));
    pdinfo->label = malloc(v * sizeof(char *));
    pdinfo->vector = malloc(v);
    if (pdinfo->varname == NULL || 
	pdinfo->label == NULL ||
	pdinfo->vector == NULL) return 1;
    for (i=0; i<v; i++) {
	pdinfo->varname[i] = malloc(9);
	if (pdinfo->varname[i] == NULL) return 1;
	pdinfo->label[i] = malloc(MAXLABEL);
	if (pdinfo->label[i] == NULL) return 1;
	pdinfo->label[i][0] = '\0';
	pdinfo->vector[i] = 1;
    }
    strcpy(pdinfo->varname[0], "const");
    strcpy(pdinfo->label[0], _("auto-generated constant"));
    return 0;
}

/**
 * datainfo_new:
 *
 * Create a new data information struct pointer from scratch,
 * properly initialized.
 * 
 * Returns: pointer to data information struct, or NULL on error.
 *
 */

DATAINFO *datainfo_new (void)
{
    DATAINFO *dinfo;

    dinfo = malloc(sizeof *dinfo);
    if (dinfo == NULL) return NULL;

    dinfo->v = 0;
    dinfo->n = 0;
    dinfo->pd = 1;
    dinfo->bin = 0;
    dinfo->extra = 0;
    dinfo->sd0 = 1.0;
    dinfo->t1 = 0;
    dinfo->t2 = 0;
    dinfo->stobs[0] = '\0';
    dinfo->endobs[0] = '\0';
    dinfo->varname = NULL;
    dinfo->label = NULL;    
    dinfo->markers = 0;    
    dinfo->S = NULL;
    dinfo->descrip = NULL;
    dinfo->vector = NULL;

    return dinfo;
}

/**
 * create_new_dataset:
 * @pZ: pointer to data matrix.
 * @nvar: number of variables.
 * @nobs: number of observations per variable 
 * @markers: 1 if there are case markers for the observations, 0
 * otherwise.
 *
 * Create a new data information struct corresponding to a given
 * data matrix.
 * 
 * Returns: pointer to data information struct, or NULL on error.
 *
 */

DATAINFO *create_new_dataset (double ***pZ,  
			      int nvar,
			      int nobs,
			      int markers
			      )
{
    DATAINFO *pdinfo;

    pdinfo = malloc(sizeof *pdinfo);
    if (pdinfo == NULL) return NULL;

    pdinfo->v = nvar;
    pdinfo->n = nobs;
    *pZ = NULL;
    if (start_new_Z(pZ, pdinfo, 0)) {
	free(pdinfo);
	return NULL;
    }
    pdinfo->markers = (short) markers;
    if (pdinfo->markers) {
	if (dataset_allocate_markers(pdinfo)) {
	    free_datainfo(pdinfo);
	    return NULL;
	}
    } 
    dataset_dates_defaults(pdinfo);
    pdinfo->descrip = NULL;
    return pdinfo;
}

/**
 * start_new_Z:
 * @pZ: pointer to data matrix.
 * @pdinfo: data information struct.
 * @resample: 1 if we're sub-sampling from a full data set, 0 otherwise.
 *
 * Initialize data matrix (add the constant) and the data information
 * struct.
 * 
 * Returns: 0 on successful completion, 1 on error.
 *
 */

int start_new_Z (double ***pZ, DATAINFO *pdinfo, int resample)
{
    if (prepZ(pZ, pdinfo)) return 1;

    pdinfo->t1 = 0; 
    pdinfo->t2 = pdinfo->n - 1;

    if (resample) {
	pdinfo->varname = NULL;
	pdinfo->label = NULL;
    } else {
	if (dataset_allocate_varnames(pdinfo))
	    return 1;
    }

    pdinfo->S = NULL;
    pdinfo->markers = 0;
    pdinfo->descrip = NULL;
    
    return 0;
}

/* ................................................. */

static int prepZ (double ***pZ, const DATAINFO *pdinfo)
    /* allocate data array and put in constant */
{
    int i, t;

    if (*pZ != NULL) free(*pZ);
    *pZ = malloc(pdinfo->v * sizeof **pZ);
    if (*pZ == NULL) return 1;
    for (i=0; i<pdinfo->v; i++) {
	(*pZ)[i] = malloc(pdinfo->n * sizeof ***pZ);
	if (*pZ == NULL) return 1;
    }

    for (t=0; t<pdinfo->n; t++) (*pZ)[0][t] = 1.0; 
    return 0;
}

/* ................................................. */

static void eatspace (FILE *fp)
{
    char c;

    while (1) {
	c = fgetc(fp);
	if (!isspace((unsigned char) c)) {
	    ungetc(c, fp);
	    return;
	}
    }
}

/* ................................................. */

static int readdata (FILE *fp, const DATAINFO *pdinfo, double **Z)
{
    int i, t, n = pdinfo->n;
    char c, marker[9];
    float x;

    gretl_errmsg[0] = '\0';

    if (pdinfo->bin == 1) { /* single-precision binary data */
	for (i=1; i<pdinfo->v; i++) {
	    for (t=0; t<n; t++) {
		if (!fread(&x, sizeof(float), 1, fp)) {
		    sprintf(gretl_errmsg, _("WARNING: binary data read error at "
			    "var %d"), i);
		    return 1;
		}
		Z[i][t] = (double) x;
	    }
	}
    }
    else if (pdinfo->bin == 2) { /* double-precision binary data */
	for (i=1; i<pdinfo->v; i++) {
	    if (!fread(Z[i], sizeof(double), n, fp)) {
		sprintf(gretl_errmsg, 
			_("WARNING: binary data read error at var %d"), i);
		return 1;
	    }
	}
    } else { /* ascii data file */
	for (t=0; t<n; t++) {
	    eatspace(fp);
	    c = fgetc(fp);  /* test for a #-opened comment line */
	    if (c == '#') while (c != '\n') c = fgetc(fp);
	    else ungetc(c, fp);
	    if (pdinfo->markers) {
		fscanf(fp, "%8s", marker);
		strcpy(pdinfo->S[t], marker);
	    }
	    for (i=1; i<pdinfo->v; i++) {
		if ((fscanf(fp, "%lf", &Z[i][t])) != 1) {
		    sprintf(gretl_errmsg, 
			    _("WARNING: ascii data read error at var %d, "
			    "obs %d"), i, t + 1);
		    return 1;
		}
	    }
	}
    }
    return 0;
}

/* ................................................. */

static int gz_readdata (gzFile fz, const DATAINFO *pdinfo, double **Z)
{
    int i, t, n = pdinfo->n;
    
    gretl_errmsg[0] = '\0';

    if (pdinfo->bin == 1) { /* single-precision binary data */
	float xx;

	for (i=1; i<pdinfo->v; i++) {
	    for (t=0; t<n; t++) {
		if (!gzread(fz, &xx, sizeof xx)) {
		    sprintf(gretl_errmsg, _("WARNING: binary data read error at "
			    "var %d"), i);
		    return 1;
		}
		Z[i][t] = (double) xx;
	    }
	}
    }
    else if (pdinfo->bin == 2) { /* double-precision binary data */
	for (i=1; i<pdinfo->v; i++) {
	    if (!gzread(fz, &Z[i][0], n * sizeof(double))) {
		sprintf(gretl_errmsg, 
			_("WARNING: binary data read error at var %d"), i);
		return 1;
	    }
	}
    } else { /* ascii data file */
	char *line, numstr[24];
	int llen = pdinfo->v * 32;
	size_t offset;

	line = malloc(llen);
	if (line == NULL) return E_ALLOC;
	for (t=0; t<n; t++) {
	    offset = 0L;
	    if (!gzgets(fz, line, llen - 1)) {
		sprintf(gretl_errmsg, _("WARNING: ascii data read error at "
			"obs %d"), t + 1);
		free(line);
		return 1;
	    }
	    chopstr(line);
	    compress_spaces(line);
	    if (line[0] == '#') {
		t--;
		continue;
	    }
	    if (pdinfo->markers) {
		if (sscanf(line, "%8s", pdinfo->S[t]) != 1) {
		   sprintf(gretl_errmsg, 
			   _("WARNING: failed to read case marker for "
			   "obs %d"), t + 1);
		   free(line);
		   return 1;
		}
		pdinfo->S[t][8] = 0;
		offset += strlen(pdinfo->S[t]) + 1;
	    }
	    for (i=1; i<pdinfo->v; i++) {
		if (sscanf(line + offset, "%23s", numstr) != 1) {
		    sprintf(gretl_errmsg, 
			    _("WARNING: ascii data read error at var %d, "
			    "obs %d"), i, t + 1);
		    return 1;
		}
		numstr[23] = 0;
		Z[i][t] = atof(numstr);
		if (i < pdinfo->v - 1)
		    offset += strlen(numstr) + 1;
	    }
	}
	free(line);
    }
    return 0;
}

/**
 * check_varname:
 * @varname: putative name for variable.
 * 
 * Check a variable name for legality.
 * 
 * Returns: 0 if name is OK, 1 if not.
 *
 */

int check_varname (const char *varname)
{
    int i, n = strlen(varname);

    gretl_errmsg[0] = '\0';
    
    if (!(isalpha((unsigned char) varname[0]))) {
        sprintf(gretl_errmsg, _("First char of varname ('%c') is bad\n"
               "(first must be alphabetical)"), varname[0]);
        return 1;
    }
    for (i=1; i<n; i++) {
        if (!(isalpha((unsigned char) varname[i]))  
            && !(isdigit((unsigned char) varname[i]))
            && varname[i] != '_') {
	    if (isprint((unsigned char) varname[i]))
		sprintf(gretl_errmsg, _("Varname contains illegal character '%c'\n"
			"Use only letters, digits and underscore"), 
			varname[i]);
	    else
		sprintf(gretl_errmsg, _("Varname contains illegal character 0x%x\n"
			"Use only letters, digits and underscore"), 
			(unsigned) varname[i]);
            return 1;
        }
    }
    return 0;
}   

/* ................................................ */

static int readhdr (const char *hdrfile, DATAINFO *pdinfo)
{
    FILE *fp;
    int n, i = 0, panel = 0, descrip = 0;
    char str[MAXLEN], byobs[6], option[8];

    gretl_errmsg[0] = '\0';

    fp = fopen(hdrfile, "r");
    if (fp == NULL) {
	sprintf(gretl_errmsg, _("Couldn't open file %s"),  hdrfile);
	return E_FOPEN;
    }
    fscanf(fp, "%s", str);
    i += skipcomments(fp, str); 
    while (1) { /* find number of variables */
        if (fscanf(fp, "%s", str) != 1) {
	    fclose(fp);
	    sprintf(gretl_errmsg, _("Opened header file %s\n"
		    "Couldn't find list of variables (must "
		    "be terminated with a semicolon)"), hdrfile);
	    return 1;
	}
	n = strlen(str);
	if (str[n-1] == ';') {
	    if (n > 1) i++;
	    break;
	} else i++;
    }
    pdinfo->v = i + 1;
    fclose(fp);

    pdinfo->S = NULL;
    if (dataset_allocate_varnames(pdinfo)) return E_ALLOC;

    i = 1;
    fp = fopen(hdrfile, "r");
    str[0] = 0;
    fscanf(fp, "%s", str);
    if (skipcomments(fp, str)) {
        safecpy(pdinfo->varname[i], str, 8);
	if (check_varname(pdinfo->varname[i++])) 
	    goto varname_error;
    } else
	descrip = 1; /* comments were found */
    while (1) {
        fscanf(fp, "%s", str);
	n = strlen(str);
	if (str[n-1] != ';') {
            safecpy(pdinfo->varname[i], str, 8);
	    if (check_varname(pdinfo->varname[i++])) 
		goto varname_error;
        } else {
	    if (n > 1) {
		safecpy(pdinfo->varname[i], str, n-1);
		pdinfo->varname[i][n] = '\0';
		if (check_varname(pdinfo->varname[i]))
		    goto varname_error; 
	    }
	    break;
	}
    }

    fscanf(fp, "%d", &pdinfo->pd);
    fscanf(fp, "%s", pdinfo->stobs);
    fscanf(fp, "%s", pdinfo->endobs);
    pdinfo->sd0 = atof(pdinfo->stobs);
    pdinfo->n = dateton(pdinfo->endobs, pdinfo) + 1;
    pdinfo->extra = 0;    

    if (pdinfo->sd0 >= 2.0) 
        pdinfo->time_series = TIME_SERIES; /* actual time series? */
    else if (pdinfo->sd0 > 1.0) {
	pdinfo->time_series = STACKED_TIME_SERIES; /* panel data? */
    }
    else pdinfo->time_series = 0;

    pdinfo->bin = 0;
    pdinfo->markers = 0;
    if (fscanf(fp, "%5s %7s", byobs, option) == 2) {
	if (strcmp(option, "SINGLE") == 0)
	    pdinfo->bin = 1;
	else if (strcmp(option, "BINARY") == 0)
	    pdinfo->bin = 2;
	else if (strcmp(option, "MARKERS") == 0) 
	    pdinfo->markers = 1;
	else if (strcmp(option, "PANEL2") == 0) {
	    panel = 1;
	    pdinfo->time_series = STACKED_TIME_SERIES;
	} else if (strcmp(option, "PANEL3") == 0) {
	    panel = 1;
	    pdinfo->time_series = STACKED_CROSS_SECTION;
	}
    }
    if (!panel && fscanf(fp, "%6s", option) == 1) {
	if (strcmp(option, "PANEL2") == 0)
	    pdinfo->time_series = STACKED_TIME_SERIES;
	else if (strcmp(option, "PANEL3") == 0)
	    pdinfo->time_series = STACKED_CROSS_SECTION;
    }
    if (fp != NULL) fclose(fp);

    /* last pass, to pick up comments */
    pdinfo->descrip = NULL;
    if (descrip) {
	char *dbuf = NULL;
	int lines;

	fp = fopen(hdrfile, "r");
	if (fp == NULL) return 0;
	if ((lines = comment_lines(fp, &dbuf)) > 0) {
	    delchar('\r', dbuf);
	    pdinfo->descrip = malloc(strlen(dbuf) + 1);
	    if (pdinfo->descrip != NULL) 
		strcpy(pdinfo->descrip, dbuf);
	    free(dbuf);
	}
	else if (lines < 0) 
	    fprintf(stderr, _("Failed to store data comments\n"));
	fclose(fp);
    } 
	
    return 0;

    varname_error:
    fclose(fp);
    clear_datainfo(pdinfo, CLEAR_FULL);
    return E_DATA;
}

/* .......................................................... */

static int check_date (const char *date)
{
    int i, n = strlen(date);

    gretl_errmsg[0] = 0;

    for (i=0; i<n; i++) {
	if (!isdigit((unsigned char) date[i]) && date[i] != '.' 
	    && date[i] != ':') {
	    if (isprint((unsigned char) date[i]))
		sprintf(gretl_errmsg, 
			_("Bad character '%c' in date string"), date[i]);
	    else 
		sprintf(gretl_errmsg, 
			_("Bad character %d in date string"), date[i]);
	    return 1;
	}
    }
    return 0;
}

/**
 * dateton:
 * @date: string representation of date for processing.
 * @pdinfo: pointer to data information struct.
 * 
 * Given a "current" date string, a periodicity, and a starting
 * date string, returns the observation number corresponding to
 * the current date string, counting from zero.
 * 
 * Returns: integer observation number.
 *
 */

int dateton (const char *date, const DATAINFO *pdinfo)
{
    int dotpos1 = 0, dotpos2 = 0, maj = 0, min = 0, n, i;
    char majstr[5], minstr[3];
    char startmajstr[5], startminstr[3];
    int startmaj, startmin;

    if (dated_daily_data(pdinfo)) {
	return daily_obs_number(date, pdinfo);
    }

    if (check_date(date)) {
	return -1;
    }

    n = strlen(date);
    for (i=1; i<n; i++) {
        if (date[i] == '.' || date[i] == ':') {
	    dotpos1 = i;
	    break;
	}
    }
    if (dotpos1) {
        safecpy(majstr, date, dotpos1);
        maj = atoi(majstr);
        strcpy(minstr, date + dotpos1 + 1);
        min = atoi(minstr);
    }
    n = strlen(pdinfo->stobs);
    for (i=1; i<n; i++) {
        if (pdinfo->stobs[i] == '.' || pdinfo->stobs[i] == ':') {
	    dotpos2 = i;
	    break;
	}
    }
    if ((dotpos1 && !dotpos2) || (dotpos2 && !dotpos1)) {
	sprintf(gretl_errmsg, _("Date strings inconsistent"));
	return -1;  
    }
    if (!dotpos1 && !dotpos2) {
	n = atoi(date) - atoi(pdinfo->stobs);
	if (n < 0 || (pdinfo->n != -1 && n > pdinfo->n)) {
	    sprintf(gretl_errmsg, _("Observation number out of bounds"));
	    return -1; 
	}
        else return n;
    }
    safecpy(startmajstr, pdinfo->stobs, dotpos2);
    startmaj = atoi(startmajstr);
    strcpy(startminstr, pdinfo->stobs + dotpos2 + 1);
    startmin = atoi(startminstr);
    n = pdinfo->pd * (maj - startmaj);
    n += min - startmin;
   
    return n;
}

/**
 * ntodate:
 * @datestr: string to which date is to be printed.
 * @nt: an observation number (zero-based).
 * @pdinfo: data information struct.
 * 
 * print to @datestr the calendar representation of observation
 * number nt.
 * 
 */

void ntodate (char *datestr, const int nt, const DATAINFO *pdinfo)
/* print to datestr the calendar representation of nt */
{
    double xn;

    if (dated_daily_data(pdinfo)) {
	daily_date_string(datestr, nt, pdinfo);
	return;
    }

    xn = date(nt, pdinfo->pd, pdinfo->sd0);

    if (pdinfo->pd == 1) {
        int n = (int) xn;

        sprintf(datestr, "%d", n);
    }
    else if (pdinfo->pd < 10) 
	sprintf(datestr, "%.1f", xn);
    else sprintf(datestr, "%.2f", xn);
}

/* .......................................................... */

static int blank_check (FILE *fp)
{
    int i, deflt = 1;
    char s[MAXLEN];

    for (i=0; i<3 && deflt && fgets(s, MAXLEN-1, fp) ; i++) {
	if (i == 0 && strncmp(s, "(*", 2)) deflt = 0;
	else if (i == 1 && strncmp(s, _("space for comments"), 18)) deflt = 0;
	else if (i == 2 && strncmp(s, "*)", 2)) deflt = 0;
    }
    fclose(fp);
    return deflt;
}

/**
 * get_info:
 * @hdrfile: name of data header file
 * @prn: gretl printing struct.
 * 
 * print to @prn the informative comments contained in the given
 * data file (if any).
 * 
 * Returns: 0 on successful completion, non-zero on error or if there
 * are no informative comments.
 * 
 */

int get_info (const char *hdrfile, PRN *prn)
{      
    char s[MAXLEN];
    int i = 0;
    FILE *hdr;

    if ((hdr = fopen(hdrfile, "r")) == NULL) {
	pprintf(prn, _("Couldn't open %s\n"), hdrfile); 
	return 1;
    }

    /* see if it's just the default "space for comments" */
    if (blank_check(hdr)) { /* yes */
	pprintf(prn, _("No info in %s\n"), hdrfile);
	return 2;
    } 

    /* no, so restart the read */
    if ((hdr = fopen(hdrfile, "r")) == NULL) {
	pprintf(prn, _("Couldn't open %s\n"), hdrfile); 
	return 1;
    }    

    pprintf(prn, _("Data info in file %s:\n\n"), hdrfile);
    if (fgets(s, MAXLEN-1, hdr) != NULL && strncmp(s, STARTCOMMENT, 2) == 0) {
	do {
	    if (fgets(s, MAXLEN-1, hdr) != NULL && strncmp(s, "*)", 2)) {
#ifndef OS_WIN32
		delchar('\r', s);
#endif
		pprintf(prn, "%s", s);
		i++;
	    }
	} while (s != NULL && strncmp(s, ENDCOMMENT, 2));
    }
    if (i == 0) pprintf(prn, _(" (none)\n"));
    pprintf(prn, "\n");

    if (hdr != NULL) fclose(hdr);
    return 0;
}

/* ................................................ */

static int writehdr (const char *hdrfile, const int *list, 
		     const DATAINFO *pdinfo, const int opt)
{
    FILE *fp;
    int bin = 0, i;
    char startdate[9], enddate[9];

    if (opt == GRETL_DATA_FLOAT) bin = 1;
    else if (opt == GRETL_DATA_DOUBLE) bin = 2;

    ntodate(startdate, pdinfo->t1, pdinfo);
    ntodate(enddate, pdinfo->t2, pdinfo);

    fp = fopen(hdrfile, "w");
    if (fp == NULL) return 1;

    /* write description of data set, if any */
    if (pdinfo->descrip != NULL) {
	size_t len = strlen(pdinfo->descrip);

	if (len > 2) 
	    fprintf(fp, "(*\n%s%s*)\n", pdinfo->descrip,
		    (pdinfo->descrip[len-1] == '\n')? "" : "\n");
    }

    /* then list of variables */
    for (i=1; i<=list[0]; i++) {
	if (list[i] == 0) continue;
	fprintf(fp, "%s ", pdinfo->varname[list[i]]);
	if (i && i <list[0] && (i+1) % 8 == 0) fprintf(fp, "\n");
    }    
    fputs(";\n", fp);

    /* then obs line */
    fprintf(fp, "%d ", pdinfo->pd);
    fprintf(fp, "%s ", startdate);
    fprintf(fp, "%s\n", enddate);
    
    /* and flags as required */
    if (bin == 1) fputs("BYVAR\nSINGLE\n", fp);
    else if (bin == 2) fputs("BYVAR\nBINARY\n", fp);
    else { 
	fputs("BYOBS\n", fp);
	if (pdinfo->markers) fputs("MARKERS\n", fp);
    }
    if (pdinfo->time_series == STACKED_TIME_SERIES) 
	fprintf(fp, "PANEL2\n");
    else if (pdinfo->time_series == STACKED_CROSS_SECTION) 
	fprintf(fp, "PANEL3\n");
    
    if (fp != NULL) fclose(fp);
    return 0;
}

/**
 * get_precision:
 * @x: data vector.
 * @n: length of x.
 *
 * Find the number of decimal places required to represent a given
 * data series uniformly.
 * 
 * Returns: the required number of decimal places.
 *
 */

int get_precision (double *x, int n)
{
    int i, p = 6, pmax = 0;
    char *s, numstr[48];

    for (i=0; i<n; i++) {
	if (na(x[i])) continue;
	sprintf(numstr, "%f", x[i]);
	s = numstr + strlen(numstr) - 1;
	while (*s-- == '0') p--;
	if (p > pmax) pmax = p;
    }
    return pmax;
}

/**
 * write_data:
 * @fname: name of file to write.
 * @list: list of variables to write.
 * @Z: data matrix.
 * @pdinfo: data information struct.
 * @opt: code for format in which to write the data (see #data_options).
 * @ppaths: pointer to paths information (should be NULL when not
 * called from gui).
 * 
 * Write out a data file containing the values of the given set
 * of variables.
 * 
 * Returns: 0 on successful completion, non-zero on error.
 * 
 */

int write_data (const char *fname, const int *list, 
		double **Z, const DATAINFO *pdinfo, 
		int opt, PATHS *ppaths)
{
    int i = 0, t, l0, n = pdinfo->n;
    char datfile[MAXLEN], hdrfile[MAXLEN], lblfile[MAXLEN];
    FILE *fp = NULL;
    int *pmax = NULL, tsamp = pdinfo->t2 - pdinfo->t1 + 1;
    double xx;

    l0 = list[0];
    if (l0 == 0) return 1;

    if (opt == 0 || opt == GRETL_DATA_GZIPPED) 
	return write_xmldata(fname, list, Z, pdinfo, opt, ppaths);

    strcpy(datfile, fname);

    if (opt == GRETL_DATA_R && pdinfo->time_series == TIME_SERIES) 
	opt = GRETL_DATA_R_ALT;

    /* write header and label files if not exporting to other formats */
    if (opt != GRETL_DATA_R && opt != GRETL_DATA_R_ALT && 
	opt != GRETL_DATA_CSV && opt != GRETL_DATA_OCTAVE) {
	if (!has_gz_suffix(datfile)) {
	    switch_ext(hdrfile, datfile, "hdr");
	    switch_ext(lblfile, datfile, "lbl");
	} else {
	    gz_switch_ext(hdrfile, datfile, "hdr");
	    gz_switch_ext(lblfile, datfile, "lbl");
	}
	if (writehdr(hdrfile, list, pdinfo, opt)) {
	    fprintf(stderr, _("Write of header file failed"));
	    return 1;
	}
	if (writelbl(lblfile, list, pdinfo)) {
	    fprintf(stderr, _("Write of labels file failed"));
	    return 1;
	}
    }

    /* open files, other than for gzipped output */
    if (opt == GRETL_DATA_FLOAT || opt == GRETL_DATA_DOUBLE) 
	fp = fopen(datfile, "wb");
    else 
	fp = fopen(datfile, "w");
    if (fp == NULL) return 1;

    if (opt == GRETL_DATA_FLOAT) { /* single-precision binary */
	float x;

	for (i=1; i<=l0; i++) {
	    for (t=0; t<n; t++) {
		x = (float) (pdinfo->vector[list[i]])? 
			     Z[list[i]][t] : Z[list[i]][0];
		fwrite(&x, sizeof(float), 1, fp);
	    }
	}
    }
    else if (opt == GRETL_DATA_DOUBLE) { /* double-precision binary */
	for (i=1; i<=l0; i++) {
	    if (pdinfo->vector[list[i]])
		fwrite(&Z[list[i]][0], sizeof(double), n, fp);
	    else {
		for (t=0; t<n; t++) 
		    fwrite(&Z[list[i]][0], sizeof(double), 1, fp);
	    }
	}
    }

    if (opt == GRETL_DATA_CSV || opt == GRETL_DATA_OCTAVE || 
	GRETL_DATA_R || opt == GRETL_DATA_TRAD) { 
	/* an ASCII variant of some sort */
	pmax = malloc(l0 * sizeof *pmax);
	if (pmax == NULL) return 1;
	for (i=1; i<=l0; i++) {
	    if (pdinfo->vector[list[i]])
		pmax[i-1] = get_precision(&Z[list[i]][pdinfo->t1], tsamp);
	    else
		pmax[i-1] = get_precision(&Z[list[i]][0], 1);
	}	
    }

    if (opt == GRETL_DATA_TRAD) { /* plain ASCII */
	for (t=pdinfo->t1; t<=pdinfo->t2; t++) {
	    if (pdinfo->markers && pdinfo->S != NULL) 
		fprintf(fp, "%s ", pdinfo->S[t]);
	    for (i=1; i<=l0; i++) {
		if (na(Z[list[i]][t]))
		    fprintf(fp, "-999 ");
		else 
		    fprintf(fp, "%.*f ", pmax[i-1], 
			    (pdinfo->vector[list[i]])? 
			    Z[list[i]][t] : Z[list[i]][0]);
	    }
	    fputs("\n", fp);
	}
	fputs("\n", fp);
    }
    else if (opt == GRETL_DATA_CSV || opt == GRETL_DATA_R) { 
	/* export CSV or GNU R (dataframe) */
	double xdate;
	char comma[2];
	
	if (opt == GRETL_DATA_CSV) strcpy(comma, ",");
	else strcpy(comma, " ");

	/* variable names */
	if (opt == GRETL_DATA_CSV) fprintf(fp, "obs,");
	for (i=1; i<l0; i++) 
	    fprintf(fp, "%s%s", pdinfo->varname[list[i]], comma);
	fprintf(fp, "%s\n", pdinfo->varname[list[l0]]);
	
	for (t=pdinfo->t1; t<=pdinfo->t2; t++) {
	    if (pdinfo->S != NULL) 
		fprintf(fp, "%s%s", pdinfo->S[t], comma);
	    else {
		xdate = date(t, pdinfo->pd, pdinfo->sd0);
		if (pdinfo->pd == 1) 
		    fprintf(fp, "\"%d\"%s", (int) xdate, comma);
		else if (pdinfo->pd < 10) 
		    fprintf(fp, "\"%.1f\"%s", xdate, comma);
		else fprintf(fp, "\"%.2f\"%s", xdate, comma);
	    }
	    for (i=1; i<=l0; i++) { 
		xx = (pdinfo->vector[list[i]])? 
		    Z[list[i]][t] : Z[list[i]][0];
		if (na(xx))
		    fprintf(fp, "NA");
		else
		    fprintf(fp, "%.*f", pmax[i-1], xx);
		if (i < l0) fprintf(fp, "%s", comma);
		else fprintf(fp, "\n");
	    }
	}
	fputs("\n", fp);
    }
    else if (opt == GRETL_DATA_R_ALT) { /* export GNU R (structure) */
	for (i=1; i<=l0; i++) {
	    fprintf(fp, "\"%s\" <-\n", pdinfo->varname[list[i]]);
	    fprintf(fp, "structure(c(");
	    for (t=pdinfo->t1; t<=pdinfo->t2; t++) {
		xx = (pdinfo->vector[list[i]])?
		    Z[list[i]][t] : Z[list[i]][0];
		if (na(xx)) fprintf(fp, "NA");
		else fprintf(fp, "%g", xx);
		if (t < pdinfo->t2) fprintf(fp, ", "); 
		if (t > pdinfo->t1 && (t - pdinfo->t1) % 8 == 0 &&
		    t < pdinfo->t2)
		    fprintf(fp, "\n");
	    }
	    fprintf(fp, ")");
	    if (pdinfo->time_series == TIME_SERIES) 
		fprintf(fp, ",\n.Tsp = c(%f, %f, %d), class = \"ts\"",
			obs_float(pdinfo, 0), obs_float(pdinfo, 1), 
			pdinfo->pd);
	    fprintf(fp, ")\n");
	}
    }
    else if (opt == GRETL_DATA_OCTAVE) { /* export GNU Octave */
	/* write out info on dependent variable */
	fprintf(fp, "# name: %s\n# type: matrix\n# rows: %d\n# columns: 1\n", 
		pdinfo->varname[list[1]], n);
	/* write out column of values of dep. var. */
	for (t=pdinfo->t1; t<=pdinfo->t2; t++) 
	    fprintf(fp, "%.*f\n", pmax[0], 
		    (pdinfo->vector[list[i]])? 
		    Z[list[1]][t] : Z[list[1]][0]);
	/* write out info for indep vars matrix */
	fprintf(fp, "# name: X\n# type: matrix\n# rows: %d\n# columns: %d\n", 
		n, list[0] - 1);
	/* write out indep. var. matrix */
	for (t=pdinfo->t1; t<=pdinfo->t2; t++) {
	    for (i=2; i<=list[0]; i++) {
		fprintf(fp, "%.*f ", pmax[i-1], 
			(pdinfo->vector[list[i]])? 
			Z[list[i]][t] : Z[list[i]][0]);
	    }
	    fputs("\n", fp);
	}
	fputs("\n", fp);
    }

    if (pmax) free(pmax);
    if (fp != NULL) fclose(fp);
    return 0;
}

/* ................................................. */

static double obs_float (const DATAINFO *pdinfo, const int end)
{
    double xx, xx2 = 0.;
    int i, x1, x2 = 0;

    if (end) {
	xx = atof(pdinfo->endobs);
	if ((i = haschar('.', pdinfo->endobs)) > 0)
	   x2 = atoi(pdinfo->endobs + i + 1) - 1;
    } else {
	xx = atof(pdinfo->stobs);
	if ((i = haschar('.', pdinfo->stobs)) > 0)
	   x2 = atoi(pdinfo->stobs + i + 1) - 1;
    }
    x1 = (int) xx;
    if (x2 > 0)
	xx2 = (double) x2 / pdinfo->pd;
    
    return (double) x1 + xx2;
}

/* ................................................. */

static int readlbl (const char *lblfile, DATAINFO *pdinfo)
     /* read data "labels" from file */
{
    FILE * fp;
    char line[MAXLEN], *label, varname[9];
    int v;
    
    gretl_errmsg[0] = '\0';

    fp = fopen(lblfile, "r");
    if (fp == NULL) return 0;
    while (1) {
        if (fgets(line, MAXLEN-1, fp) == NULL) {
            fclose(fp);
            return 0;
        }
        if (sscanf(line, "%s", varname) != 1) {
            fclose(fp);
	    sprintf(gretl_errmsg, _("Bad data label in %s"), lblfile); 
            return 0;
        }
        label = line + strlen(varname);
        if (top_n_tail(label) == E_ALLOC) {
            fclose(fp);
            return E_ALLOC;
        }
	v = varindex(pdinfo, varname);
	if (v < pdinfo->v) strcpy(pdinfo->label[v], label);
	else
	    fprintf(stderr, _("extraneous label for var '%s'\n"), varname);
    }
    if (fp != NULL) 
	fclose(fp);
    return 0;
}

/* ................................................ */

static int writelbl (const char *lblfile, const int *list, 
		     const DATAINFO *pdinfo)
{
    FILE *fp;
    int i, lblcount = 0;

    for (i=1; i<=list[0]; i++) {
	if (list[i] == 0) continue;
	if (strlen(pdinfo->label[list[i]]) > 2) {
	    lblcount++;
	    break;
	}
    }
    if (lblcount == 0) return 0;

    fp = fopen(lblfile, "w");
    if (fp == NULL) return 1;

    /* spit out varnames and labels (if filled out) */
    for (i=1; i<=list[0]; i++) {
	if (list[i] == 0) continue;
	if (strlen(pdinfo->label[list[i]]) > 2) 
	    fprintf(fp, "%s %s\n", pdinfo->varname[list[i]],
		    pdinfo->label[list[i]]);
    }    
    if (fp != NULL) fclose(fp);
    return 0;
}

/**
 * is_gzipped:
 * @fname: filename to examine.
 * 
 * Determine if the given file is gzipped.
 * 
 * Returns: 1 in case of a gzipped file, 0 if not gzipped or
 * inaccessible.
 * 
 */

int is_gzipped (const char *fname)
{
    FILE *fp;
    int gz = 0;

    fp = fopen(fname, "r");
    if (fp == NULL) return 0;
    if (fgetc(fp) == 037 && fgetc(fp) == 0213) 
	gz = 1;
    fclose(fp);
    return gz;
}

/**
 * has_gz_suffix:
 * @fname: filename to examine.
 * 
 * Determine if the given filename ends with ".gz".
 * 
 * Returns: 1 in case of a ".gz" suffix, otherwise 0.
 * 
 */

int has_gz_suffix (const char *fname)
{
    size_t n = strlen(fname);
	
    if (n < 4 || strncmp(fname + n - 3, ".gz", 3))
	return 0;
    else
	return 1;
}

/**
 * gz_switch_ext:
 * @targ: target or "output" filename (must be pre-allocated).
 * @src: "source or "input" filename.
 * @ext: suffix to add to filename.
 * 
 * Copy @src filename to @targ, without the existing suffix (if any),
 * and adding the supplied extension or suffix.
 * 
 */

void gz_switch_ext (char *targ, char *src, char *ext)
{
    size_t i = dotpos(src), j = slashpos(src), k;

    strcpy(targ, src);
    targ[i] = '\0';
    k = dotpos(targ);
    if (j > 0 && k < strlen(targ) && k > j) i = k;
    targ[i] = '.';
    targ[i + 1] = '\0';
    strcat(targ, ext);
}

/* ................................................ */

static void try_gdt (char *fname)
{
    char *suff;

    if (fname != NULL) {
	suff = strrchr(fname, '.');
	if (suff != NULL && !strcmp(suff, ".dat")) {
	    strcpy(suff, ".gdt");
	} else 
	    strcat(fname, ".gdt");
    }
}

/**
 * get_data:
 * @pZ: pointer to data set.
 * @pdinfo: data information struct.
 * @datfile: name of file to try.
 * @ppaths: path information struct.
 * @data_status: indicator for whether a data file is currently open
 * in gretl's work space (not-0) or not (0).
 * @prn: where messages should be written.
 * 
 * Read data from file into gretl's work space, allocating space as
 * required.
 * 
 * Returns: 0 on successful completion, non-zero otherwise.
 *
 */

int get_data (double ***pZ, DATAINFO *pdinfo, char *datfile, PATHS *ppaths, 
	      const int data_status, PRN *prn) 
{

    FILE *dat = NULL;
    gzFile fz = NULL;
    int err, gzsuff = 0, add_gdt = 0;
    char hdrfile[MAXLEN], lblfile[MAXLEN];

    gretl_errmsg[0] = '\0';

    /* get filenames organized */
    hdrfile[0] = '\0';
    gzsuff = has_gz_suffix(datfile);

    if (addpath(datfile, ppaths, 0) == NULL) { /* not found yet */
	char tryfile[MAXLEN];
	int found = 0;

	/* try using the .gdt suffix? */
	tryfile[0] = '\0';
	strncat(tryfile, datfile, MAXLEN-1);
	try_gdt(tryfile); 
	found = (addpath(tryfile, ppaths, 0) != NULL);
	if (found) add_gdt = 1;

	/* or maybe the file is gzipped but lacks a .gz extension? */
	if (!found && !gzsuff) { 
	    sprintf(tryfile, "%s.gz", datfile);
	    if (addpath(tryfile, ppaths, 0) != NULL) {
		gzsuff = 1;
		found = 1;
	    }
	}
	if (!found) return E_FOPEN;
	else strcpy(datfile, tryfile);
    }

    /* catch XML files that have strayed in here? */
    if (add_gdt && xmlfile(datfile)) {
	return get_xmldata(pZ, pdinfo, datfile, ppaths, 
			   data_status, prn, 0);
    }
	
    if (!gzsuff) {
	switch_ext(hdrfile, datfile, "hdr");
	switch_ext(lblfile, datfile, "lbl");
    } else {
	gz_switch_ext(hdrfile, datfile, "hdr");
	gz_switch_ext(lblfile, datfile, "lbl");
    }

    /* clear any existing data info */
    if (data_status) clear_datainfo(pdinfo, CLEAR_FULL);

    /* read data header file */
    err = readhdr(hdrfile, pdinfo);
    if (err) return err;
    else 
	pprintf(prn, _("\nReading header file %s\n"), hdrfile);

    /* deal with case where first col. of data file contains
       "marker" strings */
    pdinfo->S = NULL;
    if (pdinfo->markers && dataset_allocate_markers(pdinfo)) 
	return E_ALLOC; 
    
    /* allocate dataset */
    if (prepZ(pZ, pdinfo)) return E_ALLOC;

    /* Invoke data (Z) reading function */
    if (gzsuff) {
	fz = gzopen(datfile, "rb");
	if (fz == NULL) return E_FOPEN;
    } else {
	if (pdinfo->bin)
	    dat = fopen(datfile, "rb");
	else
	    dat = fopen(datfile, "r");
	if (dat == NULL) return E_FOPEN;
    }

    /* print out basic info from the files read */
    pprintf(prn, _("periodicity: %d, maxobs: %d, "
	   "observations range: %s-%s\n"), pdinfo->pd, pdinfo->n,
	   pdinfo->stobs, pdinfo->endobs);

    pprintf(prn, _("\nReading "));
    pprintf(prn, (pdinfo->time_series == TIME_SERIES) ? 
	    _("time-series") : _("cross-sectional"));
    pprintf(prn, _(" datafile"));
    if (strlen(datfile) > 40) pprintf(prn, "\n");
    pprintf(prn, " %s\n\n", datfile);

    if (gzsuff) {
	err = gz_readdata(fz, pdinfo, *pZ); 
	gzclose(fz);
    } else {
	err = readdata(dat, pdinfo, *pZ); 
	fclose(dat);
    }
    if (err) return err;

    /* Set sample range to entire length of dataset by default */
    pdinfo->t1 = 0; 
    pdinfo->t2 = pdinfo->n - 1;

    strcpy(ppaths->datfile, datfile);
    strcpy(ppaths->hdrfile, hdrfile);
    strcpy(ppaths->lblfile, lblfile);

    err = readlbl(lblfile, pdinfo);
    if (err) return err;    

    return 0;
}

/**
 * open_nulldata:
 * @pZ: pointer to data set.
 * @pdinfo: data information struct.
 * @data_status: indicator for whether a data file is currently open
 * in gretl's work space (1) or not (0).
 * @length: desired length of data series.
 * @prn: gretl printing struct.
 * 
 * Create an empty "dummy" data set, suitable for Monte Carlo simulations.
 * 
 * Returns: 0 on successful completion, non-zero otherwise.
 *
 */

int open_nulldata (double ***pZ, DATAINFO *pdinfo, 
		   const int data_status, const int length,
		   PRN *prn) 
{
    /* clear any existing data info */
    if (data_status) clear_datainfo(pdinfo, CLEAR_FULL);

    /* dummy up the data info */
    pdinfo->n = length;
    pdinfo->v = 1;
    dataset_dates_defaults(pdinfo);

    if (dataset_allocate_varnames(pdinfo)) return E_ALLOC;

    /* no observation markers */
    pdinfo->markers = 0;
    pdinfo->S = NULL; 

    /* no descriptive comments */
    pdinfo->descrip = NULL;

    /* allocate dataset */
    if (prepZ(pZ, pdinfo)) return E_ALLOC;

    /* print out basic info */
    pprintf(prn, _("periodicity: %d, maxobs: %d, "
	   "observations range: %s-%s\n"), pdinfo->pd, pdinfo->n,
	   pdinfo->stobs, pdinfo->endobs);

    /* Set sample range to entire length of data-set by default */
    pdinfo->t1 = 0; 
    pdinfo->t2 = pdinfo->n - 1;

    return 0;
}

/* ......................................................... */

static int test_label (DATAINFO *pdinfo, PRN *prn)
     /* attempt to parse csv row labels as dates.  Return -1 if
	this doesn't work out, 0 if the labels seem to be just
	integer observation numbers, else return the inferred data
	frequency */
{
    int n1, n2, try;
    char year[5], subper[3], endobs[9];
    char lbl1[9], lbl2[9];

    strcpy(lbl1, pdinfo->S[0]);
    strcpy(lbl2, pdinfo->S[pdinfo->n - 1]);
    n1 = strlen(lbl1);
    n2 = strlen(lbl2);

    pprintf(prn, _("   first row label \"%s\", last label \"%s\"\n"), 
	   lbl1, lbl2);

    /* are the labels (probably) just 1, 2, 3 etc.? */
    sprintf(endobs, "%d", pdinfo->n);
    if (strcmp(lbl1, "1") == 0 && strcmp(lbl2, endobs) == 0)
	return 0;

    if (n1 > 7) {
	pprintf(prn, _("   label strings too long for dates?\n"));
	pdinfo->pd = 1;
	pdinfo->sd0 = 1.0;
	return -1;
    }
    if (n1 != n2) {
	pprintf(prn, _("   label strings can't be consistent dates\n"));
	return -1;
    }

    /* does it look like it starts with a year? */
    pprintf(prn, _("trying to parse row labels as dates...\n"));
    if (n1 >= 4) {
	if (isdigit((unsigned char) lbl1[0]) 
	    && isdigit((unsigned char) lbl1[1]) &&
	    isdigit((unsigned char) lbl1[2]) && 
	    isdigit((unsigned char) lbl1[3])) {
	    safecpy(year, lbl1, 4);
	    try = atoi(year);
	    if (try > 0 && try < 3000) {
		pprintf(prn, _("   %s: probably a year... "), year);
	    } else {
		pprintf(prn, _("   %s: out of bounds for a year?\n"), year);
	    }
	    if (n1 == 5) {
		pprintf(prn, _("   but I can't make sense of the extra bit\n"));
		return -1;
	    }
	    if (n1 == 4) {
		pprintf(prn, _("and just a year\n"));
		strcpy(pdinfo->stobs, year);
		pdinfo->sd0 = atof(pdinfo->stobs);
		/* need more checking!! FIXME */
		strcpy(pdinfo->endobs, lbl2);
		pdinfo->pd = 1;
		return 1;
	    }
	    if (lbl1[4] == '.' || lbl1[4] == ':' || lbl1[4] == 'Q') {
		strcpy(subper, lbl1+5);
		if (n1 == 6) {
		    pprintf(prn, _("quarter %s?\n"), subper);
		    sprintf(pdinfo->stobs, "%s.%s", year, subper);
		    pdinfo->sd0 = atof(pdinfo->stobs);
		    strncpy(pdinfo->endobs, lbl2, 4);
		    pdinfo->endobs[4] = '.';
		    strcat(pdinfo->endobs, lbl2+5);
		    pdinfo->pd = 4;
		    return 4;
		}
		if (n1 == 7) {
		    pprintf(prn, _("month %s?\n"), subper);
		    sprintf(pdinfo->stobs, "%s.%s", year, subper);
		    pdinfo->sd0 = atof(pdinfo->stobs);
		    strncpy(pdinfo->endobs, lbl2, 4);
		    pdinfo->endobs[4] = '.';
		    strcat(pdinfo->endobs, lbl2+5);
		    pdinfo->pd = 12;
		    return 12;
		}
	    }
	} else pprintf(prn, _("   definitely not a four-digit year\n"));
    }

    return -1;
}

#define MSG(p, s, g) do { \
                        if (g) pprintf(p, s); \
                        else pprintf(p, "   %s\n", s); \
                     } while (0); 

/**
 * merge_data:
 * @pZ: pointer to data set.
 * @pdinfo: data information struct.
 * @addZ: new data set to be merged in.
 * @addinfo: data information associated with @addZ.
 * @prn: print struct to accept messages.
 * @gui: if = 1, messages will be suitable for GUI message box,
 * otherwise they will be line-print oriented.
 * 
 * Attempt to merge the content of a newly opened data file into
 * gretl's current working data set.
 * 
 * Returns: 0 on successful completion, non-zero otherwise.
 *
 */

int merge_data (double ***pZ, DATAINFO *pdinfo,
		double **addZ, DATAINFO *addinfo,
		PRN *prn, int gui)
{
    int err = 0, addrows = 0, addcols = 0;

    /* first check for conformability */

    if (pdinfo->pd != addinfo->pd) {
	MSG(prn, _("Data frequency does not match"), gui);
	err = 1;
    }

    if (!err && pdinfo->n != addinfo->n && pdinfo->v != addinfo->v) {
	MSG(prn, _("New data not conformable for appending"), gui);
	err = 1;
    }
    else if (!err && pdinfo->n == addinfo->n && pdinfo->v != addinfo->v)
	addcols = 1;
    else if (!err && pdinfo->n != addinfo->n && pdinfo->v == addinfo->v)
	addrows = 1;
    else if (!err && pdinfo->n == addinfo->n && pdinfo->v == addinfo->v) {
	int i;

	addrows = 1;
	for (i=1; i<pdinfo->v; i++) {
	    if (strcmp(pdinfo->varname[i], addinfo->varname[i])) {
		addcols = 1;
		addrows = 0;
		break;
	    }
	}
    }

    if (addcols) {
	if (strcmp(pdinfo->stobs, addinfo->stobs)) {
	    MSG(prn, _("Starting observation does not match"), gui);
	    err = 1;
	} 
	else if (strcmp(pdinfo->endobs, addinfo->endobs)) {
	    MSG(prn, _("Ending observation does not match"), gui);
	    err = 1;
	}
	if (err) addcols = 0;
    }

    else if (addrows) {
	if (pdinfo->time_series && 
	    dateton(addinfo->stobs, pdinfo) != pdinfo->n) {
	    MSG(prn, _("Starting point of new data does not fit"), gui);
	    err = 1;
	}
	else if (pdinfo->markers != addinfo->markers) {
	    MSG(prn, _("Inconsistency in observation markers"), gui);
	    err = 1;
	}
	if (err) addrows = 0;
    }

    /* if checks are passed, try merging the data */

   if (addcols) { 
       int orig_vars = pdinfo->v;
       int i, t, nvars = pdinfo->v + addinfo->v - 1;

       if (dataset_add_vars(addinfo->v - 1, pZ, pdinfo)) {
	   MSG(prn, _("Out of memory adding data"), gui);
	   err = 1;
       }

       for (i=orig_vars; i<nvars && !err; i++) {
	   strcpy(pdinfo->varname[i], addinfo->varname[i - orig_vars + 1]);
	   for (t=0; t<pdinfo->n; t++)
	       (*pZ)[i][t] = addZ[i - orig_vars + 1][t];
       }
   }

   else if (addrows) { 
       int i, t, tnew = pdinfo->n + addinfo->n;
       double *xx;

       if (pdinfo->markers) {
	   char **S = realloc(pdinfo->S, tnew * sizeof *S);
	   
	   if (S == NULL) {
	       err = 1;
	   } else {
	       for (t=pdinfo->n; t<tnew && !err; t++) {
		   S[t] = malloc(9);
		   if (S[t] == NULL) err = 1;
		   else strcpy(S[t], addinfo->S[t - pdinfo->n]);
	       }
	       pdinfo->S = S;
	   }
       }

       for (i=0; i<pdinfo->v && !err; i++) {
	   xx = realloc((*pZ)[i], tnew * sizeof *xx);
	   if (xx == NULL) {
	       err = 1;
	       break;
	   } else {
	       for (t=pdinfo->n; t<tnew; t++)
		   xx[t] = addZ[i][t - pdinfo->n];
	       (*pZ)[i] = xx;
	   }
       }

       if (err) { 
	   MSG(prn, _("Out of memory adding data"), gui);
       } else {
	   pdinfo->n = tnew;
	   ntodate(pdinfo->endobs, tnew - 1, pdinfo);
	   pdinfo->t2 = pdinfo->n - 1;
	   MSG(prn, _("Data appended OK"), gui);
       }
   }

   free_Z(addZ, addinfo);
   clear_datainfo(addinfo, CLEAR_FULL);

   return err;
}

/* ......................................................... */

static void trim_csv_line (char *line)
{
    size_t n;

    if (line == NULL) return;
    n = strlen(line);
    if (n == 0) return;

    if (line[n-1] == '\n') line[n-1] = '\0';
    n = strlen(line);
    if (n == 0) return;
    if (line[n-1] == '\r') line[n-1] = '\0';
    n = strlen(line);
    if (n == 0) return;
    if (line[n-1] == ',') line[n-1] = '\0';
}

/**
 * import_csv:
 * @pZ: pointer to data set.
 * @pdinfo: data information struct.
 * @fname: name of CSV file.
 * @prn: gretl printing struct.
 * 
 * Open a Comma-Separated Values data file and read the data into
 * the current work space.
 * 
 * Returns: 0 on successful completion, non-zero otherwise.
 *
 */

int import_csv (double ***pZ, DATAINFO *pdinfo, 
		const char *fname, PRN *prn)
{
    int n, nv, missval = 0, ncols = 0, chkcols = 0;
    char c, cbak;
    int bad_commas = 0, skipvar = 0, markertest = -1;
    int i, j, k, t, blank_1 = 0, obs_1 = 0, len = 0, maxlen = 0, ok = 0;
    char *line, varname[9], numstr[32], field_1[32];
    FILE *fp;
    DATAINFO *csvinfo;
    double **csvZ = NULL;
    const char *msg = _("\nPlease note:\n"
	"- The first row of the CSV file should contain the "
	"names of the variables.\n"
	"- The first column may optionally contain date "
	"strings or other 'markers':\n  in that case its row 1 entry "
	"should be blank, or should say 'obs' or 'date'.\n"
	"- The remainder of the file must be a rectangular "
	"array of data.\n");

    fp = fopen(fname, "r");
    if (fp == NULL) {
	pprintf(prn, _("Couldn't open %s\n"), fname);
	return 1;
    }

    csvinfo = datainfo_new();
    if (csvinfo == NULL) {
	pprintf(prn, _("Out of memory\n"));
	return 1;
    }

    pprintf(prn, _("parsing %s...\n"), fname);

    /* count chars and fields in first line */
    if (fread(&cbak, 1, 1, fp) == 0 || cbak == '\n') {
	pprintf(prn, _("   empty first line!\n"));
	fclose(fp);
	return 1;
    }
    if (cbak == ',') {
	blank_1 = 1;
	pprintf(prn, _("   first field is blank (dates?)\n"));
	ncols++;
    }
    maxlen++;
    while (fread(&c, 1, 1, fp)) {
	if ((c == '\n' || c == '\r') && cbak == ',') {
	    bad_commas = 1;
	    pprintf(prn, _("   file has trailing commas (lame)\n"));
	}
	if (c == '\n') break;
	cbak = c;
	maxlen++;
	if (c == ',') ncols++;
    }
    if (!bad_commas) ncols++;

    pprintf(prn, _("   number of columns = %d\n"), ncols);

    /* now count remaining non-blank rows, checking for fields */
    chkcols = (bad_commas)? -1: 0;
    while (fread(&c, 1, 1, fp)) {
	if (!(isspace((unsigned char) c))) ok = 1;
	if (c == ',') chkcols += 1;
	if (c != '\n') len++;
	else {
	    if (len > maxlen) maxlen = len;
	    len = 0;
	    if (ok) {
		chkcols += 1; 
		csvinfo->n += 1;
		if (chkcols != ncols) {
		    pprintf(prn, _("   ...but row %d has %d fields: aborting\n"),
			    csvinfo->n, chkcols);
		    fclose(fp);
		    pprintf(prn, msg);
		    return 1;
		}
	    }
	    ok = 0; 
	    chkcols = (bad_commas)? -1: 0;
	}
	cbak = c;
    }
    pprintf(prn, _("   longest line: %d characters\n"), maxlen + 1);

    if (cbak != '\n') 
	fprintf(stderr, "last char was not newline: could be a problem\n");

    if (!blank_1) {
	rewind(fp);
	c = 0; i = 0;
	while (c != ',') {
	    fread(&c, 1, 1, fp);
	    field_1[i++] = c;
	}
	field_1[i-1] = '\0';
	delchar('"', field_1);
	pprintf(prn, _("   first field: '%s'\n"), field_1);
	lower(field_1);
	if (strcmp(field_1, "obs") == 0 || strcmp(field_1, "date") == 0) {
	    pprintf(prn, _("   seems to be observation label\n"));
	    obs_1 = 1;
	    skipvar = 1;
	}
    }

    csvinfo->v = (blank_1 || obs_1)? ncols: ncols + 1;
    pprintf(prn, _("   number of variables: %d\n"), csvinfo->v - 1);
    pprintf(prn, _("   number of non-blank lines: %d\n"), 
	    csvinfo->n + 1);

    fclose(fp);
    /* end initial checking */

    /* initialize datainfo and Z */
    if (start_new_Z(&csvZ, csvinfo, 0)) return E_ALLOC;

    if (blank_1 || obs_1) {
	csvinfo->markers = 1;
	if (dataset_allocate_markers(csvinfo)) return E_ALLOC;
    }

    /* second pass */
    fp = fopen(fname, "r");
    if (fp == NULL) return 1;
    line = malloc(maxlen + 1);
    if (line == NULL) {
	fclose(fp);
	clear_datainfo(csvinfo, CLEAR_FULL);
	return E_ALLOC;
    }

    /* parse the variable names, truncating to 8 chars */
    pprintf(prn, _("scanning for variable names...\n"));
    fgets(line, maxlen + 1, fp);
    trim_csv_line(line);
    delchar(' ', line);
    delchar('"', line);
    pprintf(prn, _("   line: %s\n"), line);
    n = strlen(line);
    k = 0;
    for (i=0; i<n; i++) {
	while (line[i] == ',' || line[i] == '"' || line[i] == QUOTE) i++;
	j = 0; 
	while (line[i] != '"' && line[i] != QUOTE && line[i] != ',' && j < 8) 
	    varname[j++] = line[i++];
	varname[j] = '\0';
	k++;
	if (strlen(varname) == 0 || varname[0] == '\n') {
	    pprintf(prn, _("   variable name %d is missing: aborting\n"), k);
	    pprintf(prn, msg);
	    fclose(fp);
	    free(line);
	    clear_datainfo(csvinfo, CLEAR_FULL);
	    return 1;
	}
	if (k == 1 && skipvar) {
	    k--;
	    skipvar = 0;
	} else {
	    pprintf(prn, _("   variable %d: '%s'\n"), k, varname); 
	    strcpy(csvinfo->varname[k], varname);
	} 
	if (k == csvinfo->v - 1) break;
	if ((k) && j == 8 && line[i] != ',') 
	    while (line[i+1] != ',') i++;
    }

    pprintf(prn, _("scanning for row labels and data...\n"));
    for (t=0; t<csvinfo->n; t++) {
	ok = 0;
	fgets(line, maxlen + 1, fp);
	trim_csv_line(line);
	delchar(' ', line);
	delchar('"', line);
	n = strlen(line);
	for (i=0; i<n; i++) {
	    if (!(isspace((unsigned char) line[i]))) { 
		ok = 1; 
		break; 
	    }
	}
	if (!ok) { 
	    t--; 
	    continue; 
	}
	k = 0;
	/* printf("t=%d: ", t); */
	for (i=0; i<n; i++) {   /* parse line */
	    if (i != 0 || line[i] != ',') {
		if (k == 0 && line[i] == ',') i++;
		if (line[i] == '"' || line[i] == QUOTE) i++;
		j = 0; 
		while (line[i] != ',' && line[i] != '\n' 
		       && line[i] != '"' && line[i] != QUOTE
		       && line[i] != '\0') {
		    numstr[j++] = line[i++];
		}
		numstr[j] = '\0';
	    } else {
		numstr[0] = '\0';
	    }
	    if (strlen(numstr) == 0 || numstr[0] == '\n' ||
		strcmp(numstr, "NA") == 0) {
		if (numstr[0] == 'N') 
		    pprintf(prn, _("   warning: missing value for variable "
			    "%d, obs %d\n"), k, t+1);
		else 
		    pprintf(prn, _("   the cell for variable %d, obs %d "
			    "is empty: treating as missing value\n"), 
			    k, t+1);
		missval = 1;
	    } 
	    k++;
	    if (blank_1 || obs_1) nv = k - 1;
	    else nv = k;
	    if ((blank_1 || obs_1) && k == 1) {
		_esl_trunc(numstr, 8);
		strcpy(csvinfo->S[t], numstr);
	    } else {
		if (missval) 
		    csvZ[nv][t] = NADBL;
		else
		    csvZ[nv][t] = atof(numstr);
		missval = 0;
	    }
	    if (k == ncols) break;
	}
    }
    fclose(fp); 
    free(line);

    csvinfo->t1 = 0;
    csvinfo->t2 = csvinfo->n - 1;
    if (blank_1 || obs_1) markertest = test_label(csvinfo, prn);
    if ((blank_1 || obs_1) && (markertest > 0))
	pprintf(prn, _("taking date information from row labels\n\n"));
    else {
	pprintf(prn, _("treating these as undated data\n\n"));
	dataset_dates_defaults(csvinfo);
    }	
    if (csvinfo->pd != 1 || strcmp(csvinfo->stobs, "1")) 
        csvinfo->time_series = TIME_SERIES;

    /* If there were observation labels and they were not interpretable
       as dates, and they weren't simply "1, 2, 3, ...", then they 
       should probably be preserved. */

    if (csvinfo->S != NULL && markertest >= 0) {
	csvinfo->markers = 0;
	for (i=0; i<csvinfo->n; i++) free(csvinfo->S[i]);
	free(csvinfo->S);
	csvinfo->S = NULL;
    }

    if (*pZ == NULL) {
	*pZ = csvZ;
	*pdinfo = *csvinfo;
    } else {
	if (merge_data(pZ, pdinfo, csvZ, csvinfo, prn, 0))
	    return 1;
    }

    return 0;
}

/**
 * add_case_markers:
 * @pdinfo: data information struct.
 * @fname: name of file containing case markers.
 * 
 * Read case markers (strings of 8 characters or less that identify
 * the observations) from a file, and associate tham with the 
 * current data set.
 * 
 * Returns: 0 on successful completion, non-zero otherwise.
 *
 */

int add_case_markers (DATAINFO *pdinfo, const char *fname)
{
    FILE *fp;
    char **S, marker[9];
    int i, t;

    fp = fopen(fname, "r");
    if (fp == NULL) return E_FOPEN;
    
    S = malloc(pdinfo->n * sizeof *S);
    if (S == NULL) return E_ALLOC; 
    for (i=0; i<pdinfo->n; i++) {
	S[i] = malloc(9);
	if (S[i] == NULL) return E_ALLOC; 
    }

    for (t=0; t<pdinfo->n; t++) {
	eatspace(fp);
	if (fscanf(fp, "%8s", marker) != 1) {
	    for (i=0; i<pdinfo->n; i++) free (S[i]);
	    free(S);
	    fclose(fp);
	    return 1;
	}
	marker[8] = '\0';
	strcpy(S[t], marker);
    }
    fclose(fp);

    if (pdinfo->S != NULL) {
	for (i=0; i<pdinfo->n; i++) 
	    free (pdinfo->S[i]);
	free(pdinfo->S);
    }
    pdinfo->S = S;
    pdinfo->markers = 1;
    return 0;
}

/* ................................................. */

static char *unspace (char *s)
{
    int i;
    size_t n = strlen(s);

    for (i=n-1; i>=0; i--) { 
	if (s[i] == ' ') s[i] = '\0';
	else break;
    }
    return s;
}

/* #define BOX_DEBUG 1 */

/**
 * import_box:
 * @pZ: pointer to data set.
 * @pdinfo: data information struct.
 * @fname: name of CSV file.
 * @prn: gretl printing struct.
 * 
 * Open a BOX1 data file (as produced by the US Census Bureau's
 * Data Extraction Service) and read the data into
 * the current work space.
 * 
 * Returns: 0 on successful completion, non-zero otherwise.
 *
 */

int import_box (double ***pZ, DATAINFO *pdinfo, 
		const char *fname, PRN *prn)
{
    int c, cc, i, t, v, realv, gotdata;
    int maxline, dumpvars;
    char tmp[48];
    unsigned *varsize, *varstart;
    char *test, *line;
    double x;
    FILE *fp;
    DATAINFO *boxinfo;
    double **boxZ = NULL;
    extern int errno;

    fp = fopen(fname, "r");
    if (fp == NULL) {
	pprintf(prn, _("Couldn't open %s\n"), fname);
	return 1;
    }

    boxinfo = datainfo_new();
    if (boxinfo == NULL) {
	pprintf(prn, _("Out of memory\n"));
	return 1;
    }

    pprintf(prn, _("parsing %s...\n"), fname);

    /* first pass: find max line length, number of vars and number
       of observations, plus basic sanity check */
    cc = maxline = 0;
    boxinfo->v = 1;
    do {
	c = getc(fp); 
	if (c != EOF && c != 10 && !isprint((unsigned char) c)) {
	    pprintf(prn, _("Binary data (%d) encountered: this is not a valid "
		   "BOX1 file\n"), c);
	    fclose(fp);
	    return 1;
	}
	if (c == '\n') {
	    if (cc > maxline) maxline = cc;
	    cc = 0;
	    if ((c=getc(fp)) != EOF) {
		tmp[0] = c; cc++;
	    } else break;
	    if ((c=getc(fp)) != EOF) {
		tmp[1] = c; cc++;
	    } else break;
	    tmp[2] = '\0';
	    if (!strcmp(tmp, "03")) boxinfo->v += 1;
	    else if (!strcmp(tmp, "99")) boxinfo->n += 1;
	} else
	    cc++;
    } while (c != EOF);
    fclose(fp);

    pprintf(prn, _("   found %d variables\n"), boxinfo->v - 1);
    pprintf(prn, _("   found %d observations\n"), boxinfo->n);
    pprintf(prn, _("   longest line = %d characters\n"), maxline); 
    maxline += 2;

    /* allocate space for data etc */
    pprintf(prn, _("allocating memory for data... "));
    if (start_new_Z(&boxZ, boxinfo, 0)) return E_ALLOC;
    varstart = malloc((boxinfo->v - 1) * sizeof *varstart);
    if (varstart == NULL) return E_ALLOC;
    varsize = malloc((boxinfo->v - 1) * sizeof *varsize);
    if (varsize == NULL) return E_ALLOC;
    line = malloc(maxline);
    if (line == NULL) return E_ALLOC;
    pprintf(prn, _("done\n"));

    fp = fopen(fname, "r");
    if (fp == NULL) return 1;
    pprintf(prn, _("reading variable information...\n"));

    /* second pass: get detailed info on variables */
    v = 0; realv = 1; t = 0;
    dumpvars = 0; gotdata = 0;
    while (fgets(line, maxline, fp)) {
	strncpy(tmp, line, 2);
	tmp[2] = '\0';
	switch (atoi(tmp)) {
	case 0: /* comment */
	    break;
	case 1: /* BOX info (ignored for now) */
	    break;
	case 2: /* raw data records types (ignored for now) */
	    break;
	case 3: /* variable info */
	    strncpy(boxinfo->varname[realv], line+11, 8);
	    boxinfo->varname[realv][8] = '\0';
	    unspace(boxinfo->varname[realv]);
	    lower(boxinfo->varname[realv]);
	    pprintf(prn, _(" variable %d: '%s'\n"), v+1, boxinfo->varname[realv]);
#ifdef notdef  
	    /* This is wrong!  How do you identify character data? */
	    if (line[51] != '2') {
		pprintf(prn, _("   Non-numeric data: will be skipped\n"));
		varstart[v] = 0;
		varsize[v] = 0;
		v++;
		break;
	    }
#endif
	    strncpy(tmp, line+52, 6);
	    tmp[6] = '\0';
	    varstart[v] = atoi(tmp) - 1;
	    pprintf(prn, _("   starting col. %d, "), varstart[v]);
	    strncpy(tmp, line+58, 4);
	    tmp[4] = '\0';
	    varsize[v] = atoi(tmp);
	    pprintf(prn, _("field width %d, "), varsize[v]);
	    strncpy(tmp, line+62, 2);
	    tmp[2] = '\0';
	    pprintf(prn, _("decimal places %d\n"), atoi(tmp));
	    tmp[0] = '\0';
	    strncpy(tmp, line+64, 20);
	    tmp[20] = '\0';
	    unspace(tmp);
	    if (strlen(tmp))
		pprintf(prn, _("   Warning: coded variable (format '%s' "
			"in BOX file)\n"), tmp);
	    strncpy(boxinfo->label[realv], line+87, 99);
	    boxinfo->label[realv][99] = '\0';
	    unspace(boxinfo->label[realv]);
	    pprintf(prn, _("   definition: '%s'\n"), boxinfo->label[realv]);
	    realv++;
	    v++;
	    break;
	case 4: /* category info (ignored for now) */
	    break;
	case 99: /* data line */
	    realv = 1;
 	    for (i=0; i<v; i++) {
		if (varstart[i] == 0 && varsize[i] == 0) {
		    if (!gotdata) dumpvars++;
		    continue;
		}
		strncpy(tmp, line + varstart[i], varsize[i]);
		tmp[varsize[i]] = '\0';
		top_n_tail(tmp);
		x = strtod(tmp, &test);
#ifdef BOX_DEBUG
		fprintf(stderr, _("read %d chars from pos %d: '%s' -> %g\n"),
			varsize[i], varstart[i], tmp, x); 
#endif
		if (!strcmp(tmp, test)) {
		    pprintf(prn, _("'%s' -- no numeric conversion performed!\n"), 
			    tmp);
		    x = -999.0;
		}
		if (test[0] != '\0') {
		    if (isprint(test[0]))
			pprintf(prn, _("Extraneous character '%c' in data\n"), 
				test[0]);
		    else
			pprintf(prn, _("Extraneous character (0x%x) in data\n"), 
				test[0]);
		    x = -999.0;
		}
		if (errno == ERANGE) {
		    pprintf(prn, _("'%s' -- number out of range!\n"), tmp);
		    x = -999.0;
		}
		boxZ[realv][t] = x;
#ifdef BOX_DEBUG
		fprintf(stderr, "setting Z[%d][%d] = %g\n", realv, t, x);
#endif
		realv++;
	    }
	    t++;
	    gotdata = 1;
	    break;
	default:
	    break;
	}
    }

    pprintf(prn, _("done reading data\n"));
    fclose(fp);

    free(varstart);
    free(varsize);
    free(line);

    dataset_dates_defaults(boxinfo);

    if (dumpvars) {
	dataset_drop_vars(dumpvars, &boxZ, boxinfo);
	pprintf(prn, _("Warning: discarded %d non-numeric variable(s)\n"), 
		dumpvars);
    }

    if (*pZ == NULL) {
	*pZ = boxZ;
	*pdinfo = *boxinfo;
    }

    return 0;
}

static int xmlfile (const char *fname)
{
    gzFile fz;
    char test[6];
    int ret = 0;

    fz = gzopen(fname, "rb");
    if (fz != Z_NULL) {
	if (gzread(fz, test, 5)) {
	    test[5] = '\0';
	    if (!strcmp(test, "<?xml")) ret = 1;
	} 
	gzclose(fz);
    } 
    return ret;
} 

#ifdef OS_WIN32
# include <windows.h>
#else
# include <dlfcn.h>
#endif

int open_plugin (const PATHS *ppaths, const char *plugin, void **handle)
{
    char pluginpath[MAXLEN];

#ifdef OS_WIN32
    sprintf(pluginpath, "%s\\%s.dll", ppaths->gretldir, plugin);
    *handle = LoadLibrary(pluginpath);
    if (*handle == NULL) return 1;
#else
    sprintf(pluginpath, "%splugins/%s.so", ppaths->gretldir, plugin);
    *handle = dlopen(pluginpath, RTLD_LAZY);
    if (*handle == NULL) {
	fprintf(stderr, "%s\n", dlerror());
	return 1;
    }
#endif 
    return 0;
}

void *get_plugin_function (const char *funcname, void *handle)
{
    void *funp;

#ifdef OS_WIN32
    funp = GetProcAddress(handle, funcname);
#else
    funp = dlsym(handle, funcname);
    if (funp == NULL) 
	fprintf(stderr, "%s\n", dlerror());
#endif   
    return funp;
}

void close_plugin (void *handle)
{
#ifdef OS_WIN32
    FreeLibrary(handle);
#else
    if (dlclose(handle)) 
	fprintf(stderr, "%s\n", dlerror());
#endif
}

/**
 * detect_filetype:
 * @fname: name of file to examine.
 * @ppaths: path information struct.
 * @prn: gretl printing struct.
 * 
 * Attempt to determine the type of a file to be opened in gretl:
 * data file (native, CSV or BOX), or command script.
 * 
 * Returns: integer code indicating the type of file (see #gretl_filetypes).
 *
 */

int detect_filetype (char *fname, PATHS *ppaths, PRN *prn)
{
    size_t n = strlen(fname);
    int i, c, comma, ftype = GRETL_NATIVE_DATA;
    char teststr[5];
    FILE *fp;

    /* might be a script file? (watch out for DOS-mangled names) */
    if (n > 4 && (!strcmp(fname + n - 4, ".inp") ||
		  !strcmp(fname + n - 4, ".INP") ||
		  !strcmp(fname + n - 4, ".GRE"))) 
	return GRETL_SCRIPT;
    if (n > 6 && !strcmp(fname + n - 6, ".gretl")) 
	return GRETL_SCRIPT; 
    if (n > 9 && !strcmp(fname + n - 9, ".gnumeric")) 
	return GRETL_GNUMERIC;
    if (n > 4 && !strcmp(fname + n - 4, ".xls")) 
	return GRETL_EXCEL;

    addpath(fname, ppaths, 0); 

    if (xmlfile(fname))
	return GRETL_XML_DATA;   

    fp = fopen(fname, "r");
    if (fp == NULL)  
	return GRETL_NATIVE_DATA; /* may be native file in different location */

    /* first look at extension */
    n = strlen(fname);
    if (n >= 5) {
	if (strcmp(fname + n - 4, ".csv") == 0) 
	    ftype = GRETL_CSV_DATA;
	else if (strcmp(fname + n - 4, ".box") == 0) 
	    ftype = GRETL_BOX_DATA;
    }
    /* then take a peek at content */
    comma = 0;
    for (i=0; i<80; i++) {
	c = getc(fp);
	if (c == EOF || c == '\n') break;
	if (c == ',') comma = 1;
	if (!isprint(c) && c != '\r') {
	    ftype = GRETL_NATIVE_DATA; /* native binary data? */
	    break;
	}
	if (i < 4) teststr[i] = c;
    }
    fclose(fp);
    teststr[4] = 0;

    switch (ftype) {
    case GRETL_NATIVE_DATA: 
	return GRETL_NATIVE_DATA;
    case GRETL_CSV_DATA: 
	if (comma) return GRETL_CSV_DATA;
	else {
	    pprintf(prn, _("csv file seems to be malformed\n"));
	    return GRETL_UNRECOGNIZED;
	}
    case GRETL_BOX_DATA: 
	if (strcmp(teststr, "00**") == 0) return GRETL_BOX_DATA;
	else {
	    pprintf(prn, _("box file seems to be malformed\n"));
	    return GRETL_UNRECOGNIZED;
	}
    }
    return GRETL_NATIVE_DATA; /* FIXME? */
}

#define UTF const xmlChar *

/* #define XML_DEBUG */

static char *simple_fname (char *dest, const char *src)
{
    char *p;

    /* take last part of src filename */
    if (strrchr(src, SLASH))
        strcpy(dest, strrchr(src, SLASH) + 1);
    else
        strcpy(dest, src);

    /* trash any extension */
    p = strrchr(dest, '.');
    if (p != NULL && strlen(dest) > 3)
	strcpy(p, "");

    return dest;
}

static char *xml_encode (char *buf)
{
    char *xmlbuf, *p;
    size_t sz = strlen(buf) + 1;

#ifdef XML_DEBUG
    fprintf(stderr, "xml_encode: original buffer size=%d\n", sz);
#endif

    p = buf;
    while (*buf++) {
	if (*buf == '&') sz += 4;
	else if (*buf == '<') sz += 3;
	else if (*buf == '>') sz += 3;
    }
    buf = p;

    xmlbuf = malloc(sz);
    if (xmlbuf == NULL) {
	sprintf(gretl_errmsg, _("out of memory in XML encoding"));
	return NULL;
    }
#ifdef XML_DEBUG
    fprintf(stderr, "xml_encode: malloc'd xmlbuf at size %d\n", sz);
#endif
    p = xmlbuf;
    while (*buf) {
	if (*buf == '&') {
	    strcpy(p, "&amp;");
	    p += 5;
	} else if (*buf == '<') {
	    strcpy(p, "&lt;");
	    p += 4;
	} else if (*buf == '>') {
	    strcpy(p, "&gt;");
	    p += 4;
	} else {
	    *p++ = *buf;
	}
	buf++;
    }
    xmlbuf[sz-1] = '\0';

#ifdef XML_DEBUG
    fprintf(stderr, "done xml_encode: xmlbuf='%s'\n", xmlbuf);
#endif

    return xmlbuf;
}

/**
 * write_xmldata:
 * @fname: name of file to write.
 * @list: list of variables to write.
 * @Z: data matrix.
 * @pdinfo: data information struct.
 * @opt: if non-zero, write gzipped data, else plain.
 * @ppaths: pointer to paths information (or NULL).
 * 
 * Write out in xml a data file containing the values of the given set
 * of variables.
 * 
 * Returns: 0 on successful completion, non-zero on error.
 * 
 */

static int write_xmldata (const char *fname, const int *list, 
			  double **Z, const DATAINFO *pdinfo, 
			  int opt, PATHS *ppaths)
{
    int err, i, t;
    FILE *fp = NULL;
    gzFile *fz = Z_NULL;
    int *pmax = NULL, tsamp = pdinfo->t2 - pdinfo->t1 + 1;
    char startdate[9], enddate[9], datname[MAXLEN], type[32];
    char *xmlbuf = NULL;
    long sz = 0L;
    void *handle;
    int (*show_progress) (long, long, int) = NULL;
    

    err = 0;
    if (opt) {
	fz = gzopen(fname, "wb");
	if (fz == Z_NULL) err = 1;
    } else {
	fp = fopen(fname, "w");
	if (fp == NULL) err = 1;
    }
    if (err) {
	sprintf(gretl_errmsg, _("Couldn't open %s for writing"), fname);
	return 1;
    }

    pmax = malloc(list[0] * sizeof *pmax);
    if (pmax == NULL) {
	sprintf(gretl_errmsg, _("Out of memory"));
	return 1;
    } 

    sz = (tsamp * pdinfo->v * sizeof(double));
    if (sz > 100000) {
	fprintf(stderr, _("Writing %ld Kbytes of data\n"), sz / 1024);
	if (ppaths == NULL) sz = 0L;
    } else sz = 0L;

    if (sz) {
	if (open_plugin(ppaths, "progress_bar", &handle) == 0) {
	    show_progress = 
		get_plugin_function("show_progress", handle);
	    if (show_progress == NULL) {
		close_plugin(&handle);
		sz = 0;
	    }
	} else sz = 0;
    }

    if (sz) (*show_progress)(0, sz, SP_SAVE_INIT); 

    for (i=1; i<=list[0]; i++) {
	if (pdinfo->vector[list[i]])
	    pmax[i-1] = get_precision(&Z[list[i]][pdinfo->t1], tsamp);
	else
	    pmax[i-1] = get_precision(Z[list[i]], 1);
    }

    ntodate(startdate, pdinfo->t1, pdinfo);
    ntodate(enddate, pdinfo->t2, pdinfo);

    simple_fname(datname, fname);

    if (opt) {
	gzprintf(fz, "<?xml version=\"1.0\"?>\n"
		 "<!DOCTYPE gretldata SYSTEM \"gretldata.dtd\">\n\n"
		 "<gretldata name=\"%s\" frequency=\"%d\" "
		 "startobs=\"%s\" endobs=\"%s\" ", 
		 datname, pdinfo->pd, startdate, enddate);

    } else {
	fprintf(fp, "<?xml version=\"1.0\"?>\n"
		"<!DOCTYPE gretldata SYSTEM \"gretldata.dtd\">\n\n"
		"<gretldata name=\"%s\" frequency=\"%d\" "
		"startobs=\"%s\" endobs=\"%s\" ", 
		datname, pdinfo->pd, startdate, enddate);
    }

    switch (pdinfo->time_series) {
    case 0:
	strcpy(type, "cross-section"); break;
    case TIME_SERIES:
	strcpy(type, "time-series"); break;
    case STACKED_TIME_SERIES:
	strcpy(type, "stacked-time-series"); break;
    case STACKED_CROSS_SECTION:
	strcpy(type, "stacked-cross-section"); break;
    default:
	strcpy(type, "cross-section"); break;
    }

    if (opt) gzprintf(fz, "type=\"%s\">\n", type);
    else fprintf(fp, "type=\"%s\">\n", type);

    /* first deal with description, if any */
    if (pdinfo->descrip != NULL) {
	xmlbuf = xml_encode(pdinfo->descrip);
	if (xmlbuf == NULL) return 1;
	else {
	    if (opt) {
		gzputs(fz, "<description>\n");
		gzputs(fz, xmlbuf);
		gzputs(fz, "</description>\n");
	    }
	    else
		fprintf(fp, "<description>\n%s</description>\n", xmlbuf);
	    free(xmlbuf);
#ifdef XML_DEBUG
	    fprintf(stderr, "xmlbuf encoded buffer freed\n");
#endif
	}
    }

    /* then listing of variable names and labels */
    if (opt) gzprintf(fz, "<variables count=\"%d\">\n", list[0]);
    else fprintf(fp, "<variables count=\"%d\">\n", list[0]);
    for (i=1; i<=list[0]; i++) {
	xmlbuf = xml_encode(pdinfo->varname[list[i]]);
	if (xmlbuf == NULL) return 1;
	else {
	    if (opt) gzprintf(fz, "<variable name=\"%s\"", xmlbuf);
	    else fprintf(fp, "<variable name=\"%s\"", xmlbuf);
	    free(xmlbuf);
	}
	if (!pdinfo->vector[list[i]]) {
	    if (opt) 
		gzprintf(fz, "\n role=\"scalar\" value=\"%.*f\"",
			 pmax[i-1], Z[list[i]][0]);
	    else 
		fprintf(fp, "\n role=\"scalar\" value=\"%.*f\"",
			 pmax[i-1], Z[list[i]][0]);
	}
	if (pdinfo->label[list[i]][0]) {
	    xmlbuf = xml_encode(pdinfo->label[list[i]]);
	    if (xmlbuf == NULL) return 1;
	    else {
		if (opt) gzprintf(fz, "\n label=\"%s\"/>\n", xmlbuf);
		else fprintf(fp, "\n label=\"%s\"/>\n", xmlbuf);
		free(xmlbuf);
	    }
	} else {
	    if (opt) gzputs(fz, "/>\n");
	    else fputs("/>\n", fp);
	}
    }
    if (opt) gzputs(fz, "</variables>\n");
    else fputs("</variables>\n", fp);

    /* then listing of observations */
    if (opt)
	gzprintf(fz, "<observations count=\"%d\" labels=\"%s\">\n",
		tsamp, (pdinfo->markers && pdinfo->S != NULL)? "true" : "false");
    else
	fprintf(fp, "<observations count=\"%d\" labels=\"%s\">\n",
		tsamp, (pdinfo->markers && pdinfo->S != NULL)? "true" : "false");

    for (t=pdinfo->t1; t<=pdinfo->t2; t++) {
	if (opt) gzputs(fz, "<obs");
	else fputs("<obs", fp);
	if (pdinfo->markers && pdinfo->S != NULL) {
	    if (opt) gzprintf(fz, " label=\"%s\">", pdinfo->S[t]);
	    else fprintf(fp, " label=\"%s\">", pdinfo->S[t]);
	} else {
	    if (opt) gzputs(fz, ">");
	    else fputs(">", fp);
	}
	for (i=1; i<=list[0]; i++) {
	    if (!pdinfo->vector[list[i]]) continue;
	    if (na(Z[list[i]][t])) {
		if (opt) gzputs(fz, "NA ");
		else fputs("NA ", fp);
	    } else {
		if (opt) gzprintf(fz, "%.*f ", pmax[i-1], Z[list[i]][t]);
		else fprintf(fp, "%.*f ", pmax[i-1], Z[list[i]][t]);
	    }
	}
	if (opt) gzputs(fz, "</obs>\n");
	else fputs("</obs>\n", fp);
	if (sz && t && ((t - pdinfo->t1) % 50 == 0)) 
	    (*show_progress) (50, tsamp, SP_NONE);
    }

    if (opt) gzprintf(fz, "</observations>\n</gretldata>\n");
    else fprintf(fp, "</observations>\n</gretldata>\n");

    if (sz) {
	(*show_progress)(0, pdinfo->t2 - pdinfo->t1 + 1, SP_FINISH);
	close_plugin(&handle);
    }  

    if (pmax) free(pmax);
    if (fp != NULL) fclose(fp);
    if (fz != Z_NULL) gzclose(fz);

    return 0;
}

static int process_varlist (xmlNodePtr node, DATAINFO *pdinfo, double ***pZ)
{
    xmlNodePtr cur;
    int i;
    char *tmp = xmlGetProp(node, (UTF) "count");

    if (tmp) {
	int v, err = 0;

	if (sscanf(tmp, "%d", &v) == 1) {
	    pdinfo->v = v + 1;
	} else {
	    sprintf(gretl_errmsg, _("Failed to parse count of variables"));
	    err = 1;
	}
	if (!err && dataset_allocate_varnames(pdinfo)) {
	    sprintf(gretl_errmsg, _("Out of memory reading data file"));
	    err = 1;
	}
	if (!err) {
	    *pZ = malloc(pdinfo->v * sizeof **pZ);
	    if (*pZ == NULL) {
		sprintf(gretl_errmsg, _("Out of memory reading data file"));
		err = 1;
	    }
	}		
	free(tmp);
	if (err) return 1;
    }
    else {
	sprintf(gretl_errmsg, _("Got no variables"));
	return 1;
    }

    /* now get individual variable info: names and labels */
    cur = node->xmlChildrenNode;
    while (cur && xmlIsBlankNode(cur)) {
	cur = cur->next;
    }
    if (cur == 0) {
	sprintf(gretl_errmsg, _("Got no variables"));
	return 1;
    }

    i = 1;
    while (cur != NULL) {
        if (!xmlStrcmp(cur->name, (UTF) "variable")) {
	    tmp = xmlGetProp(cur, (UTF) "name");
	    if (tmp) {
		strncpy(pdinfo->varname[i], tmp, 8);
		pdinfo->varname[i][8] = '\0';
		free(tmp);
	    } else {
		sprintf(gretl_errmsg, _("Variable %d has no name"), i);
		return 1;
	    }
	    tmp = xmlGetProp(cur, (UTF) "label");
	    if (tmp) {
		strncpy(pdinfo->label[i], tmp, MAXLABEL-1);
		pdinfo->label[i][MAXLABEL-1] = '\0';
		free(tmp);
	    }
	    tmp = xmlGetProp(cur, (UTF) "role");
	    if (tmp) {
		if (!strcmp(tmp, "scalar")) {
		    char *val = xmlGetProp(cur, (UTF) "value");
		    
		    if (val) {
			double xx = atof(val);

			free(val);
			(*pZ)[i] = malloc(sizeof ***pZ);
			(*pZ)[i][0] = xx;
			pdinfo->vector[i] = 0;
		    }
		}
		free(tmp);
	    }
	    i++;
	}	    
	cur = cur->next;
    }
   
    if (i != pdinfo->v) {
	sprintf(gretl_errmsg, _("Number of variables does not match declaration"));
	return 1;
    }
    else return 0;
}

static int process_values (double **Z, DATAINFO *pdinfo, int t, char *s)
{
    int i;
    double x;

    for (i=1; i<pdinfo->v; i++) {
	if (!pdinfo->vector[i]) continue;
	s = strpbrk(s, "01234567890+-NA");
	if (!strncmp(s, "NA", 2)) x = NADBL;
	else if (*s && (sscanf(s, "%lf", &x) != 1)) {
	    sprintf(gretl_errmsg, _("Failed to parse data values at obs %d"), t+1);
	    return 1;
	}
	Z[i][t] = x;
	s = strpbrk(s, " ,\t\n\r");
    }
    return 0;
}

static int process_observations (xmlDocPtr doc, xmlNodePtr node, 
				 double ***pZ, DATAINFO *pdinfo,
				 PATHS *ppaths, long progress)
{
    xmlNodePtr cur;
    char *tmp = xmlGetProp(node, (UTF) "count");
    int i, t;
    void *handle;
    int (*show_progress) (long, long, int) = NULL;

    if (progress) {
	if (open_plugin(ppaths, "progress_bar", &handle) == 0) {
	    show_progress = 
		get_plugin_function("show_progress", handle);
	    if (show_progress == NULL) {
		close_plugin(&handle);
		progress = 0;
	    }
	} else progress = 0;
    }

    if (tmp) {
	int n;

	if (sscanf(tmp, "%d", &n) == 1) 
	    pdinfo->n = n;
	else {
	    sprintf(gretl_errmsg, _("Failed to parse number of observations"));
	    return 1;
	}
	free(tmp);
    } else 
	return 1;

    tmp = xmlGetProp(node, (UTF) "labels");
    if (tmp) {
	if (!strcmp(tmp, "true")) {
	    pdinfo->markers = 1;
	    if (dataset_allocate_markers(pdinfo)) {
		sprintf(gretl_errmsg, "Out of memory");
		return 1;
	    }
	} else if (strcmp(tmp, "false")) {
	    sprintf(gretl_errmsg, _("labels attribute for observations must be "
		    "'true' or 'false'"));
	    return 1;
	}
	free(tmp);
    } else
	return 1;

    if (pdinfo->endobs[0] == '\0') 
	sprintf(pdinfo->endobs, "%d", pdinfo->n);

    pdinfo->t2 = pdinfo->n - 1;

    for (i=0; i<pdinfo->v; i++) {
	if (!pdinfo->vector[i]) continue;
	(*pZ)[i] = malloc(pdinfo->n * sizeof ***pZ);
	if ((*pZ)[i] == NULL) return 1;
    }

    for (t=0; t<pdinfo->n; t++)
	(*pZ)[0][t] = 1.0;

    /* now get individual obs info: labels and values */
    cur = node->xmlChildrenNode;
    while (cur && xmlIsBlankNode(cur)) {
	cur = cur->next;
    }
    if (cur == 0) {
	sprintf(gretl_errmsg, _("Got no observations\n"));
	return 1;
    }

    if (progress) (*show_progress)(0, progress, SP_LOAD_INIT);

    t = 0;
    while (cur != NULL) {
        if (!xmlStrcmp(cur->name, (UTF) "obs")) {
	    if (pdinfo->markers) {
		tmp = xmlGetProp(cur, (UTF) "label");
		if (tmp) {
		    strncpy(pdinfo->S[t], tmp, 8);
		    pdinfo->S[t][8] = '\0';
		    free(tmp);
		} else {
		    sprintf(gretl_errmsg, _("Case marker missing at obs %d"), t+1);
		    return 1;
		}
	    }
	    tmp = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
	    if (tmp) {
		if (process_values(*pZ, pdinfo, t, tmp))
		    return 1;
		free(tmp);
		t++;
	    } else {
		sprintf(gretl_errmsg, _("Values missing at observation %d"), t+1);
		return 1;
	    }
	}	    
	cur = cur->next;
	if (progress && t % 50 == 0) 
	    (*show_progress) (50, pdinfo->n, SP_NONE);
    }

    if (progress) {
	(*show_progress)(0, pdinfo->n, SP_FINISH);
	close_plugin(&handle);
    }

    if (t != pdinfo->n) {
	sprintf(gretl_errmsg, _("Number of observations does not match declaration"));
	return 1;
    }
    else return 0;
}

static long get_filesize (const char *fname)
{
    struct stat buf;

    if (stat(fname, &buf) == 0)
        return buf.st_size;
    else
        return -1;
}

/**
 * get_xmldata:
 * @pZ: pointer to data set.
 * @pdinfo: data information struct.
 * @fname: name of file to try.
 * @ppaths: path information struct.
 * @data_status: indicator for whether a data file is currently open
 * in gretl's work space (not-0) or not (0).
 * @prn: where messages should be written.
 * @gui: should = 1 if the function is launched from the GUI, else 0.
 * 
 * Read data from file into gretl's work space, allocating space as
 * required.
 * 
 * Returns: 0 on successful completion, non-zero otherwise.
 *
 */

int get_xmldata (double ***pZ, DATAINFO *pdinfo, char *fname,
		 PATHS *ppaths, int data_status, PRN *prn, int gui) 
{
    xmlDocPtr doc;
    xmlNodePtr cur;
    char *tmp;
    int gotvars = 0, gotobs = 0, err = 0;
    long fsz, progress = 0L;

    gretl_errmsg[0] = '\0';

    /* COMPAT: Do not generate nodes for formatting spaces */
    LIBXML_TEST_VERSION
	xmlKeepBlanksDefault(0);

    fsz = get_filesize(fname);
    if (fsz > 100000) {
	    fprintf(stderr, _("%s %ld bytes of data...\n"), 
		    (is_gzipped(fname))? _("Uncompressing") : _("Reading"),
		    fsz);
	    if (gui) progress = fsz;
    }

    doc = xmlParseFile(fname);
    if (doc == NULL) {
	sprintf(gretl_errmsg, _("xmlParseFile failed on %s"), fname);
	return 1;
    }

    /* clear any existing data info */
    if (data_status) clear_datainfo(pdinfo, CLEAR_FULL);

    cur = xmlDocGetRootElement(doc);
    if (cur == NULL) {
        sprintf(gretl_errmsg, _("%s: empty document"), fname);
	xmlFreeDoc(doc);
	return 1;
    }

    if (xmlStrcmp(cur->name, (UTF) "gretldata")) {
        sprintf(gretl_errmsg, _("File of the wrong type, root node not gretldata"));
	xmlFreeDoc(doc);
	return 1;
    }

    /* set some datainfo parameters */
    tmp = xmlGetProp(cur, (UTF) "type");
    if (tmp == NULL) {
	sprintf(gretl_errmsg, 
		_("Required attribute 'type' is missing from data file"));
	return 1;
    } else {
	if (!strcmp(tmp, "cross-section")) 
	    pdinfo->time_series = 0;
	else if (!strcmp(tmp, "time-series"))
	    pdinfo->time_series = TIME_SERIES;
	else if (!strcmp(tmp, "stacked-time-series"))
	    pdinfo->time_series = STACKED_TIME_SERIES;
	else if (!strcmp(tmp, "stacked-cross-section"))
	    pdinfo->time_series = STACKED_CROSS_SECTION;
	else {
	    sprintf(gretl_errmsg, _("Unrecognized type attribute for data file"));
	    return 1;
	}
	free(tmp);
    }
    pdinfo->pd = 1;
    tmp = xmlGetProp(cur, (UTF) "frequency");
    if (tmp) {
	int pd = 0;

	if (sscanf(tmp, "%d", &pd) == 1)
	    pdinfo->pd = pd;
	else {
	    strcpy(gretl_errmsg, _("Failed to parse data frequency"));
	    return 1;
	}
	free(tmp);
    }

    strcpy(pdinfo->stobs, "1");
    tmp = xmlGetProp(cur, (UTF) "startobs");
    if (tmp) {
	if (dataset_is_daily(pdinfo)) {
	    long ed = get_epoch_day(tmp);

	    if (ed < 0) err = 1;
	    else pdinfo->sd0 = ed;
	} else {
	    double x;

	    if (sscanf(tmp, "%lf", &x) != 1) err = 1;
	    else pdinfo->sd0 = atof(tmp);
	}
	if (err) {
	    strcpy(gretl_errmsg, _("Failed to parse startobs"));
	    return 1;
	}
	strncpy(pdinfo->stobs, tmp, 8);
	pdinfo->stobs[8] = '\0';
	free(tmp);
    }

    pdinfo->endobs[0] = '\0';
    tmp = xmlGetProp(cur, (UTF) "endobs");
    if (tmp) {
	if (dataset_is_daily(pdinfo)) {
	    long ed = get_epoch_day(tmp);

	    if (ed < 0) err = 1;
	} else {
	    double x;

	    if (sscanf(tmp, "%lf", &x) != 1) err = 1;
	} 
	if (err) {
	    strcpy(gretl_errmsg, _("Failed to parse endobs"));
	    return 1;
	}
	strncpy(pdinfo->endobs, tmp, 8);
	pdinfo->endobs[8] = '\0';
	free(tmp);
    }

    /* Now walk the tree */
    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        if (!xmlStrcmp(cur->name, (UTF) "description")) {
	    pdinfo->descrip = 
		xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
        } else if (!xmlStrcmp(cur->name, (UTF) "variables")) {
	    if (process_varlist(cur, pdinfo, pZ)) 
		return 1;
	    else
		gotvars = 1;
	}
        else if (!xmlStrcmp(cur->name, (UTF) "observations")) {
	    if (!gotvars) {
		sprintf(gretl_errmsg, _("Variables information is missing"));
		return 1;
	    }
	    if (process_observations(doc, cur, pZ, pdinfo, ppaths, progress)) 
		return 1;
	    else
		gotobs = 1;
	}
	cur = cur->next;
    }

    xmlFreeDoc(doc);
    xmlCleanupParser();

    if (!gotvars) {
	sprintf(gretl_errmsg, _("Variables information is missing"));
	return 1;
    }
    if (!gotobs) {
	sprintf(gretl_errmsg, _("No observations were found"));
	return 1;
    }

    strcpy(ppaths->datfile, fname);
    ppaths->hdrfile[0] = '\0';
    ppaths->lblfile[0] = '\0';

    pprintf(prn, _("\nRead datafile %s\n"), fname);
    pprintf(prn, _("periodicity: %d, maxobs: %d, "
	   "observations range: %s-%s\n\n"), pdinfo->pd, pdinfo->n,
	    pdinfo->stobs, pdinfo->endobs);

    return 0;
}

/**
 * get_xml_description:
 * @fname: name of file to try.
 * 
 * Read data description for gretl xml data file.
 * 
 * Returns: buffer containing description, or NULL on failure.
 *
 */

char *get_xml_description (const char *fname)
{
    xmlDocPtr doc;
    xmlNodePtr cur;
    char *buf = NULL;

    gretl_errmsg[0] = '\0';

    LIBXML_TEST_VERSION
	xmlKeepBlanksDefault(0);

    doc = xmlParseFile(fname);
    if (doc == NULL) {
	sprintf(gretl_errmsg, _("xmlParseFile failed on %s"), fname);
	return NULL;
    }

    cur = xmlDocGetRootElement(doc);
    if (cur == NULL) {
        sprintf(gretl_errmsg, _("%s: empty document"), fname);
	xmlFreeDoc(doc);
	return NULL;
    }

    if (xmlStrcmp(cur->name, (UTF) "gretldata")) {
        sprintf(gretl_errmsg, _("File of the wrong type, root node not gretldata"));
	xmlFreeDoc(doc);
	return NULL;
    }

    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        if (!xmlStrcmp(cur->name, (UTF) "description")) {
	    buf = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
	    break;
        }
	cur = cur->next;
    }

    xmlFreeDoc(doc);
    xmlCleanupParser();

    return buf;
}