File: ncd2dispatch.c

package info (click to toggle)
netcdf-parallel 1%3A4.7.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 105,352 kB
  • sloc: ansic: 229,114; sh: 11,180; yacc: 2,561; makefile: 1,390; lex: 1,173; xml: 173; awk: 2
file content (2839 lines) | stat: -rw-r--r-- 83,468 bytes parent folder | download | duplicates (2)
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
/*********************************************************************
 *   Copyright 2018, UCAR/Unidata
 *   See netcdf/COPYRIGHT file for copying and redistribution conditions.
 *********************************************************************/

#include "dapincludes.h"
#include "ncd2dispatch.h"
#include "ncrc.h"
#include "ncoffsets.h"
#ifdef DEBUG2
#include "dapdump.h"
#endif

#ifdef _MSC_VER
#include <crtdbg.h>
#endif

#ifdef HAVE_GETRLIMIT
#  ifdef HAVE_SYS_RESOURCE_H
#    include <sys/time.h>
#  endif
#  ifdef HAVE_SYS_RESOURCE_H
#    include <sys/resource.h>
#  endif
#endif

/* Define the set of protocols known to be constrainable */
static const char* constrainableprotocols[] = {"http", "https",NULL};

static int ncd2initialized = 0;

/* Forward */
static NCerror buildncstructures(NCDAPCOMMON*);
static NCerror builddims(NCDAPCOMMON*);
static char* getdefinename(CDFnode* node);
static NCerror buildvars(NCDAPCOMMON*);
static NCerror buildglobalattrs(NCDAPCOMMON*, CDFnode* root);
static NCerror buildattribute(NCDAPCOMMON*, CDFnode*, NCattribute*);
static void computedimindexanon(CDFnode* dim, CDFnode* var);
static void replacedims(NClist* dims);
static int equivalentdim(CDFnode* basedim, CDFnode* dupdim);
static NCerror addstringdims(NCDAPCOMMON*);
static NCerror defrecorddim(NCDAPCOMMON*);
static NCerror defseqdims(NCDAPCOMMON*);
static NCerror showprojection(NCDAPCOMMON*, CDFnode* var);
static NCerror getseqdimsize(NCDAPCOMMON*, CDFnode* seq, size_t* sizep);
static NCerror makeseqdim(NCDAPCOMMON*, CDFnode* seq, size_t count, CDFnode** sqdimp);
static NCerror countsequence(NCDAPCOMMON*, CDFnode* xseq, size_t* sizep);
static NCerror freeNCDAPCOMMON(NCDAPCOMMON*);
static NCerror fetchpatternmetadata(NCDAPCOMMON*);
static size_t fieldindex(CDFnode* parent, CDFnode* child);
static NCerror computeseqcountconstraints(NCDAPCOMMON*, CDFnode*, NCbytes*);
static void computeseqcountconstraintsr(NCDAPCOMMON*, CDFnode*, CDFnode**);
static void estimatevarsizes(NCDAPCOMMON*);
static NCerror fetchconstrainedmetadata(NCDAPCOMMON*);
static NCerror suppressunusablevars(NCDAPCOMMON*);
static NCerror fixzerodims(NCDAPCOMMON*);
static void applyclientparamcontrols(NCDAPCOMMON*);
static NCerror applyclientparams(NCDAPCOMMON*);

/**************************************************/

static int
NCD2_create(const char *path, int cmode,
           size_t initialsz, int basepe, size_t *chunksizehintp,
           void* mpidata, const struct NC_Dispatch*,int);

static int NCD2_redef(int ncid);
static int NCD2__enddef(int ncid, size_t h_minfree, size_t v_align, size_t v_minfree, size_t r_align);
static int NCD2_sync(int ncid);
static int NCD2_abort(int ncid);

static int NCD2_put_vara(int ncid, int varid,
	    const size_t *start, const size_t *edges0,
            const void *value0,
	    nc_type memtype);

static int NCD2_get_vara(int ncid, int varid,
	    const size_t *start, const size_t *edges,
            void *value,
	    nc_type memtype);

static int NCD2_put_vars(int ncid, int varid,
	    const size_t *start, const size_t *edges, const ptrdiff_t* stride,
            const void *value0, nc_type memtype);

static int NCD2_get_vars(int ncid, int varid,
	    const size_t *start, const size_t *edges, const ptrdiff_t* stride,
            void *value, nc_type memtype);

static const NC_Dispatch NCD2_dispatch_base = {

NC_FORMATX_DAP2,
NC_DISPATCH_VERSION,

NCD2_create,
NCD2_open,

NCD2_redef,
NCD2__enddef,
NCD2_sync,
NCD2_abort,
NCD2_close,
NCD2_set_fill,
NCD2_inq_format,
NCD2_inq_format_extended, /*inq_format_extended*/

NCD2_inq,
NCD2_inq_type,

NCD2_def_dim,
NCD2_inq_dimid,
NCD2_inq_dim,
NCD2_inq_unlimdim,
NCD2_rename_dim,

NCD2_inq_att,
NCD2_inq_attid,
NCD2_inq_attname,
NCD2_rename_att,
NCD2_del_att,
NCD2_get_att,
NCD2_put_att,

NCD2_def_var,
NCD2_inq_varid,
NCD2_rename_var,
NCD2_get_vara,
NCD2_put_vara,
NCD2_get_vars,
NCD2_put_vars,
NCDEFAULT_get_varm,
NCDEFAULT_put_varm,

NCD2_inq_var_all,

NCD2_var_par_access,
NCD2_def_var_fill,

NCD2_show_metadata,
NCD2_inq_unlimdims,
NCD2_inq_ncid,
NCD2_inq_grps,
NCD2_inq_grpname,
NCD2_inq_grpname_full,
NCD2_inq_grp_parent,
NCD2_inq_grp_full_ncid,
NCD2_inq_varids,
NCD2_inq_dimids,
NCD2_inq_typeids,
NCD2_inq_type_equal,
NCD2_def_grp,
NCD2_rename_grp,
NCD2_inq_user_type,
NCD2_inq_typeid,

NCD2_def_compound,
NCD2_insert_compound,
NCD2_insert_array_compound,
NCD2_inq_compound_field,
NCD2_inq_compound_fieldindex,
NCD2_def_vlen,
NCD2_put_vlen_element,
NCD2_get_vlen_element,
NCD2_def_enum,
NCD2_insert_enum,
NCD2_inq_enum_member,
NCD2_inq_enum_ident,
NCD2_def_opaque,
NCD2_def_var_deflate,
NCD2_def_var_fletcher32,
NCD2_def_var_chunking,
NCD2_def_var_endian,
NCD2_def_var_filter,
NCD2_set_var_chunk_cache,
NCD2_get_var_chunk_cache,

NC_NOTNC4_filter_actions,

};

const NC_Dispatch* NCD2_dispatch_table = NULL; /* moved here from ddispatch.c */

int
NCD2_initialize(void)
{
    NCD2_dispatch_table = &NCD2_dispatch_base;
    ncd2initialized = 1;
#ifdef DEBUG
    /* force logging to go to stderr */
    nclogclose();
    if(nclogopen(NULL))
        ncsetlogging(1); /* turn it on */
#endif
    return NC_NOERR;
}

int
NCD2_finalize(void)
{
    return NC_NOERR;
}

static int
NCD2_redef(int ncid)
{
    return (NC_EPERM);
}

static int
NCD2__enddef(int ncid, size_t h_minfree, size_t v_align, size_t v_minfree, size_t r_align)
{
    return (NC_EPERM);
}

static int
NCD2_sync(int ncid)
{
    return (NC_EINVAL);
}

static int
NCD2_abort(int ncid)
{
    return NCD2_close(ncid,NULL);
}

static int
NCD2_create(const char *path, int cmode,
           size_t initialsz, int basepe, size_t *chunksizehintp,
           void* mpidata, const NC_Dispatch* dispatch, int ncid)
{
   return NC_EPERM;
}

static int
NCD2_put_vara(int ncid, int varid,
	    const size_t *start, const size_t *edges,
            const void *value,
	    nc_type memtype)
{
    return NC_EPERM;
}

static int
NCD2_get_vara(int ncid, int varid,
	    const size_t *start, const size_t *edges,
            void *value,
	    nc_type memtype)
{
    int stat = nc3d_getvarx(ncid, varid, start, edges, NC_stride_one, value,memtype);
    return stat;
}

static int
NCD2_put_vars(int ncid, int varid,
	    const size_t *start, const size_t *edges, const ptrdiff_t* stride,
            const void *value0, nc_type memtype)
{
    return NC_EPERM;
}

static int
NCD2_get_vars(int ncid, int varid,
	    const size_t *start, const size_t *edges, const ptrdiff_t* stride,
            void *value, nc_type memtype)
{
    int stat = nc3d_getvarx(ncid, varid, start, edges, stride, value, memtype);
    return stat;
}

/* See ncd2dispatch.c for other version */
int
NCD2_open(const char* path, int mode, int basepe, size_t *chunksizehintp,
          void* mpidata, const NC_Dispatch* dispatch, int ncid)
{
    NCerror ncstat = NC_NOERR;
    OCerror ocstat = OC_NOERR;
    NCDAPCOMMON* dapcomm = NULL;
    NC* drno;
    const char* value;
    int nc3id = -1;

    /* Find pointer to NC struct for this file. */
    ncstat = NC_check_id(ncid,&drno);
    if(ncstat != NC_NOERR) {goto done;}

    if(path == NULL)
	{ncstat = NC_EDAPURL; goto done;}
    if(dispatch == NULL)
	PANIC("NCD3_open: no dispatch table");

    /* Setup our NC and NCDAPCOMMON state*/

    dapcomm = (NCDAPCOMMON*)calloc(1,sizeof(NCDAPCOMMON));
    if(dapcomm == NULL)
	{ncstat = NC_ENOMEM; goto done;}

    NCD2_DATA_SET(drno,dapcomm);
    drno->int_ncid = nc__pseudofd(); /* create a unique id */
    dapcomm->controller = (NC*)drno;

    dapcomm->cdf.separator = ".";
    dapcomm->cdf.smallsizelimit = DFALTSMALLLIMIT;
    dapcomm->cdf.cache = createnccache();

#ifdef HAVE_GETRLIMIT
    { struct rlimit rl;
      if(getrlimit(RLIMIT_NOFILE, &rl) >= 0) {
	dapcomm->cdf.cache->cachecount = (size_t)(rl.rlim_cur / 2);
      }
    }
#endif

#ifdef OCCOMPILEBYDEFAULT
    { int rullen = 0;
    /* set the compile flag by default */
    rullen = strlen(path)+strlen("[compile]");;
    rullen++; /* strlcat nul */
    dapcomm->oc.rawurltext = (char*)emalloc(rullen+1);
    strncpy(dapcomm->oc.rawurltext,"[compile]",rullen);
    strlcat(dapcomm->oc.rawurltext, path, rullen);
    }
#else
    dapcomm->oc.rawurltext = strdup(path);
#endif

    if(ncuriparse(dapcomm->oc.rawurltext,&dapcomm->oc.url))
	{ncstat = NC_EURL; goto done;}

    if(!constrainable(dapcomm->oc.url))
	SETFLAG(dapcomm->controls,NCF_UNCONSTRAINABLE);

#ifdef COLUMBIA_HACK
    {
	const char* p;
	/* Does this url look like it is from columbia? */
	if(dapcomm->oc.url->host != NULL) {
	    for(p=dapcomm->oc.url->host;*p;p++) {
	        if(strncmp(p,COLUMBIA_HACK,strlen(COLUMBIA_HACK))==0)
		    SETFLAG(dapcomm->controls,NCF_COLUMBIA);
	    }
	}
    }
#endif

    /* fail if we are unconstrainable but have constraints */
    if(FLAGSET(dapcomm->controls,NCF_UNCONSTRAINABLE)) {
	if(dapcomm->oc.url->query != NULL) {
	    nclog(NCLOGWARN,"Attempt to constrain an unconstrainable data source: %s",
		   dapcomm->oc.url->query);
	    ncstat = THROW(NC_EDAPCONSTRAINT);
	    goto done;
	}
    }

    /* Use libsrc code (netcdf-3) for storing metadata */
    {
	char tmpname[32];

        /* Create fake file name: exact name must be unique,
           but is otherwise irrelevant because we are using NC_DISKLESS
        */
        snprintf(tmpname,sizeof(tmpname),"tmp_%d",drno->int_ncid);

        /* Now, use the file to create the hidden, in-memory netcdf file.
	   We want this hidden file to always be NC_CLASSIC, so we need to
           force default format temporarily in case user changed it.
	   Since diskless is enabled, create file in-memory.
	*/
	{
	    int new = 0; /* format netcdf-3 */
	    int old = 0;
	    int ncflags = NC_CLOBBER|NC_CLASSIC_MODEL;
	    ncflags |= NC_DISKLESS;
	    nc_set_default_format(new,&old); /* save and change */
            ncstat = nc_create(tmpname,ncflags,&nc3id);
	    nc_set_default_format(old,&new); /* restore */
	    dapcomm->substrate.realfile = ((ncflags & NC_DISKLESS) != 0);
	    dapcomm->substrate.filename = strdup(tmpname);
	    if(tmpname == NULL) ncstat = NC_ENOMEM;
	    dapcomm->substrate.nc3id = nc3id;
	}
        if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto done;}
	/* Avoid fill */
	nc_set_fill(nc3id,NC_NOFILL,NULL);

    }
    dapcomm->oc.dapconstraint = (DCEconstraint*)dcecreate(CES_CONSTRAINT);
    dapcomm->oc.dapconstraint->projections = nclistnew();
    dapcomm->oc.dapconstraint->selections = nclistnew();

     /* Parse constraints to make sure they are syntactically correct */
     ncstat = dapparsedapconstraints(dapcomm,dapcomm->oc.url->query,dapcomm->oc.dapconstraint);
     if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto done;}

    /* Construct a url for oc minus any constraint and params*/
    dapcomm->oc.urltext = ncuribuild(dapcomm->oc.url,NULL,NULL,NCURIBASE);

    /* Pass to OC */
    ocstat = oc_open(dapcomm->oc.urltext,&dapcomm->oc.conn);
    if(ocstat != OC_NOERR) {THROWCHK(ocstat); goto done;}

#ifdef DEBUG1
    (void)oc_trace_curl(dapcomm->oc.conn);
#endif

    nullfree(dapcomm->oc.urltext); /* clean up */
    dapcomm->oc.urltext = NULL;

    /* process control client parameters */
    applyclientparamcontrols(dapcomm);

    /* Turn on logging; only do this after oc_open*/
    if((value = dapparamvalue(dapcomm,"log")) != NULL) {
	ncloginit();
        if(nclogopen(value))
	    ncsetlogging(1);
	ncloginit();
        if(nclogopen(value))
	    ncsetlogging(1);
    }

    /* fetch and build the unconstrained DDS for use as
       pattern */
    ncstat = fetchpatternmetadata(dapcomm);
    if(ncstat != NC_NOERR) goto done;

    /* Operations on the pattern tree */

    /* Accumulate useful nodes sets  */
    ncstat = computecdfnodesets(dapcomm,dapcomm->cdf.fullddsroot->tree);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* Define the dimsettrans list */
    ncstat = definedimsettrans(dapcomm,dapcomm->cdf.fullddsroot->tree);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* Mark the nodes of the pattern that are eligible for prefetch */
    ncstat = markprefetch(dapcomm);

    /* fetch and build the constrained DDS */
    ncstat = fetchconstrainedmetadata(dapcomm);
    if(ncstat != NC_NOERR) goto done;

#ifdef DEBUG2
fprintf(stderr,"constrained dds: %s\n",dumptree(dapcomm->cdf.ddsroot));
#endif

    /* Operations on the constrained tree */

    /* Accumulate useful nodes sets  */
    ncstat = computecdfnodesets(dapcomm,dapcomm->cdf.ddsroot->tree);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* Fix grids */
    ncstat = fixgrids(dapcomm);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* Locate and mark usable sequences */
    ncstat = sequencecheck(dapcomm);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* suppress variables not in usable sequences */
    ncstat = suppressunusablevars(dapcomm);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* apply client parameters */
    ncstat = applyclientparams(dapcomm);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* Add (as needed) string dimensions*/
    ncstat = addstringdims(dapcomm);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    if(nclistlength(dapcomm->cdf.ddsroot->tree->seqnodes) > 0) {
	/* Build the sequence related dimensions */
        ncstat = defseqdims(dapcomm);
        if(ncstat) {THROWCHK(ncstat); goto done;}
    }

    /* Define the dimsetplus and dimsetall lists */
    ncstat = definedimsets(dapcomm,dapcomm->cdf.ddsroot->tree);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* Re-compute the dimension names*/
    ncstat = computecdfdimnames(dapcomm);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* Deal with zero size dimensions */
    ncstat = fixzerodims(dapcomm);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* Attempt to use the DODS_EXTRA info to turn
       one of the dimensions into unlimited.
       Assume computecdfdimnames34 has already been called.
    */
    ncstat = defrecorddim(dapcomm);
    if(ncstat) {THROWCHK(ncstat); goto done;}
    if(dapcomm->cdf.recorddimname != NULL
       && nclistlength(dapcomm->cdf.ddsroot->tree->seqnodes) > 0) {
	/*nclog(NCLOGWARN,"unlimited dimension specified, but sequences exist in DDS");*/
	PANIC("unlimited dimension specified, but sequences exist in DDS");
    }

    /* Re-compute the var names*/
    ncstat = computecdfvarnames(dapcomm,
				 dapcomm->cdf.ddsroot,
				 dapcomm->cdf.ddsroot->tree->varnodes);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* Transfer data from the unconstrained DDS data to the unconstrained DDS */
    ncstat = dimimprint(dapcomm);
    if(ncstat) goto done;

    /* Process the constraints to map to the constrained CDF tree */
    /* (must follow fixgrids3) */
    ncstat = dapmapconstraints(dapcomm->oc.dapconstraint,dapcomm->cdf.ddsroot);
    if(ncstat != NC_NOERR) goto done;

    /* Canonicalize the constraint */
    ncstat = dapfixprojections(dapcomm->oc.dapconstraint->projections);
    if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto done;}

    /* Fill in segment information */
    ncstat = dapqualifyconstraints(dapcomm->oc.dapconstraint);
    if(ncstat != NC_NOERR) goto done;

    /* Accumulate set of variables in the constraint's projections */
    ncstat = dapcomputeprojectedvars(dapcomm,dapcomm->oc.dapconstraint);
    if(ncstat) {THROWCHK(ncstat); goto done;}

    /* using the modified constraint, rebuild the constraint string */
    if(FLAGSET(dapcomm->controls,NCF_UNCONSTRAINABLE)) {
	/* ignore all constraints */
	dapcomm->oc.urltext = ncuribuild(dapcomm->oc.url,NULL,NULL,NCURIBASE);
    } else {
	char* constraintstring = dcebuildconstraintstring(dapcomm->oc.dapconstraint);
        ncurisetquery(dapcomm->oc.url,constraintstring);
	nullfree(constraintstring);
        dapcomm->oc.urltext = ncuribuild(dapcomm->oc.url,NULL,NULL,NCURISVC);
    }

#ifdef DEBUG
fprintf(stderr,"ncdap3: final constraint: %s\n",dapcomm->oc.url->query);
#endif

    /* Estimate the variable sizes */
    estimatevarsizes(dapcomm);

    /* Build the meta data */
    ncstat = buildncstructures(dapcomm);
    if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto done;}

    /* Explicitly do not call enddef because it will complain
       about variables that are too large.
    */
#if 0
    ncstat = nc_endef(nc3id,NC_NOFILL,NULL);
    if(ncstat != NC_NOERR && ncstat != NC_EVARSIZE)
        {THROWCHK(ncstat); goto done;}
#endif

    { /* (for now) break abstractions*/
	    NC* ncsub;
	    NC3_INFO* nc3i;
	    CDFnode* unlimited = dapcomm->cdf.recorddim;
            /* get the dispatch data for the substrate */
            ncstat = NC_check_id(nc3id,&ncsub);
	    if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto done;}
	    nc3i = (NC3_INFO*)ncsub->dispatchdata;
	    /* This must be checked after all dds and data processing
               so we can figure out the value of numrecs.
	    */
            if(unlimited != NULL) { /* Set the effective size of UNLIMITED */
                NC_set_numrecs(nc3i,unlimited->dim.declsize);
	    }
            /* Pretend the substrate is read-only */
	    NC_set_readonly(nc3i);
    }

    /* Do any necessary data prefetch */
    if(FLAGSET(dapcomm->controls,NCF_PREFETCH)
       && FLAGSET(dapcomm->controls,NCF_PREFETCH_EAGER)) {
        ncstat = prefetchdata(dapcomm);
        if(ncstat != NC_NOERR) {
            del_from_NCList((NC*)drno); /* undefine here */
	    {THROWCHK(ncstat); goto done;}
	}
    }

    return ncstat;

done:
    if(drno != NULL) NCD2_close(drno->ext_ncid,NULL);
    if(ocstat != OC_NOERR) ncstat = ocerrtoncerr(ocstat);
    return THROW(ncstat);
}

int
NCD2_close(int ncid, void* ignore)
{
    NC* drno;
    NCDAPCOMMON* dapcomm;
    int ncstatus = NC_NOERR;

    ncstatus = NC_check_id(ncid, (NC**)&drno);
    if(ncstatus != NC_NOERR) return THROW(ncstatus);
    dapcomm = (NCDAPCOMMON*)drno->dispatchdata;

    /* We call abort rather than close to avoid
       trying to write anything or try to pad file length
     */
    ncstatus = nc_abort(getnc3id(drno));

    /* clean NC* */
    freeNCDAPCOMMON(dapcomm);

    return THROW(ncstatus);
}

/**************************************************/

static NCerror
buildncstructures(NCDAPCOMMON* dapcomm)
{
    NCerror ncstat = NC_NOERR;
    CDFnode* dds = dapcomm->cdf.ddsroot;

    ncstat = buildglobalattrs(dapcomm,dds);
    if(ncstat != NC_NOERR) goto done;

    ncstat = builddims(dapcomm);
    if(ncstat != NC_NOERR) goto done;

    ncstat = buildvars(dapcomm);
    if(ncstat != NC_NOERR) goto done;

done:
    return THROW(ncstat);
}

static NCerror
builddims(NCDAPCOMMON* dapcomm)
{
    int i;
    NCerror ncstat = NC_NOERR;
    int dimid;
    NClist* dimset = NULL;
    NC* ncsub;
    char* definename;

    /* collect all dimensions from variables */
    dimset = dapcomm->cdf.ddsroot->tree->dimnodes;

    /* Sort by fullname just for the fun of it */
    for(;;) {
	int last = nclistlength(dimset) - 1;
	int swap = 0;
        for(i=0;i<last;i++) {
	    CDFnode* dim1 = (CDFnode*)nclistget(dimset,i);
	    CDFnode* dim2 = (CDFnode*)nclistget(dimset,i+1);
   	    if(strcmp(dim1->ncfullname,dim2->ncfullname) > 0) {
		nclistset(dimset,i,(void*)dim2);
		nclistset(dimset,i+1,(void*)dim1);
		swap = 1;
		break;
	    }
	}
	if(!swap) break;
    }

    /* Define unlimited only if needed */
    if(dapcomm->cdf.recorddim != NULL) {
	CDFnode* unlimited = dapcomm->cdf.recorddim;
	definename = getdefinename(unlimited);
        ncstat = nc_def_dim(dapcomm->substrate.nc3id,
			definename,
			NC_UNLIMITED,
			&unlimited->ncid);
	nullfree(definename);
        if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto done;}

        /* get the id for the substrate */
        ncstat = NC_check_id(dapcomm->substrate.nc3id,&ncsub);
        if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto done;}
#if 0
	nc3sub = (NC3_INFO*)&ncsub->dispatchdata;
        /* Set the effective size of UNLIMITED;
           note that this cannot easily be done through the normal API.*/
        NC_set_numrecs(nc3sub,unlimited->dim.declsize);
#endif

    }

    for(i=0;i<nclistlength(dimset);i++) {
	CDFnode* dim = (CDFnode*)nclistget(dimset,i);
        if(dim->dim.basedim != NULL) continue; /* handle below */
	if(DIMFLAG(dim,CDFDIMRECORD)) continue; /* defined above */
#ifdef DEBUG1
fprintf(stderr,"define: dim: %s=%ld\n",dim->ncfullname,(long)dim->dim.declsize);
#endif
	definename = getdefinename(dim);
        ncstat = nc_def_dim(dapcomm->substrate.nc3id,definename,dim->dim.declsize,&dimid);
        if(ncstat != NC_NOERR) {
          THROWCHK(ncstat); nullfree(definename); goto done;
	}
	nullfree(definename);
        dim->ncid = dimid;
    }

    /* Make all duplicate dims have same dimid as basedim*/
    /* (see computecdfdimnames)*/
    for(i=0;i<nclistlength(dimset);i++) {
	CDFnode* dim = (CDFnode*)nclistget(dimset,i);
        if(dim->dim.basedim != NULL) {
	    dim->ncid = dim->dim.basedim->ncid;
	}
    }
done:
    nclistfree(dimset);
    return THROW(ncstat);
}

/* Simultaneously build any associated attributes*/
/* and any necessary pseudo-dimensions for string types*/
static NCerror
buildvars(NCDAPCOMMON* dapcomm)
{
    int i,j;
    NCerror ncstat = NC_NOERR;
    int varid;
    NClist* varnodes = dapcomm->cdf.ddsroot->tree->varnodes;
    char* definename;

    ASSERT((varnodes != NULL));
    for(i=0;i<nclistlength(varnodes);i++) {
	CDFnode* var = (CDFnode*)nclistget(varnodes,i);
        int dimids[NC_MAX_VAR_DIMS];
	unsigned int ncrank;
        NClist* vardims = NULL;

	if(var->invisible) continue;
	if(var->array.basevar != NULL) continue;

#ifdef DEBUG1
fprintf(stderr,"buildvars.candidate=|%s|\n",var->ncfullname);
#endif

	vardims = var->array.dimsetall;
	ncrank = nclistlength(vardims);
	if(ncrank > 0) {
            for(j=0;j<ncrank;j++) {
                CDFnode* dim = (CDFnode*)nclistget(vardims,j);
                dimids[j] = dim->ncid;
 	    }
        }
	definename = getdefinename(var);

#ifdef DEBUG1
fprintf(stderr,"define: var: %s/%s",
		definename,var->ocname);
if(ncrank > 0) {
int k;
for(k=0;k<ncrank;k++) {
CDFnode* dim = (CDFnode*)nclistget(vardims,k);
fprintf(stderr,"[%ld]",dim->dim.declsize);
 }
 }
fprintf(stderr,"\n");
#endif
        ncstat = nc_def_var(dapcomm->substrate.nc3id,
		        definename,
                        var->externaltype,
                        ncrank,
                        (ncrank==0?NULL:dimids),
                        &varid);
	nullfree(definename);
        if(ncstat != NC_NOERR) {
	    THROWCHK(ncstat);
	    goto done;
	}
        var->ncid = varid;
	if(var->attributes != NULL) {
	    NCattribute* unsignedatt = NULL;
	    int unsignedval = 0;
	    /* See if variable has _Unsigned attribute */ 
	    for(j=0;j<nclistlength(var->attributes);j++) {
		NCattribute* att = (NCattribute*)nclistget(var->attributes,j);
		if(strcmp(att->name,"_Unsigned") == 0) {
		    char* value = nclistget(att->values,0);
		    unsignedatt = att;
		    if(value != NULL) {
			if(strcasecmp(value,"false")==0
			   || strcmp(value,"0")==0)
			    unsignedval = 0;
			else
			    unsignedval = 1;
		    }
		    break;
		}
	    }
	    for(j=0;j<nclistlength(var->attributes);j++) {
		NCattribute* att = (NCattribute*)nclistget(var->attributes,j);
		char* val = NULL;
		/* Check for _FillValue/Variable mismatch */
		if(strcmp(att->name,"_FillValue")==0) {
		    /* Special case var is byte, fillvalue is int16 and 
			unsignedattr == 0;
			This exception is needed because DAP2 byte type
			is equivalent to netcdf ubyte type. So passing
                        a signed byte thru DAP2 requires some type and
                        signedness hacking that we have to undo.
		    */
		    if(var->etype == NC_UBYTE
			&& att->etype == NC_SHORT
			&& unsignedatt != NULL && unsignedval == 0) {
			/* Forcibly change the attribute type and signedness */
			att->etype = NC_BYTE;
			val = nclistremove(unsignedatt->values,0);
			if(val) free(val);
			nclistpush(unsignedatt->values,strdup("false"));
		    } else if(att->etype != var->etype) {/* other mismatches */
			/* Log a message */
	                nclog(NCLOGERR,"_FillValue/Variable type mismatch: variable=%s",var->ncbasename);
			/* See if mismatch is allowed */
			if(FLAGSET(dapcomm->controls,NCF_FILLMISMATCH)) {
			    /* Forcibly change the attribute type to match */
			    att->etype = var->etype;
			} else {
			    ncstat = NC_EBADTYPE; /* fail */
			    goto done;
			}
		    }
		}
		ncstat = buildattribute(dapcomm,var,att);
        	if(ncstat != NC_NOERR) goto done;
	    }
	}
	/* Tag the variable with its DAP path */
	if(dapparamcheck(dapcomm,"show","projection"))
	    showprojection(dapcomm,var);
    }
done:
    return THROW(ncstat);
}

static NCerror
buildglobalattrs(NCDAPCOMMON* dapcomm, CDFnode* root)
{
    int i;
    NCerror ncstat = NC_NOERR;
    const char* txt;
    char *nltxt, *p;
    NCbytes* buf = NULL;
    NClist* cdfnodes;

    if(root->attributes != NULL) {
        for(i=0;i<nclistlength(root->attributes);i++) {
   	    NCattribute* att = (NCattribute*)nclistget(root->attributes,i);
	    ncstat = buildattribute(dapcomm,NULL,att);
            if(ncstat != NC_NOERR) goto done;
	}
    }

    /* Add global attribute identifying the sequence dimensions */
    if(dapparamcheck(dapcomm,"show","seqdims")) {
        buf = ncbytesnew();
        cdfnodes = dapcomm->cdf.ddsroot->tree->nodes;
        for(i=0;i<nclistlength(cdfnodes);i++) {
	    CDFnode* dim = (CDFnode*)nclistget(cdfnodes,i);
	    if(dim->nctype != NC_Dimension) continue;
	    if(DIMFLAG(dim,CDFDIMSEQ)) {
	        char* cname = cdflegalname(dim->ocname);
	        if(ncbyteslength(buf) > 0) ncbytescat(buf,", ");
	        ncbytescat(buf,cname);
	        nullfree(cname);
	    }
	}
        if(ncbyteslength(buf) > 0) {
            ncstat = nc_put_att_text(dapcomm->substrate.nc3id,NC_GLOBAL,"_sequence_dimensions",
	           ncbyteslength(buf),ncbytescontents(buf));
	}
    }

    /* Define some additional system global attributes
       depending on show= clientparams*/
    /* Ignore failures*/

    if(dapparamcheck(dapcomm,"show","translate")) {
        /* Add a global attribute to show the translation */
        ncstat = nc_put_att_text(dapcomm->substrate.nc3id,NC_GLOBAL,"_translate",
	           strlen("netcdf-3"),"netcdf-3");
    }
    if(dapparamcheck(dapcomm,"show","url")) {
	if(dapcomm->oc.rawurltext != NULL)
            ncstat = nc_put_att_text(dapcomm->substrate.nc3id,NC_GLOBAL,"_url",
				       strlen(dapcomm->oc.rawurltext),dapcomm->oc.rawurltext);
    }
    if(dapparamcheck(dapcomm,"show","dds")) {
	txt = NULL;
	if(dapcomm->cdf.ddsroot != NULL)
  	    txt = oc_tree_text(dapcomm->oc.conn,dapcomm->cdf.ddsroot->ocnode);
	if(txt != NULL) {
	    /* replace newlines with spaces*/
	    nltxt = nulldup(txt);
	    for(p=nltxt;*p;p++) {if(*p == '\n' || *p == '\r' || *p == '\t') {*p = ' ';}};
            ncstat = nc_put_att_text(dapcomm->substrate.nc3id,NC_GLOBAL,"_dds",strlen(nltxt),nltxt);
	    nullfree(nltxt);
	}
    }
    if(dapparamcheck(dapcomm,"show","das")) {
	txt = NULL;
	if(dapcomm->oc.ocdasroot != NULL)
	    txt = oc_tree_text(dapcomm->oc.conn,dapcomm->oc.ocdasroot);
	if(txt != NULL) {
	    nltxt = nulldup(txt);
	    for(p=nltxt;*p;p++) {if(*p == '\n' || *p == '\r' || *p == '\t') {*p = ' ';}};
            ncstat = nc_put_att_text(dapcomm->substrate.nc3id,NC_GLOBAL,"_das",strlen(nltxt),nltxt);
	    nullfree(nltxt);
	}
    }

done:
    ncbytesfree(buf);
    return THROW(ncstat);
}

static NCerror
buildattribute(NCDAPCOMMON* dapcomm, CDFnode* var, NCattribute* att)
{
    int i;
    NCerror ncstat = NC_NOERR;
    unsigned int nvalues = nclistlength(att->values);
    int varid = (var == NULL ? NC_GLOBAL : var->ncid);
    void* mem = NULL;

    /* If the type of the attribute is string, then we need*/
    /* to convert to a single character string by concatenation.
	modified: 10/23/09 to insert newlines.
	modified: 10/28/09 to interpret escapes
    */
    if(att->etype == NC_STRING || att->etype == NC_URL) {
	char* newstring = NULL;
	size_t newlen = 0;
	for(i=0;i<nvalues;i++) {
	    char* s = (char*)nclistget(att->values,i);
	    newlen += (1+strlen(s));
	}
	newlen++; /* for strlcat nul */
        newstring = (char*)malloc(newlen+1);
        MEMCHECK(newstring,NC_ENOMEM);
	newstring[0] = '\0';
	for(i=0;i<nvalues;i++) {
	    char* s = (char*)nclistget(att->values,i);
	    if(i > 0) strlcat(newstring,"\n",newlen);
	    strlcat(newstring,s,newlen);
	}
        dapexpandescapes(newstring);
	if(newstring[0]=='\0')
	    ncstat = nc_put_att_text(dapcomm->substrate.nc3id,varid,att->name,1,newstring);
	else
	    ncstat = nc_put_att_text(dapcomm->substrate.nc3id,varid,att->name,strlen(newstring),newstring);
	free(newstring);
        if(ncstat) goto done;
    } else {
	nc_type atype;
	unsigned int typesize;
	atype = nctypeconvert(dapcomm,att->etype);
	typesize = nctypesizeof(atype);
	if (nvalues > 0) {
	    mem = malloc(typesize * nvalues);
	}
        ncstat = dapcvtattrval(atype,mem,att->values,att);
        if(ncstat == NC_ERANGE)
	    nclog(NCLOGERR,"Attribute value out of range: %s:%s",
		(var==NULL?"":var->ncbasename),att->name);
        if(ncstat) goto done;
        ncstat = nc_put_att(dapcomm->substrate.nc3id,varid,att->name,atype,nvalues,mem);
        if(ncstat) goto done;
    }
done:
    if(mem) free(mem);
    return THROW(ncstat);
}

static char*
getdefinename(CDFnode* node)
{
    char* spath = NULL;
    NClist* path = NULL;

    switch (node->nctype) {
    case NC_Atomic:
	/* The define name is same as the fullname with elided nodes */
	path = nclistnew();
        collectnodepath(node,path,!WITHDATASET);
        spath = makepathstring(path,".",PATHNC|PATHELIDE);
        nclistfree(path);
	break;

    case NC_Dimension:
	/* Return just the node's ncname */
	spath = nulldup(node->ncbasename);
	break;

    default:
	PANIC("unexpected nctype");
    }
    return spath;
}

int
NCDAP2_ping(const char* url)
{
    OCerror ocstat = OC_NOERR;
    ocstat = oc_ping(url);
    return ocerrtoncerr(ocstat);
}

int
NCD2_inq_format_extended(int ncid, int* formatp, int* modep)
{
    NC* nc;
    int ncstatus = NC_check_id(ncid, (NC**)&nc);
    if(ncstatus != NC_NOERR) return THROW(ncstatus);
    if(modep) *modep = nc->mode;
    if(formatp) *formatp = NC_FORMATX_DAP2;
    return NC_NOERR;
}

/**************************************************/
/* Support functions */

/*
   Provide short and/or unified names for dimensions.
   This must mimic lib-ncdap, which is difficult.
*/
NCerror
computecdfdimnames(NCDAPCOMMON* nccomm)
{
    int i,j;
    char tmp[NC_MAX_NAME*2];
    NClist* conflicts = nclistnew();
    NClist* varnodes = nccomm->cdf.ddsroot->tree->varnodes;
    NClist* alldims;
    NClist* basedims;

    /* Collect all dimension nodes from dimsetall lists */

    alldims = getalldims(nccomm,0);

    /* Assign an index to all anonymous dimensions
       vis-a-vis its containing variable
    */
    for(i=0;i<nclistlength(varnodes);i++) {
	CDFnode* var = (CDFnode*)nclistget(varnodes,i);
        for(j=0;j<nclistlength(var->array.dimsetall);j++) {
	    CDFnode* dim = (CDFnode*)nclistget(var->array.dimsetall,j);
	    if(dim->ocname != NULL) continue; /* not anonymous */
 	    computedimindexanon(dim,var);
	}
    }

    /* Unify dimensions by defining one dimension as the "base"
       dimension, and make all "equivalent" dimensions point to the
       base dimension.
	1. Equivalent means: same size and both have identical non-null names.
	2. Dims with same name but different sizes will be handled separately
    */
    for(i=0;i<nclistlength(alldims);i++) {
	CDFnode* dupdim = NULL;
	CDFnode* basedim = (CDFnode*)nclistget(alldims,i);
	if(basedim == NULL) continue;
	if(basedim->dim.basedim != NULL) continue; /* already processed*/
	for(j=i+1;j<nclistlength(alldims);j++) { /* Sigh, n**2 */
	    dupdim = (CDFnode*)nclistget(alldims,j);
	    if(basedim == dupdim) continue;
	    if(dupdim == NULL) continue;
	    if(dupdim->dim.basedim != NULL) continue; /* already processed */
	    if(!equivalentdim(basedim,dupdim))
		continue;
            dupdim->dim.basedim = basedim; /* equate */
#ifdef DEBUG1
fprintf(stderr,"assign: %s/%s -> %s/%s\n",
basedim->dim.array->ocname,basedim->ocname,
dupdim->dim.array->ocname,dupdim->ocname
);
#endif
	}
    }

    /* Next case: same name and different sizes*/
    /* => rename second dim */

    for(i=0;i<nclistlength(alldims);i++) {
	CDFnode* basedim = (CDFnode*)nclistget(alldims,i);
	if(basedim->dim.basedim != NULL) continue;
	/* Collect all conflicting dimensions */
	nclistclear(conflicts);
        for(j=i+1;j<nclistlength(alldims);j++) {
	    CDFnode* dim = (CDFnode*)nclistget(alldims,j);
	    if(dim->dim.basedim != NULL) continue;
	    if(dim->ocname == NULL && basedim->ocname == NULL) continue;
	    if(dim->ocname == NULL || basedim->ocname == NULL) continue;
	    if(strcmp(dim->ocname,basedim->ocname)!=0) continue;
	    if(dim->dim.declsize == basedim->dim.declsize) continue;
#ifdef DEBUG2
fprintf(stderr,"conflict: %s[%lu] %s[%lu]\n",
			basedim->ncfullname,(unsigned long)basedim->dim.declsize,
			dim->ncfullname,(unsigned long)dim->dim.declsize);
#endif
	    nclistpush(conflicts,(void*)dim);
	}
	/* Give  all the conflicting dimensions an index */
	for(j=0;j<nclistlength(conflicts);j++) {
	    CDFnode* dim = (CDFnode*)nclistget(conflicts,j);
	    dim->dim.index1 = j+1;
	}
    }
    nclistfree(conflicts);

    /* Replace all non-base dimensions with their base dimension */
    for(i=0;i<nclistlength(varnodes);i++) {
	CDFnode* node = (CDFnode*)nclistget(varnodes,i);
	replacedims(node->array.dimsetall);
	replacedims(node->array.dimsetplus);
	replacedims(node->array.dimset0);
    }

    /* Collect list of all basedims */
    basedims = nclistnew();
    for(i=0;i<nclistlength(alldims);i++) {
	CDFnode* dim = (CDFnode*)nclistget(alldims,i);
	if(dim->dim.basedim == NULL) {
	    if(!nclistcontains(basedims,(void*)dim)) {
		nclistpush(basedims,(void*)dim);
	    }
	}
    }

    nccomm->cdf.ddsroot->tree->dimnodes = basedims;

    /* cleanup */
    nclistfree(alldims);

    /* Assign ncbasenames and ncfullnames to base dimensions */
    for(i=0;i<nclistlength(basedims);i++) {
	CDFnode* dim = (CDFnode*)nclistget(basedims,i);
	CDFnode* var = dim->dim.array;
	if(dim->dim.basedim != NULL) PANIC1("nonbase basedim: %s\n",dim->ocname);
	/* stringdim names are already assigned */
	if(dim->ocname == NULL) { /* anonymous: use the index to compute the name */
            snprintf(tmp,sizeof(tmp),"%s_%d",
                            var->ncfullname,dim->dim.index1-1);
            nullfree(dim->ncbasename);
            dim->ncbasename = cdflegalname(tmp);
            nullfree(dim->ncfullname);
            dim->ncfullname = nulldup(dim->ncbasename);
    	} else { /* !anonymous; use index1 if defined */
   	    char* legalname = cdflegalname(dim->ocname);
	    nullfree(dim->ncbasename);
	    if(dim->dim.index1 > 0) {/* need to fix conflicting names (see above) */
	        char sindex[64];
		size_t baselen;
		snprintf(sindex,sizeof(sindex),"_%d",dim->dim.index1);
		baselen = strlen(sindex)+strlen(legalname);
		baselen++; /* for strlcat nul */
		dim->ncbasename = (char*)malloc(baselen+1);
		if(dim->ncbasename == NULL) {nullfree(legalname); return NC_ENOMEM;}
		strncpy(dim->ncbasename,legalname,baselen);
		strlcat(dim->ncbasename,sindex,baselen);
		nullfree(legalname);
	    } else {/* standard case */
	        dim->ncbasename = legalname;
	    }
    	    nullfree(dim->ncfullname);
	    dim->ncfullname = nulldup(dim->ncbasename);
	}
     }

    /* Verify unique and defined names for dimensions*/
    for(i=0;i<nclistlength(basedims);i++) {
	CDFnode* dim1 = (CDFnode*)nclistget(basedims,i);
        CDFnode* dim2 = NULL;
	if(dim1->dim.basedim != NULL) PANIC1("nonbase basedim: %s\n",dim1->ncbasename);
	if(dim1->ncbasename == NULL || dim1->ncfullname == NULL)
	    PANIC1("missing dim names: %s",dim1->ocname);
	/* search backward so we can delete duplicates */
	for(j=nclistlength(basedims)-1;j>i;j--) {
      if(!dim1->ncfullname) continue;
      dim2 = (CDFnode*)nclistget(basedims,j);
      if(strcmp(dim1->ncfullname,dim2->ncfullname)==0) {
		/* complain and suppress one of them */
		fprintf(stderr,"duplicate dim names: %s[%lu] %s[%lu]\n",
                dim1->ncfullname,(unsigned long)dim1->dim.declsize,
                dim2->ncfullname,(unsigned long)dim2->dim.declsize);
		nclistremove(basedims,j);
      }
	}
    }

#ifdef DEBUG
for(i=0;i<nclistlength(basedims);i++) {
CDFnode* dim = (CDFnode*)nclistget(basedims,i);
fprintf(stderr,"basedim: %s=%ld\n",dim->ncfullname,(long)dim->dim.declsize);
 }
#endif

    return NC_NOERR;
}

int
constrainable(NCURI* durl)
{
   const char** protocol = constrainableprotocols;
   for(;*protocol;protocol++) {
	if(strcmp(durl->protocol,*protocol)==0)
	    return 1;
   }
   return 0;
}

/* Lookup a parameter key; case insensitive */
static const char*
paramlookup(NCDAPCOMMON* state, const char* key)
{
    const char* value = NULL;
    if(state == NULL || key == NULL || state->oc.url == NULL) return NULL;
    value = ncurilookup(state->oc.url,key);
    return value;
}

/* Note: this routine only applies some common
   client parameters, other routines may apply
   specific ones.
*/

static NCerror
applyclientparams(NCDAPCOMMON* nccomm)
{
    int i,len;
    int dfaltstrlen = DEFAULTSTRINGLENGTH;
    int dfaltseqlim = DEFAULTSEQLIMIT;
    const char* value;
    char tmpname[NC_MAX_NAME+32];
    char* pathstr = NULL;
    OClink conn = nccomm->oc.conn;
    unsigned long limit;

    ASSERT(nccomm->oc.url != NULL);

    nccomm->cdf.cache->cachelimit = DFALTCACHELIMIT;
    value = paramlookup(nccomm,"cachelimit");
    limit = getlimitnumber(value);
    if(limit > 0) nccomm->cdf.cache->cachelimit = limit;

    nccomm->cdf.fetchlimit = DFALTFETCHLIMIT;
    value = paramlookup(nccomm,"fetchlimit");
    limit = getlimitnumber(value);
    if(limit > 0) nccomm->cdf.fetchlimit = limit;

    nccomm->cdf.smallsizelimit = DFALTSMALLLIMIT;
    value = paramlookup(nccomm,"smallsizelimit");
    limit = getlimitnumber(value);
    if(limit > 0) nccomm->cdf.smallsizelimit = limit;

    nccomm->cdf.cache->cachecount = DFALTCACHECOUNT;
#ifdef HAVE_GETRLIMIT
    { struct rlimit rl;
      if(getrlimit(RLIMIT_NOFILE, &rl) >= 0) {
	nccomm->cdf.cache->cachecount = (size_t)(rl.rlim_cur / 2);
      }
    }
#endif
    value = paramlookup(nccomm,"cachecount");
    limit = getlimitnumber(value);
    if(limit > 0) nccomm->cdf.cache->cachecount = limit;
    /* Ignore limit if not caching */
    if(!FLAGSET(nccomm->controls,NCF_CACHE))
        nccomm->cdf.cache->cachecount = 0;

    if(paramlookup(nccomm,"nolimit") != NULL)
	dfaltseqlim = 0;
    value = paramlookup(nccomm,"limit");
    if(value != NULL && strlen(value) != 0) {
        if(sscanf(value,"%d",&len) && len > 0) dfaltseqlim = len;
    }
    nccomm->cdf.defaultsequencelimit = dfaltseqlim;

    /* allow embedded _ */
    value = paramlookup(nccomm,"stringlength");
    if(value == NULL) 
        value = paramlookup(nccomm,"maxstrlen");
    if(value != NULL && strlen(value) != 0) {
        if(sscanf(value,"%d",&len) && len > 0) dfaltstrlen = len;
    } 
    nccomm->cdf.defaultstringlength = dfaltstrlen;

    /* String dimension limits apply to variables */
    for(i=0;i<nclistlength(nccomm->cdf.ddsroot->tree->varnodes);i++) {
	CDFnode* var = (CDFnode*)nclistget(nccomm->cdf.ddsroot->tree->varnodes,i);
	/* Define the client param stringlength/maxstrlen for this variable*/
	/* create the variable path name */
	var->maxstringlength = 0; /* => use global dfalt */
	strncpy(tmpname,"stringlength_",sizeof(tmpname));
	pathstr = makeocpathstring(conn,var->ocnode,".");
	strlcat(tmpname,pathstr,sizeof(tmpname));
	value = paramlookup(nccomm,tmpname);
	if(value == NULL) {
	    strcpy(tmpname,"maxstrlen_");
	    strncat(tmpname,pathstr,NC_MAX_NAME);
	    value = paramlookup(nccomm,tmpname);
        }
	nullfree(pathstr);
        if(value != NULL && strlen(value) != 0) {
            if(sscanf(value,"%d",&len) && len > 0) var->maxstringlength = len;
	}
    }
    /* Sequence limits apply to sequences */
    for(i=0;i<nclistlength(nccomm->cdf.ddsroot->tree->nodes);i++) {
	CDFnode* var = (CDFnode*)nclistget(nccomm->cdf.ddsroot->tree->nodes,i);
	if(var->nctype != NC_Sequence) continue;
	var->sequencelimit = dfaltseqlim;
	strncpy(tmpname,"nolimit_",sizeof(tmpname));
	pathstr = makeocpathstring(conn,var->ocnode,".");
	strlcat(tmpname,pathstr,sizeof(tmpname));
	if(paramlookup(nccomm,tmpname) != NULL)
	    var->sequencelimit = 0;
	strncpy(tmpname,"limit_",sizeof(tmpname));
	strlcat(tmpname,pathstr,sizeof(tmpname));
	value = paramlookup(nccomm,tmpname);
        if(value != NULL && strlen(value) != 0) {
            if(sscanf(value,"%d",&len) && len > 0)
		var->sequencelimit = len;
	}
	nullfree(pathstr);
    }

    /* test for the appropriate fetch flags */
    value = paramlookup(nccomm,"fetch");
    if(value != NULL && strlen(value) > 0) {
	if(value[0] == 'd' || value[0] == 'D') {
            SETFLAG(nccomm->controls,NCF_ONDISK);
	}
    }

    /* test for the force-whole-var flag */
    value = paramlookup(nccomm,"wholevar");
    if(value != NULL) {
        SETFLAG(nccomm->controls,NCF_WHOLEVAR);
    }

    return NC_NOERR;
}

/**
 *  Given an anonymous dimension, compute the
 *  effective 0-based index wrt to the specified var.
 *  The result should mimic the libnc-dap indices.
 */

static void
computedimindexanon(CDFnode* dim, CDFnode* var)
{
    int i;
    NClist* dimset = var->array.dimsetall;
    for(i=0;i<nclistlength(dimset);i++) {
	CDFnode* candidate = (CDFnode*)nclistget(dimset,i);
        if(dim == candidate) {
	   dim->dim.index1=i+1;
	   return;
	}
    }
}

/* Replace dims in a list with their corresponding basedim */
static void
replacedims(NClist* dims)
{
    int i;
    for(i=0;i<nclistlength(dims);i++) {
        CDFnode* dim = (CDFnode*)nclistget(dims,i);
	CDFnode* basedim = dim->dim.basedim;
	if(basedim == NULL) continue;
	nclistset(dims,i,(void*)basedim);
    }
}

/**
 Two dimensions are equivalent if
 1. they have the same size
 2. neither are anonymous
 3. they ave the same names.
 */
static int
equivalentdim(CDFnode* basedim, CDFnode* dupdim)
{
    if(dupdim->dim.declsize != basedim->dim.declsize) return 0;
    if(basedim->ocname == NULL && dupdim->ocname == NULL) return 0;
    if(basedim->ocname == NULL || dupdim->ocname == NULL) return 0;
    if(strcmp(dupdim->ocname,basedim->ocname) != 0) return 0;
    return 1;
}

static void
getalldimsa(NClist* dimset, NClist* alldims)
{
    int i;
    for(i=0;i<nclistlength(dimset);i++) {
	CDFnode* dim = (CDFnode*)nclistget(dimset,i);
	if(!nclistcontains(alldims,(void*)dim)) {
#ifdef DEBUG3
fprintf(stderr,"getalldims: %s[%lu]\n",
			dim->ncfullname,(unsigned long)dim->dim.declsize);
#endif
	    nclistpush(alldims,(void*)dim);
	}
    }
}

/* Accumulate a set of all the known dimensions
   vis-a-vis defined variables
*/
NClist*
getalldims(NCDAPCOMMON* nccomm, int visibleonly)
{
    int i;
    NClist* alldims = nclistnew();
    NClist* varnodes = nccomm->cdf.ddsroot->tree->varnodes;

    /* get bag of all dimensions */
    for(i=0;i<nclistlength(varnodes);i++) {
	CDFnode* node = (CDFnode*)nclistget(varnodes,i);
	if(!visibleonly || !node->invisible) {
	    getalldimsa(node->array.dimsetall,alldims);
	}
    }
    return alldims;
}


static NCerror
addstringdims(NCDAPCOMMON* dapcomm)
{
    /* for all variables of string type, we will need another dimension
       to represent the string; Accumulate the needed sizes and create
       the dimensions with a specific name: either as specified
       in DODS{...} attribute set or defaulting to the variable name.
       All such dimensions are global.
    */
    int i;
    NClist* varnodes = dapcomm->cdf.ddsroot->tree->varnodes;
    CDFnode* globalsdim = NULL;
    char dimname[4096];
    size_t dimsize;

    /* Start by creating the global string dimension */
    snprintf(dimname,sizeof(dimname),"maxStrlen%lu",
	    (unsigned long)dapcomm->cdf.defaultstringlength);
    globalsdim = makecdfnode(dapcomm, dimname, OC_Dimension, NULL,
                                 dapcomm->cdf.ddsroot);
    nclistpush(dapcomm->cdf.ddsroot->tree->nodes,(void*)globalsdim);
    DIMFLAGSET(globalsdim,CDFDIMSTRING);
    globalsdim->dim.declsize = dapcomm->cdf.defaultstringlength;
    globalsdim->dim.declsize0 = globalsdim->dim.declsize;
    globalsdim->dim.array = dapcomm->cdf.ddsroot;
    globalsdim->ncbasename = cdflegalname(dimname);
    globalsdim->ncfullname = nulldup(globalsdim->ncbasename);
    dapcomm->cdf.globalstringdim = globalsdim;

    for(i=0;i<nclistlength(varnodes);i++) {
	CDFnode* var = (CDFnode*)nclistget(varnodes,i);
	CDFnode* sdim = NULL;

	/* Does this node need a string dim? */
	if(var->etype != NC_STRING && var->etype != NC_URL) continue;

	dimsize = 0;
	if(var->dodsspecial.maxstrlen > 0)
	    dimsize = var->dodsspecial.maxstrlen;
	else
	    dimsize = var->maxstringlength;

	/* check is a variable-specific string length was specified */
	if(dimsize == 0)
	    sdim = dapcomm->cdf.globalstringdim; /* use default */
	else {
	    /* create a pseudo dimension for the charification of the string*/
	    if(var->dodsspecial.dimname != NULL) {
	        strncpy(dimname,var->dodsspecial.dimname,sizeof(dimname));
	        dimname[sizeof(dimname)-1] = '\0';
	    } else
	        snprintf(dimname,sizeof(dimname),"maxStrlen%lu",
			 (unsigned long)dimsize);
	    sdim = makecdfnode(dapcomm, dimname, OC_Dimension, NULL,
                                 dapcomm->cdf.ddsroot);
	    if(sdim == NULL) return THROW(NC_ENOMEM);
	    nclistpush(dapcomm->cdf.ddsroot->tree->nodes,(void*)sdim);
	    DIMFLAGSET(sdim,CDFDIMSTRING);
	    sdim->dim.declsize = dimsize;
	    sdim->dim.declsize0 = dimsize;
	    sdim->dim.array = var;
	    sdim->ncbasename = cdflegalname(sdim->ocname);
	    sdim->ncfullname = nulldup(sdim->ncbasename);
	}
	/* tag the variable with its string dimension*/
	var->array.stringdim = sdim;
    }
    return NC_NOERR;
}

static NCerror
defrecorddim(NCDAPCOMMON* dapcomm)
{
    unsigned int i;
    NCerror ncstat = NC_NOERR;
    NClist* basedims;

    if(dapcomm->cdf.recorddimname == NULL) return NC_NOERR; /* ignore */
    /* Locate the base dimension matching the record dim */
    basedims = dapcomm->cdf.ddsroot->tree->dimnodes;
    for(i=0;i<nclistlength(basedims);i++) {
        CDFnode* dim = (CDFnode*)nclistget(basedims,i);
	if(strcmp(dim->ocname,dapcomm->cdf.recorddimname) != 0) continue;
        DIMFLAGSET(dim,CDFDIMRECORD);
	dapcomm->cdf.recorddim = dim;
	break;
    }

    return ncstat;
}

static NCerror
defseqdims(NCDAPCOMMON* dapcomm)
{
    unsigned int i = 0;
    NCerror ncstat = NC_NOERR;
    int seqdims = 1; /* default is to compute seq dims counts */

    /* Does the user want to compute actual sequence sizes? */
    if(dapparamvalue(dapcomm,"noseqdims")) seqdims = 0;

    /*
	Compute and define pseudo dimensions for sequences
	meeting the following qualifications:
	1. all parents (transitively) of the sequence must
           be either a dataset or a scalar structure.
	2. it must be possible to find a usable sequence constraint.
	All other sequences will be ignored.
    */

    for(i=0;i<nclistlength(dapcomm->cdf.ddsroot->tree->seqnodes);i++) {
        CDFnode* seq = (CDFnode*)nclistget(dapcomm->cdf.ddsroot->tree->seqnodes,i);
	size_t seqsize = 0;
	CDFnode* sqdim = NULL;
	CDFnode* container;
	/* Does this sequence match the requirements for use ? */
	seq->usesequence = 1; /* assume */
	for(container=seq->container;container != NULL;container=container->container) {
	    if(container->nctype == NC_Dataset) break;
	    if(container->nctype != NC_Structure
	       || nclistlength(container->array.dimset0) > 0)
		{seq->usesequence = 0; break;}/* no good */
	}
	/* Does the user want us to compute the actual sequence dim size? */
	if(seq->usesequence && seqdims) {
	    ncstat = getseqdimsize(dapcomm,seq,&seqsize);
	    if(ncstat != NC_NOERR) {
                /* Cannot read sequence; mark as unusable */
	        seq->usesequence = 0;
	    }
	} else { /* !seqdims default to size = 1 */
	    seqsize = 1;
	}
	if(seq->usesequence) {
	    /* Note: we are making the dimension in the dds root tree */
            ncstat = makeseqdim(dapcomm,seq,seqsize,&sqdim);
            if(ncstat) goto fail;
            seq->array.seqdim = sqdim;
	} else
            seq->array.seqdim = NULL;
    }

fail:
    return ncstat;
}

static NCerror
showprojection(NCDAPCOMMON* dapcomm, CDFnode* var)
{
    int i,rank;
    NCerror ncstat = NC_NOERR;
    NCbytes* projection = ncbytesnew();
    NClist* path = nclistnew();
    NC* drno = dapcomm->controller;

    /* Collect the set of DDS node name forming the xpath */
    collectnodepath(var,path,WITHOUTDATASET);
    for(i=0;i<nclistlength(path);i++) {
        CDFnode* node = (CDFnode*)nclistget(path,i);
	if(i > 0) ncbytescat(projection,".");
	ncbytescat(projection,node->ocname);
    }
    nclistfree(path);
    /* Now, add the dimension info */
    rank = nclistlength(var->array.dimset0);
    for(i=0;i<rank;i++) {
	CDFnode* dim = (CDFnode*)nclistget(var->array.dimset0,i);
	char tmp[32];
	ncbytescat(projection,"[");
	snprintf(tmp,sizeof(tmp),"%lu",(unsigned long)dim->dim.declsize);
	ncbytescat(projection,tmp);
	ncbytescat(projection,"]");
    }
    /* Define the attribute */
    ncstat = nc_put_att_text(getncid(drno),var->ncid,
                               "_projection",
		               ncbyteslength(projection),
			       ncbytescontents(projection));
    ncbytesfree(projection);
    return ncstat;
}

static NCerror
getseqdimsize(NCDAPCOMMON* dapcomm, CDFnode* seq, size_t* sizep)
{
    NCerror ncstat = NC_NOERR;
    OCerror ocstat = OC_NOERR;
    OClink conn = dapcomm->oc.conn;
    OCdatanode rootcontent = NULL;
    OCddsnode ocroot;
    CDFnode* dxdroot;
    CDFnode* xseq;
    NCbytes* seqcountconstraints = ncbytesnew();
    size_t seqsize = 0;

    /* Read the minimal amount of data in order to get the count */
    /* If the url is unconstrainable, then get the whole thing */
    computeseqcountconstraints(dapcomm,seq,seqcountconstraints);
#ifdef DEBUG
fprintf(stderr,"seqcountconstraints: %s\n",ncbytescontents(seqcountconstraints));
#endif

    /* Fetch the minimal data */
    if(FLAGSET(dapcomm->controls,NCF_UNCONSTRAINABLE))
        ncstat = dap_fetch(dapcomm,conn,NULL,OCDATADDS,&ocroot);
    else
        ncstat = dap_fetch(dapcomm,conn,ncbytescontents(seqcountconstraints),OCDATADDS,&ocroot);
    if(ncstat) goto fail;

    ncstat = buildcdftree(dapcomm,ocroot,OCDATA,&dxdroot);
    if(ncstat) goto fail;
    /* attach DATADDS to DDS */
    ncstat = attach(dxdroot,seq);
    if(ncstat) goto fail;

    /* WARNING: we are now switching to datadds tree */
    xseq = seq->attachment;
    ncstat = countsequence(dapcomm,xseq,&seqsize);
    if(ncstat != NC_NOERR) goto fail;

#ifdef DEBUG
fprintf(stderr,"sequencesize: %s = %lu\n",seq->ocname,(unsigned long)seqsize);
#endif

    /* throw away the fetch'd trees */
    unattach(dapcomm->cdf.ddsroot);
    freecdfroot(dxdroot);
#if 1
/*Note sure what this is doing?*/
    if(ncstat != NC_NOERR) {
        /* Cannot get DATADDDS*/
	char* code;
	char* msg;
	long httperr;
	oc_svcerrordata(dapcomm->oc.conn,&code,&msg,&httperr);
	if(code != NULL) {
	    nclog(NCLOGERR,"oc_fetch_datadds failed: %s %s %l",
			code,msg,httperr);
	}
	ocstat = OC_NOERR;
    }
#endif

    if(sizep) *sizep = seqsize;

fail:
    ncbytesfree(seqcountconstraints);
    oc_data_free(conn,rootcontent);
    if(ocstat != OC_NOERR) ncstat = ocerrtoncerr(ocstat);
    return ncstat;
}

static NCerror
makeseqdim(NCDAPCOMMON* dapcomm, CDFnode* seq, size_t count, CDFnode** sqdimp)
{
    CDFnode* sqdim;
    CDFnode* root = seq->root;
    CDFtree* tree = root->tree;

    /* build the dimension with given size; keep the dimension anonymous */
    sqdim = makecdfnode(dapcomm,seq->ocname,OC_Dimension,NULL,root);
    if(sqdim == NULL) return THROW(NC_ENOMEM);
    nclistpush(tree->nodes,(void*)sqdim);
    /* Assign a name to the sequence node */
    sqdim->ncbasename = cdflegalname(seq->ocname);
    sqdim->ncfullname = nulldup(sqdim->ncbasename);
    DIMFLAGSET(sqdim,CDFDIMSEQ);
    sqdim->dim.declsize = count;
    sqdim->dim.declsize0 = count;
    sqdim->dim.array = seq;
    if(sqdimp) *sqdimp = sqdim;
    return NC_NOERR;
}

static NCerror
countsequence(NCDAPCOMMON* dapcomm, CDFnode* xseq, size_t* sizep)
{
    unsigned int i;
    NClist* path = nclistnew();
    int index;
    OCerror ocstat = OC_NOERR;
    NCerror ncstat = NC_NOERR;
    OClink conn = dapcomm->oc.conn;
    size_t recordcount;
    CDFnode* xroot;
    OCdatanode data = NULL;

    ASSERT((xseq->nctype == NC_Sequence));

    /* collect the path to the sequence node */
    collectnodepath(xseq,path,WITHDATASET);

    /* Get tree root */
    ASSERT(xseq->root == (CDFnode*)nclistget(path,0));
    xroot = xseq->root;
    ocstat = oc_data_getroot(conn,xroot->tree->ocroot,&data);
    if(ocstat) goto done;

    /* Basically we use the path to walk the data instances to reach
       the sequence instance
    */
    for(i=0;i<nclistlength(path);i++) {
        CDFnode* current = (CDFnode*)nclistget(path,i);
	OCdatanode nextdata = NULL;
	CDFnode* next = NULL;

	/* invariant: current = ith node in path; data = corresponding
           datanode
        */

	/* get next node in next and next instance in nextdata */
	if(current->nctype == NC_Structure
	   || current->nctype == NC_Dataset) {
	    if(nclistlength(current->array.dimset0) > 0) {
		/* Cannot handle this case */
		ncstat = THROW(NC_EDDS);
		goto done;
	    }
	    /* get next node in path; structure/dataset => exists */
	    next = (CDFnode*)nclistget(path,i+1);
	    index = fieldindex(current,next);
            /* Move to appropriate field */
	    ocstat = oc_data_ithfield(conn,data,index,&nextdata);
	    if(ocstat) goto done;
	    oc_data_free(conn,data);
	    data = nextdata; /* set up for next loop iteration */
	} else if(current->nctype ==  NC_Sequence) {
	    /* Check for nested Sequences */
	    if(current != xseq) {
		/* Cannot handle this case */
		ncstat = THROW(NC_EDDS);
		goto done;
	    }
	    /* Get the record count */
	    ocstat = oc_data_recordcount(conn,data,&recordcount);
    	    if(sizep) *sizep = recordcount;
	    oc_data_free(conn,data); /* reclaim */
	    break; /* leave the loop */
	} else {
	    PANIC("unexpected mode");
	    return NC_EINVAL;
        }
    }

done:
    nclistfree(path);
    if(ocstat != OC_NOERR) ncstat = ocerrtoncerr(ocstat);
    return THROW(ncstat);
}

static NCerror
freeNCDAPCOMMON(NCDAPCOMMON* dapcomm)
{
    if(dapcomm == NULL) return NC_NOERR;
    freenccache(dapcomm,dapcomm->cdf.cache);
    nclistfree(dapcomm->cdf.projectedvars);
    nullfree(dapcomm->cdf.recorddimname);

    /* free the trees */
    freecdfroot(dapcomm->cdf.ddsroot);
    dapcomm->cdf.ddsroot = NULL;
    freecdfroot(dapcomm->cdf.fullddsroot);
    dapcomm->cdf.fullddsroot = NULL;
    if(dapcomm->oc.ocdasroot != NULL)
        oc_root_free(dapcomm->oc.conn,dapcomm->oc.ocdasroot);
    dapcomm->oc.ocdasroot = NULL;
    oc_close(dapcomm->oc.conn); /* also reclaims remaining OC trees */
    ncurifree(dapcomm->oc.url);
    nullfree(dapcomm->oc.urltext);
    nullfree(dapcomm->oc.rawurltext);

    dcefree((DCEnode*)dapcomm->oc.dapconstraint);
    dapcomm->oc.dapconstraint = NULL;

    /* Note that the ncio layer will figure out that the tmp file needs to be deleted,
       so we do not have to do it.
    */
    nullfree(dapcomm->substrate.filename); /* always reclaim */

    free(dapcomm);

    return NC_NOERR;
}

static size_t
fieldindex(CDFnode* parent, CDFnode* child)
{
    unsigned int i;
    for(i=0;i<nclistlength(parent->subnodes);i++) {
	CDFnode* node = (CDFnode*)nclistget(parent->subnodes,i);
	if(node == child) return i;
    }
    return -1;
}

/*
This is more complex than one might think. We want to find
a path to a variable inside the given node so that we can
ask for a single instance of that variable to minimize the
amount of data we retrieve. However, we want to avoid passing
through any nested sequence. This is possible because of the way
that sequencecheck() works.
TODO: some servers will not accept an unconstrained fetch, so
make sure we always have a constraint.
*/

static NCerror
computeseqcountconstraints(NCDAPCOMMON* dapcomm, CDFnode* seq, NCbytes* seqcountconstraints)
{
    int i,j;
    NClist* path = NULL;
    CDFnode* var = NULL;

    ASSERT(seq->nctype == NC_Sequence);
    computeseqcountconstraintsr(dapcomm,seq,&var);

    ASSERT((var != NULL));

    /* Compute var path */
    path = nclistnew();
    collectnodepath(var,path,WITHOUTDATASET);

    /* construct the projection path using minimal index values */
    for(i=0;i<nclistlength(path);i++) {
	CDFnode* node = (CDFnode*)nclistget(path,i);
	if(i > 0) ncbytescat(seqcountconstraints,".");
	ncbytescat(seqcountconstraints,node->ocname);
	if(node == seq) {
	    /* Use the limit */
	    if(node->sequencelimit > 0) {
		char tmp[64];
		snprintf(tmp,sizeof(tmp),"[0:%lu]",
		         (unsigned long)(node->sequencelimit - 1));
		ncbytescat(seqcountconstraints,tmp);
	    }
	} else if(nclistlength(node->array.dimset0) > 0) {
	    int ndims = nclistlength(node->array.dimset0);
	    for(j=0;j<ndims;j++) {
		CDFnode* dim = (CDFnode*)nclistget(node->array.dimset0,j);
		if(DIMFLAG(dim,CDFDIMSTRING)) {
		    ASSERT((j == (ndims - 1)));
		    break;
		}
		ncbytescat(seqcountconstraints,"[0]");
	    }
	}
    }
    /* Finally, add in any selection from the original URL */
    if(dap_getselection(dapcomm->oc.url) != NULL)
        ncbytescat(seqcountconstraints,dap_getselection(dapcomm->oc.url));
    nclistfree(path);
    return NC_NOERR;
}


/* Given an existing candidate, see if we prefer newchoice */
static CDFnode*
prefer(CDFnode* candidate, CDFnode* newchoice)
{
    nc_type newtyp;
    nc_type cantyp;
    int newisstring;
    int canisstring;
    int newisscalar;
    int canisscalar;

    /* always choose !null over null */
    if(newchoice == NULL)
	return candidate;
    if(candidate == NULL)
	return newchoice;

    newtyp = newchoice->etype;
    cantyp = candidate->etype;
    newisstring = (newtyp == NC_STRING || newtyp == NC_URL);
    canisstring = (cantyp == NC_STRING || cantyp == NC_URL);
    newisscalar = (nclistlength(newchoice->array.dimset0) == 0);
    canisscalar = (nclistlength(candidate->array.dimset0) == 0);

    ASSERT(candidate->nctype == NC_Atomic && newchoice->nctype == NC_Atomic);

    /* choose non-string over string */
    if(canisstring && !newisstring)
	return newchoice;
    if(!canisstring && newisstring)
	return candidate;

    /* choose scalar over array */
    if(canisscalar && !newisscalar)
	return candidate;
    if(!canisscalar && newisscalar)
	return candidate;

    /* otherwise choose existing candidate */
    return candidate;
}

/* computeseqcountconstraints recursive helper function */
static void
computeseqcountconstraintsr(NCDAPCOMMON* dapcomm, CDFnode* node, CDFnode** candidatep)
{
    CDFnode* candidate;
    CDFnode* compound;
    unsigned int i;

    candidate = NULL;
    compound = NULL;
    if(node == NULL)
      return;
    for(i=0;i<nclistlength(node->subnodes);i++) {
        CDFnode* subnode = (CDFnode*)nclistget(node->subnodes,i);
        if(subnode->nctype == NC_Structure || subnode->nctype == NC_Grid)
	    compound = subnode; /* save for later recursion */
	else if(subnode->nctype == NC_Atomic)
	    candidate = prefer(candidate,subnode);
    }
    if(candidate == NULL && compound == NULL) {
	PANIC("cannot find candidate for seqcountconstraints for a sequence");
    } else if(candidate != NULL && candidatep != NULL) {
	*candidatep = candidate;
    } else { /* compound != NULL by construction */
	/* recurse on a nested grids or strucures */
        computeseqcountconstraintsr(dapcomm,compound,candidatep);
    }
}


static unsigned long
cdftotalsize(NClist* dimensions)
{
    unsigned int i;
    unsigned long total = 1;
    if(dimensions != NULL) {
	for(i=0;i<nclistlength(dimensions);i++) {
	    CDFnode* dim = (CDFnode*)nclistget(dimensions,i);
	    total *= dim->dim.declsize;
	}
    }
    return total;
}

/* Estimate variables sizes and then resort the variable list
   by that size
*/
static void
estimatevarsizes(NCDAPCOMMON* dapcomm)
{
    int ivar;
    unsigned int rank;
    size_t totalsize = 0;

    for(ivar=0;ivar<nclistlength(dapcomm->cdf.ddsroot->tree->varnodes);ivar++) {
        CDFnode* var = (CDFnode*)nclistget(dapcomm->cdf.ddsroot->tree->varnodes,ivar);
	NClist* ncdims = var->array.dimset0;
	rank = nclistlength(ncdims);
	if(rank == 0) { /* use instance size of the type */
	    var->estimatedsize = nctypesizeof(var->etype);
#ifdef DEBUG1
fprintf(stderr,"scalar %s.estimatedsize = %lu\n",
	makecdfpathstring(var,"."),var->estimatedsize);
#endif
	} else {
	    unsigned long size = cdftotalsize(ncdims);
	    size *= nctypesizeof(var->etype);
#ifdef DEBUG1
fprintf(stderr,"array %s(%u).estimatedsize = %lu\n",
	makecdfpathstring(var,"."),rank,size);
#endif
	    var->estimatedsize = size;
	}
	totalsize += var->estimatedsize;
    }
#ifdef DEBUG1
fprintf(stderr,"total estimatedsize = %lu\n",totalsize);
#endif
    dapcomm->cdf.totalestimatedsize = totalsize;
}

static NCerror
fetchpatternmetadata(NCDAPCOMMON* dapcomm)
{
    NCerror ncstat = NC_NOERR;
    OCerror ocstat = OC_NOERR;
    OCddsnode ocroot = NULL;
    CDFnode* ddsroot = NULL;
    char* ce = NULL;

    /* Temporary hack: we need to get the selection string
       from the url
    */
    /* Get (almost) unconstrained DDS; In order to handle functions
       correctly, those selections must always be included
    */
    if(FLAGSET(dapcomm->controls,NCF_UNCONSTRAINABLE))
	ce = NULL;
    else
        ce = nulldup(dap_getselection(dapcomm->oc.url));

    /* Get selection constrained DDS */
    ncstat = dap_fetch(dapcomm,dapcomm->oc.conn,ce,OCDDS,&ocroot);
    if(ncstat != NC_NOERR) {
	/* Special Hack. If the protocol is file, then see if
           we can get the dds from the .dods file
        */
	if(strcmp(dapcomm->oc.url->protocol,"file") != 0) {
	    THROWCHK(ocstat); goto done;
	}
	/* Fetch the data dds */
        ncstat = dap_fetch(dapcomm,dapcomm->oc.conn,ce,OCDATADDS,&ocroot);
        if(ncstat != NC_NOERR) {
	    THROWCHK(ncstat); goto done;
	}
	/* Note what we did */
	nclog(NCLOGWARN,"Cannot locate .dds file, using .dods file");
    }

    /* Get selection constrained DAS */
    ncstat = dap_fetch(dapcomm,dapcomm->oc.conn,ce,OCDAS,&dapcomm->oc.ocdasroot);
    if(ncstat != NC_NOERR) {
	/* Ignore but complain */
	nclog(NCLOGWARN,"Could not read DAS; ignored");
        dapcomm->oc.ocdasroot = NULL;
	ncstat = NC_NOERR;
    }

    /* Construct the netcdf cdf tree corresponding to the dds tree*/
    ncstat = buildcdftree(dapcomm,ocroot,OCDDS,&ddsroot);
    if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto done;}
    dapcomm->cdf.fullddsroot = ddsroot;
    ddsroot = NULL; /* avoid double reclaim */

    /* Combine DDS and DAS */
    if(dapcomm->oc.ocdasroot != NULL) {
	ncstat = dapmerge(dapcomm,dapcomm->cdf.fullddsroot,
                           dapcomm->oc.ocdasroot);
        if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto done;}
    }

#ifdef DEBUG2
fprintf(stderr,"full pattern:\n%s",dumptree(dapcomm->cdf.fullddsroot));
#endif

done:
    nullfree(ce);
    if(ocstat != OC_NOERR) ncstat = ocerrtoncerr(ocstat);
    return ncstat;
}

static NCerror
fetchconstrainedmetadata(NCDAPCOMMON* dapcomm)
{
    NCerror ncstat = NC_NOERR;
    OCerror ocstat = OC_NOERR;
    OCddsnode ocroot;
    CDFnode* ddsroot; /* constrained */
    char* ce = NULL;

    if(FLAGSET(dapcomm->controls,NCF_UNCONSTRAINABLE))
	ce = NULL;
    else
        ce = dcebuildconstraintstring(dapcomm->oc.dapconstraint);
    {
        ncstat = dap_fetch(dapcomm,dapcomm->oc.conn,ce,OCDDS,&ocroot);
        if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto fail;}

        /* Construct our parallel dds tree; including attributes*/
        ncstat = buildcdftree(dapcomm,ocroot,OCDDS,&ddsroot);
        if(ncstat) goto fail;
	ocroot = NULL; /* avoid duplicate reclaim */

	dapcomm->cdf.ddsroot = ddsroot;
	ddsroot = NULL; /* to avoid double reclamation */

        if(!FLAGSET(dapcomm->controls,NCF_UNCONSTRAINABLE)) {
            /* fix DAP server problem by adding back any inserting needed structure nodes */
            ncstat = restruct(dapcomm, dapcomm->cdf.ddsroot,dapcomm->cdf.fullddsroot,dapcomm->oc.dapconstraint->projections);
            if(ncstat) goto fail;
	}

#ifdef DEBUG2
fprintf(stderr,"constrained:\n%s",dumptree(dapcomm->cdf.ddsroot));
#endif

        /* Combine DDS and DAS */
	if(dapcomm->oc.ocdasroot != NULL) {
            ncstat = dapmerge(dapcomm,dapcomm->cdf.ddsroot,
                               dapcomm->oc.ocdasroot);
            if(ncstat != NC_NOERR) {THROWCHK(ncstat); goto fail;}
	}
        /* map the constrained DDS to the unconstrained DDS */
        ncstat = mapnodes(dapcomm->cdf.ddsroot,dapcomm->cdf.fullddsroot);
        if(ncstat) goto fail;

    }

fail:
    nullfree(ce);
    if(ocstat != OC_NOERR) ncstat = ocerrtoncerr(ocstat);
    return ncstat;
}

/* Suppress variables not in usable sequences*/
static NCerror
suppressunusablevars(NCDAPCOMMON* dapcomm)
{
    int i,j;
    int found = 1;
    NClist* path = nclistnew();

    while(found) {
	found = 0;
	/* Walk backwards to aid removal semantics */
	for(i=nclistlength(dapcomm->cdf.ddsroot->tree->varnodes)-1;i>=0;i--) {
	    CDFnode* var = (CDFnode*)nclistget(dapcomm->cdf.ddsroot->tree->varnodes,i);
	    /* See if this var is under an unusable sequence */
	    nclistclear(path);
	    collectnodepath(var,path,WITHOUTDATASET);
	    for(j=0;j<nclistlength(path);j++) {
		CDFnode* node = (CDFnode*)nclistget(path,j);
		if(node->nctype == NC_Sequence
		   && !node->usesequence) {
#ifdef DEBUG
fprintf(stderr,"suppressing var in unusable sequence: %s.%s\n",node->ncfullname,var->ncbasename);
#endif
		    found = 1;
		    break;
		}
	    }
	    if(found) break;
	}
        if(found) nclistremove(dapcomm->cdf.ddsroot->tree->varnodes,i);
    }
    nclistfree(path);
    return NC_NOERR;
}


/*
For variables which have a zero size dimension,
make them invisible.
*/
static NCerror
fixzerodims(NCDAPCOMMON* dapcomm)
{
    int i,j;
    for(i=0;i<nclistlength(dapcomm->cdf.ddsroot->tree->varnodes);i++) {
	CDFnode* var = (CDFnode*)nclistget(dapcomm->cdf.ddsroot->tree->varnodes,i);
        NClist* ncdims = var->array.dimsetplus;
	if(nclistlength(ncdims) == 0) continue;
        for(j=0;j<nclistlength(ncdims);j++) {
	    CDFnode* dim = (CDFnode*)nclistget(ncdims,j);
	    if(dim->dim.declsize == 0) {
	 	/* make node invisible */
		var->invisible = 1;
		var->zerodim = 1;
	    }
	}
    }
    return NC_NOERR;
}

static void
applyclientparamcontrols(NCDAPCOMMON* dapcomm)
{
    /* clear the flags */
    CLRFLAG(dapcomm->controls,NCF_CACHE);
    CLRFLAG(dapcomm->controls,NCF_SHOWFETCH);
    CLRFLAG(dapcomm->controls,NCF_NC3);
    CLRFLAG(dapcomm->controls,NCF_NCDAP);
    CLRFLAG(dapcomm->controls,NCF_PREFETCH);
    CLRFLAG(dapcomm->controls,NCF_PREFETCH_EAGER);

    /* Turn on any default on flags */
    SETFLAG(dapcomm->controls,DFALT_ON_FLAGS);
    SETFLAG(dapcomm->controls,(NCF_NC3|NCF_NCDAP));

    /* enable/disable caching */
    if(dapparamcheck(dapcomm,"cache",NULL))
	SETFLAG(dapcomm->controls,NCF_CACHE);
    else if(dapparamcheck(dapcomm,"nocache",NULL))
	CLRFLAG(dapcomm->controls,NCF_CACHE);

    /* enable/disable cache prefetch and lazy vs eager*/
    if(dapparamcheck(dapcomm,"prefetch","eager")) {
        SETFLAG(dapcomm->controls,NCF_PREFETCH);
        SETFLAG(dapcomm->controls,NCF_PREFETCH_EAGER);
    } else if(dapparamcheck(dapcomm,"prefetch","lazy")
              || dapparamcheck(dapcomm,"prefetch",NULL)) {
        SETFLAG(dapcomm->controls,NCF_PREFETCH);
        CLRFLAG(dapcomm->controls,NCF_PREFETCH_EAGER);
    } else if(dapparamcheck(dapcomm,"noprefetch",NULL))
        CLRFLAG(dapcomm->controls,NCF_PREFETCH);

    if(FLAGSET(dapcomm->controls,NCF_UNCONSTRAINABLE))
	SETFLAG(dapcomm->controls,NCF_CACHE);

    if(dapparamcheck(dapcomm,"show","fetch"))
	SETFLAG(dapcomm->controls,NCF_SHOWFETCH);

    /* enable/disable _FillValue/Variable Mismatch */
    if(dapparamcheck(dapcomm,"fillmismatch",NULL))
	SETFLAG(dapcomm->controls,NCF_FILLMISMATCH);
    else if(dapparamcheck(dapcomm,"nofillmismatch",NULL))
	CLRFLAG(dapcomm->controls,NCF_FILLMISMATCH);

    nclog(NCLOGNOTE,"Caching=%d",FLAGSET(dapcomm->controls,NCF_CACHE));

}

/*
Force dap2 access to be read-only
*/
int
NCD2_set_fill(int ncid, int fillmode, int* old_modep)
{
    return THROW(NC_EPERM);
}

int
NCD2_def_dim(int ncid, const char* name, size_t len, int* idp)
{
    return THROW(NC_EPERM);
}

int
NCD2_put_att(int ncid, int varid, const char* name, nc_type datatype,
	   size_t len, const void* value, nc_type t)
{
    return THROW(NC_EPERM);
}

int
NCD2_def_var(int ncid, const char *name,
  	     nc_type xtype, int ndims, const int *dimidsp, int *varidp)
{
    return THROW(NC_EPERM);
}

/*
Following functions basically return the netcdf-3 value WRT to the nc3id.
*/

int
NCD2_inq_format(int ncid, int* formatp)
{
    NC* drno;
    int ret = NC_NOERR;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_format(getnc3id(drno), formatp);
    return THROW(ret);
}

int
NCD2_inq(int ncid, int* ndimsp, int* nvarsp, int* nattsp, int* unlimdimidp)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq(getnc3id(drno), ndimsp, nvarsp, nattsp, unlimdimidp);
    return THROW(ret);
}

int
NCD2_inq_type(int ncid, nc_type p2, char* p3, size_t* p4)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_type(getnc3id(drno), p2, p3, p4);
    return THROW(ret);
}

int
NCD2_inq_dimid(int ncid, const char* name, int* idp)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_dimid(getnc3id(drno), name, idp);
    return THROW(ret);
}

int
NCD2_inq_dim(int ncid, int dimid, char* name, size_t* lenp)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_dim(getnc3id(drno), dimid, name, lenp);
    return THROW(ret);
}

int
NCD2_inq_unlimdim(int ncid, int* unlimdimidp)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_unlimdim(getnc3id(drno), unlimdimidp);
    return THROW(ret);
}

int
NCD2_rename_dim(int ncid, int dimid, const char* name)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_rename_dim(getnc3id(drno), dimid, name);
    return THROW(ret);
}

int
NCD2_inq_att(int ncid, int varid, const char* name,
	    nc_type* xtypep, size_t* lenp)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_att(getnc3id(drno), varid, name, xtypep, lenp);
    return THROW(ret);
}

int
NCD2_inq_attid(int ncid, int varid, const char *name, int *idp)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_attid(getnc3id(drno), varid, name, idp);
    return THROW(ret);
}

int
NCD2_inq_attname(int ncid, int varid, int attnum, char* name)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_attname(getnc3id(drno), varid, attnum, name);
    return THROW(ret);
}

int
NCD2_rename_att(int ncid, int varid, const char* name, const char* newname)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_rename_att(getnc3id(drno), varid, name, newname);
    return THROW(ret);
}

int
NCD2_del_att(int ncid, int varid, const char* p3)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_del_att(getnc3id(drno), varid, p3);
    return THROW(ret);
}

int
NCD2_get_att(int ncid, int varid, const char* name, void* value, nc_type t)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = NCDISPATCH_get_att(getnc3id(drno), varid, name, value, t);
    return THROW(ret);
}

int
NCD2_inq_var_all(int ncid, int varid, char *name, nc_type* xtypep,
               int* ndimsp, int* dimidsp, int* nattsp,
               int* shufflep, int* deflatep, int* deflate_levelp,
               int* fletcher32p, int* contiguousp, size_t* chunksizesp,
               int* no_fill, void* fill_valuep, int* endiannessp,
	       unsigned int* idp, size_t* nparamsp, unsigned int* params
               )
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = NCDISPATCH_inq_var_all(getnc3id(drno), varid, name, xtypep,
               ndimsp, dimidsp, nattsp,
               shufflep, deflatep, deflate_levelp,
               fletcher32p, contiguousp, chunksizesp,
               no_fill, fill_valuep, endiannessp,
	       idp,nparamsp,params
	       );
    return THROW(ret);
}

int
NCD2_inq_varid(int ncid, const char *name, int *varidp)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_varid(getnc3id(drno),name,varidp);
    return THROW(ret);
}

int
NCD2_rename_var(int ncid, int varid, const char* name)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_rename_var(getnc3id(drno), varid, name);
    return THROW(ret);
}

int
NCD2_var_par_access(int ncid, int p2, int p3)
{
    return THROW(NC_ENOPAR);
}

int
NCD2_def_var_fill(int ncid, int p2, int p3, const void* p4)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_var_fill(getnc3id(drno), p2, p3, p4);
    return THROW(ret);
}

int
NCD2_inq_ncid(int ncid, const char* name, int* grp_ncid)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_ncid(getnc3id(drno), name, grp_ncid);
    return THROW(ret);
}

int
NCD2_show_metadata(int ncid)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_show_metadata(getnc3id(drno));
    return THROW(ret);
}

int
NCD2_inq_grps(int ncid, int* p2, int* p3)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_grps(getnc3id(drno), p2, p3);
    return THROW(ret);
}

int
NCD2_inq_grpname(int ncid, char* p)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_grpname(getnc3id(drno), p);
    return THROW(ret);
}


int
NCD2_inq_unlimdims(int ncid, int* p2, int* p3)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_unlimdims(getnc3id(drno), p2, p3);
    return THROW(ret);
}

int
NCD2_inq_grpname_full(int ncid, size_t* p2, char* p3)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_grpname_full(getnc3id(drno), p2, p3);
    return THROW(ret);
}

int
NCD2_inq_grp_parent(int ncid, int* p)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_grp_parent(getnc3id(drno), p);
    return THROW(ret);
}

int
NCD2_inq_grp_full_ncid(int ncid, const char* p2, int* p3)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_grp_full_ncid(getnc3id(drno), p2, p3);
    return THROW(ret);
}

int
NCD2_inq_varids(int ncid, int* nvars, int* p)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_varids(getnc3id(drno), nvars, p);
    return THROW(ret);
}

int
NCD2_inq_dimids(int ncid, int* ndims, int* p3, int p4)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_dimids(getnc3id(drno), ndims, p3, p4);
    return THROW(ret);
}

int
NCD2_inq_typeids(int ncid, int*  ntypes, int* p)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_typeids(getnc3id(drno), ntypes, p);
    return THROW(ret);
}

int
NCD2_inq_type_equal(int ncid, nc_type t1, int p3, nc_type t2, int* p5)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_type_equal(getnc3id(drno), t1, p3, t2, p5);
    return THROW(ret);
}

int
NCD2_inq_user_type(int ncid, nc_type t, char* p3, size_t* p4, nc_type* p5,
                   size_t* p6, int* p7)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_user_type(getnc3id(drno), t, p3, p4, p5, p6, p7);
    return THROW(ret);
}

int
NCD2_inq_typeid(int ncid, const char* name, nc_type* t)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_typeid(getnc3id(drno), name, t);
    return THROW(ret);
}

int
NCD2_def_grp(int ncid, const char* p2, int* p3)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_grp(getnc3id(drno), p2, p3);
    return THROW(ret);
}

int
NCD2_rename_grp(int ncid, const char* p)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_rename_grp(getnc3id(drno), p);
    return THROW(ret);
}

int
NCD2_def_compound(int ncid, size_t p2, const char* p3, nc_type* t)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_compound(getnc3id(drno), p2, p3, t);
    return THROW(ret);
}

int
NCD2_insert_compound(int ncid, nc_type t1, const char* p3, size_t p4, nc_type t2)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_insert_compound(getnc3id(drno), t1, p3, p4, t2);
    return THROW(ret);
}

int
NCD2_insert_array_compound(int ncid, nc_type t1, const char* p3, size_t p4,
			  nc_type t2, int p6, const int* p7)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_insert_array_compound(getnc3id(drno), t1, p3, p4,  t2, p6, p7);
    return THROW(ret);
}

int
NCD2_inq_compound_field(int ncid, nc_type xtype, int fieldid, char *name,
		      size_t *offsetp, nc_type* field_typeidp, int *ndimsp,
		      int *dim_sizesp)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_compound_field(getnc3id(drno), xtype, fieldid, name, offsetp, field_typeidp, ndimsp, dim_sizesp);
    return THROW(ret);
}

int
NCD2_inq_compound_fieldindex(int ncid, nc_type xtype, const char *name,
			   int *fieldidp)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_compound_fieldindex(getnc3id(drno), xtype, name, fieldidp);
    return THROW(ret);
}

int
NCD2_def_vlen(int ncid, const char* p2, nc_type base_typeid, nc_type* t)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_vlen(getnc3id(drno), p2, base_typeid, t);
    return THROW(ret);
}

int
NCD2_put_vlen_element(int ncid, int p2, void* p3, size_t p4, const void* p5)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_put_vlen_element(getnc3id(drno), p2, p3, p4, p5);
    return THROW(ret);
}

int
NCD2_get_vlen_element(int ncid, int p2, const void* p3, size_t* p4, void* p5)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_get_vlen_element(getnc3id(drno), p2, p3, p4, p5);
    return THROW(ret);
}

int
NCD2_def_enum(int ncid, nc_type t1, const char* p3, nc_type* t)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_enum(getnc3id(drno), t1, p3, t);
    return THROW(ret);
}

int
NCD2_insert_enum(int ncid, nc_type t1, const char* p3, const void* p4)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_insert_enum(getnc3id(drno), t1, p3, p4);
    return THROW(ret);
}

int
NCD2_inq_enum_member(int ncid, nc_type t1, int p3, char* p4, void* p5)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_enum_member(getnc3id(drno), t1, p3, p4, p5);
    return THROW(ret);
}

int
NCD2_inq_enum_ident(int ncid, nc_type t1, long long p3, char* p4)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_inq_enum_ident(getnc3id(drno), t1, p3, p4);
    return THROW(ret);
}

int
NCD2_def_opaque(int ncid, size_t p2, const char* p3, nc_type* t)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_opaque(getnc3id(drno), p2, p3, t);
    return THROW(ret);
}

int
NCD2_def_var_deflate(int ncid, int p2, int p3, int p4, int p5)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_var_deflate(getnc3id(drno), p2, p3, p4, p5);
    return THROW(ret);
}

int
NCD2_def_var_fletcher32(int ncid, int p2, int p3)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_var_fletcher32(getnc3id(drno), p2, p3);
    return THROW(ret);
}

int
NCD2_def_var_chunking(int ncid, int p2, int p3, const size_t* p4)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_var_chunking(getnc3id(drno), p2, p3, p4);
    return THROW(ret);
}

int
NCD2_def_var_endian(int ncid, int p2, int p3)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_var_endian(getnc3id(drno), p2, p3);
    return THROW(ret);
}

int
NCD2_def_var_filter(int ncid, int varid, unsigned int id, size_t n, const unsigned int* params)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_def_var_filter(getnc3id(drno), varid, id, n, params);
    return THROW(ret);
}

int
NCD2_set_var_chunk_cache(int ncid, int p2, size_t p3, size_t p4, float p5)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_set_var_chunk_cache(getnc3id(drno), p2, p3, p4, p5);
    return THROW(ret);
}

int
NCD2_get_var_chunk_cache(int ncid, int p2, size_t* p3, size_t* p4, float* p5)
{
    NC* drno;
    int ret;
    if((ret = NC_check_id(ncid, (NC**)&drno)) != NC_NOERR) return THROW(ret);
    ret = nc_get_var_chunk_cache(getnc3id(drno), p2, p3, p4, p5);
    return THROW(ret);
}