File: avtCGNSFileFormat.C

package info (click to toggle)
paraview 4.0.1-1~bpo70%2B1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy-backports
  • size: 526,572 kB
  • sloc: cpp: 2,284,430; ansic: 816,374; python: 239,936; xml: 70,162; tcl: 48,295; fortran: 39,116; yacc: 5,466; java: 3,518; perl: 3,107; lex: 1,620; sh: 1,555; makefile: 932; asm: 471; pascal: 228
file content (2604 lines) | stat: -rw-r--r-- 92,395 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
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
/*****************************************************************************
*
* Copyright (c) 2000 - 2012, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/

// ************************************************************************* //
//                            avtCGNSFileFormat.C                            //
// ************************************************************************* //

#include <avtCGNSFileFormat.h>
#include <cgnslib.h>

#include <algorithm>
#include <string>

#include <vtkCellTypes.h>
#include <vtkCharArray.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkIntArray.h>
#include <vtkRectilinearGrid.h>
#include <vtkStructuredGrid.h>
#include <vtkUnstructuredGrid.h>

#include <avtCallback.h>
#include <avtDatabaseMetaData.h>

#include <Expression.h>
#include <DebugStream.h>
#include <snprintf.h>

#include <ImproperUseException.h>
#include <InvalidFilesException.h>
#include <InvalidVariableException.h>

#define INVALID_FILE_HANDLE -1

// Include more source code.
#include <CGNSHelpers.C>
#include <CGNSUnitsStack.C>

// ****************************************************************************
// Method: MakeSafeVariableName
//
// Purpose:
//   Replace characters that might confuse VisIt's expression parser.
//
// Arguments:
//   var : The variable name to fix.
//
// Returns:    A safe variable name.
//
// Note:
//
// Programmer: Brad Whitlock
// Creation:   Thu Apr 17 10:16:39 PDT 2008
//
// Modifications:
//
// ****************************************************************************

std::string
MakeSafeVariableName(const std::string &var)
{
    char *tmp = new char[var.size() + 1];
    strcpy(tmp, var.c_str());

    // Replace characters that could confuse VisIt.
    char invalids[][2] = {
        {' ', '_'},
        {'{', '_'},
        {'}', '_'},
        {'[', '_'},
        {']', '_'},

        {'!', '_'},
        {'@', '_'},
        {'#', '_'},
        {'$', '_'},
        {'%', '_'},
        {'^', '_'},
        {'&', '_'},
        {'*', '_'},
        {'(', '_'},
        {')', '_'},

        {'+', '_'},
        {'-', '_'},
        {'/', '_'},

        {';', '_'},
        {':', '_'},
        {',', '_'},
        {'.', '_'},
        {'<', '_'},
        {'>', '_'},
    };
    int nInvalids = sizeof(invalids) / (sizeof(char)*2);
    for(int i = 0; i < nInvalids; ++i)
    {
        for(size_t ci = 0; ci < var.size(); ++ci)
        {
            if(tmp[ci] == invalids[i][0])
                tmp[ci] = invalids[i][1];
        }
    }

    std::string retval(tmp);
    delete [] tmp;
    return retval;
}

// ****************************************************************************
//  Method: avtCGNSFileFormat constructor
//
//  Programmer: Brad Whitlock
//  Creation:   Tue Aug 30 16:08:44 PST 2005
//
//  Modifications:
//    Brad Whitlock, Tue Apr 15 16:00:52 PDT 2008
//    Added cgnsFileName, BaseNameToIndices, VisItNameToCGNSName.
//
// ****************************************************************************

avtCGNSFileFormat::avtCGNSFileFormat(const char *filename)
    : avtMTMDFileFormat(filename), times(), MeshDomainMapping(), BaseNameToIndices(),
    VisItNameToCGNSName()
{
    cgnsFileName = new char[strlen(filename) + 1];
    strcpy(cgnsFileName, filename);

    debug1 << "avtCGNSFileFormat::avtCGNSFileFormat: filename=" << cgnsFileName << endl;
    fn = INVALID_FILE_HANDLE;
    timesRead = false;
    cgnsCyclesAccurate = false;
    cgnsTimesAccurate = false;
    initializedMaps = false;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::~avtCGNSFileFormat
//
// Purpose:
//   Destructor for the avtCGNSFileFormat class.
//
// Programmer: Brad Whitlock
// Creation:   Tue Aug 30 16:12:20 PST 2005
//
// Modifications:
//
// ****************************************************************************

avtCGNSFileFormat::~avtCGNSFileFormat()
{
    delete [] cgnsFileName;
    FreeUpResources();
}

// ****************************************************************************
//  Method: avtEMSTDFileFormat::GetNTimesteps
//
//  Purpose:
//      Tells the rest of the code how many timesteps there are in this file.
//
//  Programmer: Brad Whitlock
//  Creation:   Tue Aug 30 16:08:44 PST 2005
//
// ****************************************************************************

int
avtCGNSFileFormat::GetNTimesteps(void)
{
    ReadTimes();

    return times.size();
}

// ****************************************************************************
//  Method: avtCGNSFileFormat::FreeUpResources
//
//  Purpose:
//      When VisIt is done focusing on a particular timestep, it asks that
//      timestep to free up any resources (memory, file descriptors) that
//      it has associated with it.  This method is the mechanism for doing
//      that.
//
//  Programmer: Brad Whitlock
//  Creation:   Tue Aug 30 16:08:44 PST 2005
//
// ****************************************************************************

void
avtCGNSFileFormat::FreeUpResources(void)
{
    if(fn != INVALID_FILE_HANDLE)
    {
        cg_close(fn);
        fn = INVALID_FILE_HANDLE;
    }
}

// ****************************************************************************
// Method: avtCGNSFileFormat::GetFileHandle
//
// Purpose:
//   This method opens the CGNS file and returns the file handle.
//
// Returns:    The file handle.
//
// Programmer: Brad Whitlock
// Creation:   Wed Aug 31 09:35:12 PDT 2005
//
// Modifications:
//   Brad Whitlock, Wed Apr 16 10:15:07 PDT 2008
//   Made it use cgnsFileName.
//
// ****************************************************************************

int
avtCGNSFileFormat::GetFileHandle()
{
    if(fn == INVALID_FILE_HANDLE)
    {
#ifdef CG_MODE_READ
        if(cg_open(cgnsFileName, CG_MODE_READ, &fn) != CG_OK)
#else
        // Still support pre 2.5 CGNS
        if(cg_open(cgnsFileName, MODE_READ, &fn) != CG_OK)
#endif
        {
            debug4 << cg_get_error() << endl;
            EXCEPTION1(InvalidFilesException, cgnsFileName);
        }
    }

    return fn;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::ReadTimes
//
// Purpose:
//   This method reads the times from the file and stores them in the
//   local times vector.
//
// Programmer: Brad Whitlock
// Creation:   Wed Aug 31 09:34:43 PDT 2005
//
// Modifications:
//   Maxim Loginov, Tue Mar  4 12:28:12 NOVT 2008
//   Bugfixes and improve reading times from BaseIterativeData_t node
//
//   Brad Whitlock, Wed Apr 16 10:15:21 PDT 2008
//   Made it use cgnsFileName.
//
//   Kathleen Biagas, Tue Apr 24 12:23:03 PDT 2012
//   Added call to FreeUpResources to prevent crash when opening many files
//   in a virtual database.
//
// ****************************************************************************

void
avtCGNSFileFormat::ReadTimes()
{
    const char *mName = "avtCGNSFileFormat::ReadTimes: ";

    if(!timesRead)
    {
        debug4 << mName << "Start" << endl;

        // Read the number of bases and use that for the time step.
        int nbases = 0;
        if(cg_nbases(GetFileHandle(), &nbases) != CG_OK)
        {
            debug4 << cg_get_error() << endl;
            EXCEPTION1(InvalidFilesException, cgnsFileName);
        }

        bool createTimeStates = true;
        bool createCycleStates = true;

        // TODO only one (first) base is considered currently
        int base = 1;
        int nstates = 1;
        char namenode[33];
        if(cg_biter_read(GetFileHandle(), base, namenode, &nstates) == CG_OK)
        {
            debug4 << mName << "nstates determined to be: " << nstates << endl;
            debug4 << mName << "node name: " << namenode << endl;
            if(cg_goto(GetFileHandle(), base, "BaseIterativeData_t", 1, "end") == CG_OK)
            {
                // check all arrays under the BaseIterativeData_t node
                int narrays = 0;
                if(cg_narrays(&narrays) == CG_OK)
                {
                    debug4 << mName << narrays
                       << " array(s) under BaseIterative" << endl;
                    for(int i = 0; i < narrays; ++i)
                    {
                        int ndims = 1;
                        cgsize_t dims[10];
                        DataType_t dt;
                        if(cg_array_info(i+1, namenode, &dt, &ndims, dims) == CG_OK)
                        {
                            debug4 << mName << "array name: " << namenode << endl;
                            if(strcmp(namenode,"TimeValues") == 0 ||
                               strcmp(namenode,"TimeIterValues") == 0 ||
                               strcmp(namenode,"Times") == 0
                               )
                            {
                                double *dvals = new double[nstates+1];
                                if(cg_array_read_as(i+1, RealDouble, dvals) == CG_OK)
                                {
                                    createTimeStates = false;
                                    times.clear();
                                    debug4 << mName << "Times = {";
                                    for(int j = 0; j < nstates; ++j)
                                    {
                                        debug4 << dvals[j] << ", ";
                                        times.push_back(dvals[j]);
                                    }
                                    debug4 << "}" << endl;
                                }
                                else
                                {
                                    debug4 << mName << "Could not read the array: "
                                           << cg_get_error() << endl;
                                }
                                delete [] dvals;
                            }
                            else if(strcmp(namenode,"IterationValues") == 0 ||
                                    strcmp(namenode,"Cycles") == 0
                                    )
                            {
                                int *ivals = new int[nstates+1];
                                if(cg_array_read_as(i+1, Integer, ivals) == CG_OK)
                                {
                                    createCycleStates = false;
                                    cycles.clear();
                                    debug4 << mName << "Cycles = {";
                                    for(int j = 0; j < nstates; ++j)
                                    {
                                        debug4 << ivals[j] << ", ";
                                        cycles.push_back(ivals[j]);
                                    }
                                    debug4 << "}" << endl;
                                }
                                else
                                {
                                    debug4 << mName << "Could not read the array: "
                                           << cg_get_error() << endl;
                                }
                                delete [] ivals;
                            }
                            else
                            {
                                debug5 << mName << namenode << " is not known" << endl;
                            }
                        }
                        else
                        {
                            debug4 << mName << "Could not read " << i+1 << " array info: "
                                   << cg_get_error() << endl;
                        }
                    }
                }
                else
                {
                    debug4 << mName << "Could not read narrays under BaseIterative node: "
                       << cg_get_error() << endl;
                }
            }
            else
            {
                debug4 << mName << "Could not go to BaseIterative node: "
                       << cg_get_error() << endl;
            }
        }
        else
        {
            debug4 << mName << "We can't determine the number of states. Assume 1"
                   << endl;
        }

        if(createTimeStates)
        {
            debug4 << mName << "Creating fake times." << endl;
            // Fake the times for now.
            for(int i = 0; i < nstates; ++i)
                times.push_back(double(i));
        }
        else
            cgnsTimesAccurate = true;

        if(createCycleStates)
        {
            debug4 << mName << "Creating fake cycles." << endl;
            // Fake the cycles for now.
            for(int i = 0; i < nstates; ++i)
                cycles.push_back(i);
        }
        else
           cgnsCyclesAccurate = true;

        timesRead = true;
        debug4 << mName << "End" << endl;
    }
    // make sure file handles are closed
    FreeUpResources();
}

// ****************************************************************************
// Method: avtCGNSFileFormat::GetTimes
//
// Purpose:
//   Returns the times for the database.
//
// Arguments:
//   t : The return vector for the times.
//
// Programmer: Brad Whitlock
// Creation:   Wed Aug 31 09:34:21 PDT 2005
//
// Modifications:
//
// ****************************************************************************

void
avtCGNSFileFormat::GetTimes(std::vector<double> &t)
{
    ReadTimes();
    t = times;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::GetCycles
//
// Purpose:
//   Returns the cycles for the database.
//
// Arguments:
//   c : The return vector for the cycles.
//
// Programmer: Maxim Loginov
// Creation:   Mon Mar  3 18:18:32 NOVT 2008
//
// Modifications:
//
// ****************************************************************************

void
avtCGNSFileFormat::GetCycles(std::vector<int> &c)
{
    // ncycles is equal to ntimes (CGNS MLL check this)
    ReadTimes();
    c = cycles;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::BaseContainsUnits
//
// Purpose:
//   Returns whether the base contains units.
//
// Arguments:
//   baes : The base to check for units.
//
// Returns:    True if the base contains units; false otherwise.
//
// Note:
//
// Programmer: Brad Whitlock
// Creation:   Thu Apr 17 10:18:33 PDT 2008
//
// Modifications:
//
// ****************************************************************************

bool
avtCGNSFileFormat::BaseContainsUnits(int base)
{
    const char *mName = "avtCGNSFileFormat::BaseContainsUnits: ";
    bool baseContainsUnits = false;
    MassUnits_t        massU;
    LengthUnits_t      lengthU;
    TimeUnits_t        timeU;
    TemperatureUnits_t tempU;
    AngleUnits_t       angleU;
    bool unitError = false;
    if(cg_goto(GetFileHandle(), base, "end") == CG_OK)
    {
        DataClass_t dc = DataClassNull;
        if(cg_dataclass_read(&dc) == CG_OK)
        {
            baseContainsUnits = (dc == Dimensional);
            int nunits = 0;
            if(baseContainsUnits &&
               cg_nunits(&nunits) == CG_OK &&
               nunits > 0)
            {
                if(cg_units_read(&massU, &lengthU, &timeU,
                                 &tempU, &angleU) == CG_OK)
                {
                    debug4 << mName << "We read the units!" << endl;
                    baseContainsUnits = true;
                }
            }
            else
            {
                baseContainsUnits = false;
                unitError = true;
            }
        }
        else
            unitError = true;
    }
    else
        unitError = true;
    if(unitError)
        debug4 << mName << "No units: " << cg_get_error() << endl;
    else
    {
        debug4 << mName << "The base " << base << " has" << (baseContainsUnits?"":" no")
               << " units." << endl;
    }

    return baseContainsUnits;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::GetVariablesForBase
//
// Purpose:
//   Iterates over a base and populates BaseInformation, which contains the
//   zone names, list of variables, and how each variable is mapped onto zones.
//
// Arguments:
//   base     : The base we're checking.
//   baseInfo : The base information that we're going to populate.
//
// Returns:    True on success; false on failure.
//
// Note:
//
// Programmer: Brad Whitlock
// Creation:   Thu Apr 17 10:19:18 PDT 2008
//
// Modifications:
//
// ****************************************************************************

bool
avtCGNSFileFormat::GetVariablesForBase(int base, avtCGNSFileFormat::BaseInformation &baseInfo)
{
    const char *mName = "avtCGNSFileFormat::GetVariablesForBase: ";

    bool retval = true;
    int  numCellVariable = 0;
    char namebase[33];
    if(cg_base_read(GetFileHandle(), base, namebase, &baseInfo.cellDim, &baseInfo.physicalDim) != CG_OK)
    {
        debug1 << "Could not read base " << base << endl;
        retval = false;
    }
    else
    {
        // Save the base name.
        baseInfo.name = namebase;
        debug4 << mName << "base " << namebase << ": " << endl;

        //
        // Determine the number of domains.
        //
        int nZones = 0;
        if(cg_nzones(GetFileHandle(), base, &nZones) != CG_OK)
        {
            debug4 << mName << "Could not get number of domains in base "
                   << base << ": " << cg_get_error() << endl;
            return false;
        }

        CGNSUnitsStack unitStack;
        bool baseUnits = BaseContainsUnits(base) &&
                         unitStack.PushUnits(GetFileHandle(), base);
        //
        // Iterate over the domains.
        //
        baseInfo.meshType = 0;
        for(int zone = 1; zone <= nZones; ++zone)
        {
            // Get information about the zone.
            char zonename[33];
            cgsize_t zsize[9];
            memset(zonename, 0, 33);
            memset(zsize, 0, 9 * sizeof(int));

            debug4 << "\tzone " << zone << endl;
            // Print the name and size.
            if(cg_zone_read(GetFileHandle(), base, zone, zonename, zsize) != CG_OK)
                debug4 << cg_get_error() << endl;
            else
            {
                debug4 << "\t\tname=" << zonename << endl;
                debug4 << "\t\tsize=[";
                for(int zi = 0; zi < 9; ++zi)
                {
                    if(zi > 0) debug4 << ", ";
                        debug4 << zsize[zi];
                }
                debug4 << "]" << endl;
            }
            // Save the domain name.
            baseInfo.zoneNames.push_back(zonename);

            // Get the zone type.
            ZoneType_t zt = ZoneTypeNull;
            if(cg_zone_type(GetFileHandle(), base, zone, &zt) != CG_OK)
                debug4 << cg_get_error() << endl;
            else
            {
                switch(zt)
                {
                case ZoneTypeNull:
                    debug4 << " type=ZoneTypeNull (NOT SUPPORTED!)";
                    baseInfo.meshType = -1;
                    break;
                case ZoneTypeUserDefined:
                    debug4 << " type=ZoneTypeUserDefined (NOT SUPPORTED!)";
                    baseInfo.meshType = -2;
                    break;
                case Structured:
                    debug4 << " type=Structured";
                    baseInfo.meshType |= 0;
                    break;
                case Unstructured:
                    debug4 << " type=Unstructured";
                    baseInfo.meshType |= 1;
                    break;
                }
            }

            // Get the units for the zone.
            bool zoneUnits = (zone == 1) && baseUnits &&
                              unitStack.PushUnits(GetFileHandle(), base, zone);

            int nsols = 0;
            if(cg_nsols(GetFileHandle(), base, zone, &nsols) != CG_OK)
            {
                debug4 << "Could not get number of solutions in zone "
                       << zone << endl;
                debug4 << cg_get_error() << endl;
                continue;
            }
            debug4 << "\t\tnsols=" << nsols << endl;

            //
            // Iterate over the solutions.
            //
            for(int sol = 1; sol <= nsols; ++sol)
            {
                char solname[33];
                GridLocation_t varcentering;
                if(cg_sol_info(GetFileHandle(), base, zone, sol, solname,
                               &varcentering) != CG_OK)
                {
                    debug4 << "Could not get solution " << sol << "'s info."
                           << endl;
                    debug4 << cg_get_error() << endl;
                    continue;
                }

                debug4 << "\t\t\t" << "solution[" << sol << "]" << solname;

                int nfields = 0;
                if(cg_nfields(GetFileHandle(), base, zone, sol, &nfields) != CG_OK)
                {
                    debug4 << "Could not get number of fields for solution "
                           << sol << endl;
                    debug4 << cg_get_error() << endl;
                    continue;
                }

                // Get the units for the solution.
                bool solUnits = (zone == 1) && baseUnits &&
                            unitStack.PushUnits(GetFileHandle(), base, zone, sol);

                debug4 << "\t\t\t\tnfields=" << nfields << endl;
                debug4 << "\t\t\t\tcentering=";
                int nodeCentering = 0;
                int cellCentering = 0;
                int badCentering = 1;
                switch(varcentering)
                {
                case GridLocationNull:
                     debug4 << "GridLocationNull";
                     break;
                case GridLocationUserDefined:
                     debug4 << "GridLocationUserDefined";
                     break;
                case Vertex:
                     debug4 << "Vertex";
                     nodeCentering = 1;
                     badCentering = 0;
                     break;
                case CellCenter:
                     debug4 << "CellCenter";
                     cellCentering = 1;
                     badCentering = 0;
                     break;
                case FaceCenter:
                     debug4 << "FaceCenter";
                     break;
                case IFaceCenter:
                     debug4 << "IFaceCenter";
                     break;
                case JFaceCenter:
                     debug4 << "JFaceCenter";
                     break;
                case KFaceCenter:
                     debug4 << "KFaceCenter";
                     break;
                case EdgeCenter:
                     debug4 << "EdgeCenter";
                     break;
                }
                debug4 << endl;

                for(int f = 1; f <= nfields; ++f)
                {
                    DataType_t dt;
                    char fieldname[33];

                    if(cg_field_info(GetFileHandle(), base, zone, sol, f, &dt, fieldname) != CG_OK)
                    {
                        debug4 << "Could not get number of fields for solution "
                               << sol << endl;
                        debug4 << cg_get_error() << endl;
                        continue;
                    }
                    debug4 << "\t\t\t\t\tfield[" << f << "]=" << fieldname << endl;

                    // Determine the units for the field.
                    bool fUnits = baseUnits &&
                                  unitStack.PushUnits(GetFileHandle(), base, zone, sol, f);
                    std::string fieldUnits;
                    bool fieldHasUnits = unitStack.GetUnits(fieldUnits);
                    if(fUnits)
                        unitStack.PopUnits();

                    // Now that we have a field in a solution in a zone, let's
                    std::string locatedFieldname(fieldname);
                    if(cellCentering != 0)
                    {
                        locatedFieldname = "CELL_"+locatedFieldname;
                    }
                    // add information about it to the variable information that
                    // we're populating for the current base.
                    // add information about it to the variable information that
                    // we're populating for the current base.
                    StringVarInfoMap::iterator pos = baseInfo.vars.find(locatedFieldname);

                    if(pos == baseInfo.vars.end())
                    {
                        VarInfo info;
                        info.zoneList.push_back(zone);
                        info.cellCentering = cellCentering;
                        info.nodeCentering = nodeCentering;
                        info.badCentering = badCentering;
                        info.hasUnits = fieldHasUnits;
                        if(fieldHasUnits)
                            info.units = fieldUnits;
                        baseInfo.vars[locatedFieldname] = info;
                        numCellVariable += cellCentering;
                    }
                    else if(sol == 1 || GetNTimesteps() == 1)
                    {
                        // We've already run across the variable in another zone
                        // so let's update what we know.
                        // This is done only for first iteration
                        // or steady state.
                        pos->second.zoneList.push_back(zone);
                        pos->second.cellCentering += cellCentering;
                        pos->second.nodeCentering += nodeCentering;
                        pos->second.badCentering += badCentering;
                        pos->second.hasUnits = fieldHasUnits;
                        if(fieldHasUnits)
                            pos->second.units = fieldUnits;
                    }
                } // for field

                // Pop the unit stack.
                if(solUnits)
                    unitStack.PopUnits();
            } // for sol

            // Pop the unit stack.
            if(zoneUnits)
                unitStack.PopUnits();
        } // for zone
    } // base read

    // If only "Cell centered" location is present remove prefix !
    if((numCellVariable != 0) &&
       (numCellVariable == baseInfo.vars.size()))
    {
        StringVarInfoMap newVars;
        //
        for(StringVarInfoMap::iterator pos = baseInfo.vars.begin(); pos != baseInfo.vars.end(); ++pos)
        {
            std::string newname(pos->first);
            newname = newname.substr(5);
            newVars[newname] = pos->second;
        }
        //
        baseInfo.vars.swap(newVars);
    } // base read

    return retval;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::AddVectorExpression
//
// Purpose:
//   Adds a vector expression.
//
// Arguments:
//   md            : The metadata to which the expression will be added.
//   haveComponent : An array of 3 bools indicating whether we have certain
//                   vector components.
//   nBases        : The number of bases in the file.
//   baseName      : The current base name.
//   vecName       : The name of the vector.
//
// Returns:
//
// Note:
//
// Programmer: Brad Whitlock
// Creation:   Thu Apr 17 10:20:41 PDT 2008
//
// Modifications:
//
// ****************************************************************************

void
avtCGNSFileFormat::AddVectorExpression(avtDatabaseMetaData *md, bool *haveComponent,
    int nBases, const std::string &baseName, const std::string &vecName)
{
    char def[300];

    if(haveComponent[0] && haveComponent[1] && haveComponent[2])
    {
        Expression *e = new Expression;
        if(nBases > 1)
        {
            e->SetName(baseName + "/" + vecName);
            SNPRINTF(def, 300, "{<%s/%sX>,<%s/%sY>,<%s/%sZ>}",
                baseName.c_str(), vecName.c_str(),
                baseName.c_str(), vecName.c_str(),
                baseName.c_str(), vecName.c_str());
            e->SetDefinition(def);
        }
        else
        {
            e->SetName(vecName);
            SNPRINTF(def, 300, "{%sX,%sY,%sZ}",
                vecName.c_str(), vecName.c_str(), vecName.c_str());
            e->SetName(vecName);
            e->SetDefinition(def);
        }
        e->SetType(Expression::VectorMeshVar);
        md->AddExpression(e);
    }
    else if(haveComponent[0] && haveComponent[1])
    {
        Expression *e = new Expression;
        if(nBases > 1)
        {
            e->SetName(baseName + "/" + vecName);
            SNPRINTF(def, 300, "{<%s/%sX>,<%s/%sY>}",
                baseName.c_str(), vecName.c_str(),
                baseName.c_str(), vecName.c_str());
            e->SetDefinition(def);
        }
        else
        {
            e->SetName(vecName);
            SNPRINTF(def, 300, "{%sX,%sY}",
                vecName.c_str(), vecName.c_str());
            e->SetName(vecName);
            e->SetDefinition(def);
        }
        e->SetType(Expression::VectorMeshVar);
        md->AddExpression(e);
    }
}

// ****************************************************************************
// Method: avtCGNSFileFormat::AddVectorExpressions
//
// Purpose:
//   Adds vector expressions for velocity and momentum.
//
// Arguments:
//   md            : The metadata to which the expression will be added.
//   haveVelocity  : An array of 3 bools indicating whether we have certain
//                   vector velocity components.
//   haveMomentum  : An array of 3 bools indicating whether we have certain
//                   vector momentum components.
//   nBases        : The number of bases in the file.
//   baseName      : The current base name.
//   vecName       : The name of the vector.
//
// Returns:
//
// Note:
//
// Programmer: Brad Whitlock
// Creation:   Thu Apr 17 10:22:32 PDT 2008
//
// Modifications:
//
// ****************************************************************************

void
avtCGNSFileFormat::AddVectorExpressions(avtDatabaseMetaData *md, bool *haveVelocity,
    bool *haveMomentum, int nBases, const std::string &baseName)
{
    AddVectorExpression(md, haveVelocity, nBases, baseName, "Velocity");
    AddVectorExpression(md, haveMomentum, nBases, baseName, "Momentum");
}

// ****************************************************************************
// Method: avtCGNSFileFormat::AddReferenceStateExpressions
//
// Purpose:
//   Creates constant valued fields on the mesh based on values stored in
//   the reference state.
//
// Arguments:
//   md       : The metadata to which the expressions will be added.
//   base     : The current baes index.
//   nBases   : The number of bases in the file.
//   baseName : The name of the current base.
//   meshName : The name of the mesh on which we'll define the values.
//
// Returns:
//
// Note:
//
// Programmer: Maxim Loginov
// Creation:   Thu Apr 17 10:27:23 PDT 2008
//
// Modifications:
//   Brad Whitlock, Thu Apr 17 10:28:03 PDT 2008
//   Separated out into its own method, add variables as point_constant
//   expressions.
//
//    Jeremy Meredith, Thu Aug  7 15:55:54 EDT 2008
//    Some string comparisons were erroneously comparing char* pointers.
//    I converted them to use strcmp.
//
// ****************************************************************************

void
avtCGNSFileFormat::AddReferenceStateExpressions(avtDatabaseMetaData *md,
    int base, int nBases, const std::string &baseName, const std::string &meshName)
{
    const char *mName = "avtCGNSFileFormat::AddReferenceStateExpressions: ";

    // some constants from ReferenceState_t should be available as array mesh variable
    // TODO not finished yet!!!
    // Note: BJW - We don't have a good way to add constants in VisIt. I just add them
    //             to the 1st mesh as a node-centered constant using the point_constant
    //             expression.
    if(cg_goto(GetFileHandle(), base, "ReferenceState_t", 1, "end") == CG_OK)
    {
        int nrefstate = 0;
        if(cg_narrays(&nrefstate) == CG_OK)
        {
            debug5 << mName << nrefstate << " reference states found" << endl;
            for(int i = 0; i < nrefstate; ++i)
            {
                char namenode[33];
                int ndims = 1;
                cgsize_t dims[10];
                DataType_t dt;
                if(cg_array_info(i+1, namenode, &dt, &ndims, dims) == CG_OK)
                {
                    // there is only one value in each array
                    double dval;
                    char edef[100];
                    cg_array_read_as(i+1, RealDouble, &dval);
                    debug5 << mName << "Reference state: " << namenode
                           << " = " << dval << endl;
                    if(strcmp(namenode,"Mach")==0)
                    {
                        Expression *e = new Expression;
                        if(nBases > 1)
                            e->SetName(baseName + "/mach");
                        else
                            e->SetName("mach");
                        SNPRINTF(edef, 100, "point_constant(%s, %lg)", meshName.c_str(), dval);
                        e->SetDefinition(edef);
                        e->SetType(Expression::ScalarMeshVar);
                        md->AddExpression(e);
                    }
                    else if(strcmp(namenode, "SpecificHeatRatio")==0)
                    {
                        Expression *e = new Expression;
                        if(nBases > 1)
                            e->SetName(baseName + "/gamma");
                        else
                            e->SetName("gamma");
                        SNPRINTF(edef, 100, "point_constant(%s, %lg)", meshName.c_str(), dval);
                        e->SetDefinition(edef);
                        e->SetType(Expression::ScalarMeshVar);
                        md->AddExpression(e);
                    }
                }
            }
        }
    }
}

// ****************************************************************************
//  Method: avtCGNSFileFormat::PopulateDatabaseMetaData
//
//  Purpose:
//      This database meta-data object is like a table of contents for the
//      file.  By populating it, you are telling the rest of VisIt what
//      information it can request from you.
//
//  Programmer: Brad Whitlock
//  Creation:   Tue Aug 30 16:08:44 PST 2005
//
//  Modifications:
//   Maxim Loginov, Tue Mar  4 12:28:12 NOVT 2008
//   Some constants from ReferenceState_t should be available as array mesh
//   variables.
//
//   Brad Whitlock, Wed Apr 16 10:07:16 PDT 2008
//   Totally rewrote to support reading data from multiple bases. It's more
//   modular too.
//
//   Mark C. Miller, Wed Apr 22 13:48:13 PDT 2009
//   Changed interface to DebugStream to obtain current debug level.
//
//   Mark C. Miller, Mon Sep 21 14:17:47 PDT 2009
//   Adding missing calls to actually set the times/cycles in the metadata.
// ****************************************************************************

void
avtCGNSFileFormat::PopulateDatabaseMetaData(avtDatabaseMetaData *md,
    int timeState)
{
    const char *mName = "avtCGNSFileFormat::PopulateDatabaseMetaData: ";

    // Read the times if we have not read them yet.
    ReadTimes();
    md->SetTimesAreAccurate(cgnsTimesAccurate);
    if (cgnsTimesAccurate)
        md->SetTimes(times);
    md->SetCyclesAreAccurate(cgnsCyclesAccurate);
    if (cgnsCyclesAccurate)
        md->SetCycles(cycles);

    // Get the title
    char *refstate = 0;
    if(cg_goto(GetFileHandle(), 1, "end") == CG_OK)
    {
        if(cg_state_read(&refstate) == CG_OK)
        {
            md->SetDatabaseComment(refstate);
            debug4 << mName << "Reference string = " << refstate << endl;
            cg_free(refstate);
        }
        else
            debug4 << mName << cg_get_error() << endl;
    }
    else
        debug4 << mName << cg_get_error() << endl;

    // Read the number of bases
    int nbases = 0;
    if(cg_nbases(GetFileHandle(), &nbases) != CG_OK)
    {
        debug4 << cg_get_error() << endl;
        EXCEPTION1(InvalidFilesException, cgnsFileName);
    }
    debug4 << mName << "The file contains " << nbases << " bases." << endl;

    // Read the variables for each base.
    debug4 << "====================== READING FILE ======================" << endl;
    BaseInformationVector baseInfo;
    for(int base = 1; base < nbases+1; ++base)
    {
        BaseInformation info;
        if(GetVariablesForBase(base, info))
        {
            baseInfo.push_back(info);
            BaseNameToIndices[info.name] = base;
            debug4 << mName << "Associating name \"" << info.name.c_str()
                   << "\" with base " << base << endl;
        }
    }
    // Print the information that we read from the file.
    debug4 << "==================== BASE INFORMATION ====================" << endl;
    for(size_t bi = 0; bi < baseInfo.size(); ++bi)
    {
        if(DebugStream::Level4())
            PrintBaseInformation(DebugStream::Stream4(), baseInfo[bi]);
    }

    bool someInvalidCenterings = false;

    // Now that we have variables for each base, let's determine the
    // meshes that we need to create for each base. Let's use the base name
    // as the mesh name if there is more than one zone in a base. If there's
    debug4 << "=================== POPULATE VARIABLES ===================" << endl;
    for(size_t bi = 0; bi < baseInfo.size(); ++bi)
    {
        std::string baseName(baseInfo[bi].name);
        baseName = MakeSafeVariableName(baseName);
        VisItNameToCGNSName[baseName] = baseInfo[bi].name;

        //
        // STEP 1: Come up with a mesh name.
        //
        bool useBaseNameForMesh = baseInfo.size() > 1;
        bool domainResolution = baseInfo[bi].zoneNames.size() > 1;
        std::string meshName;
        if(useBaseNameForMesh || domainResolution)
            meshName = baseName;
        else
            meshName = baseInfo[bi].zoneNames[0];
        meshName = MakeSafeVariableName(meshName);
        debug4 << mName << "Step 1: meshName = " << meshName.c_str() << endl;

        //
        // STEP 2: Determine how many meshes are required based on the
        //         unique lists of domains that we have used in the
        //         variables.
        //
        std::map<intVector, std::string> meshDef;
        intVector allDomains;
        for(size_t i = 0; i < baseInfo[bi].zoneNames.size(); ++i)
            allDomains.push_back(i+1);
        meshDef[allDomains] = meshName;
        debug4 << mName << "Step 2: Need mesh " << meshName.c_str() << endl;
        int meshCount = 0;
        for(StringVarInfoMap::const_iterator it = baseInfo[bi].vars.begin();
            it !=  baseInfo[bi].vars.end(); ++it)
        {
            std::map<intVector, std::string>::iterator meshIt =
                meshDef.find(it->second.zoneList);
            if(meshIt == meshDef.end())
            {
                ++meshCount;
                char tmp[100];
                SNPRINTF(tmp, 100, "subgrid/%s%03d",
                         baseName.c_str(), meshCount);
                meshDef[it->second.zoneList] = std::string(tmp);
                debug4 << mName << "Step 2: Need mesh " << tmp << endl;
            }
        }

        //
        // STEP 3: Create mesh metadata for each mesh that we need.
        //
        for(std::map<intVector, std::string>::const_iterator it = meshDef.begin();
            it != meshDef.end(); ++it)
        {
            bool validVariable = true;
            avtMeshType mt = AVT_UNKNOWN_MESH;
            if(baseInfo[bi].meshType == 0)
                 mt = AVT_CURVILINEAR_MESH;
            else if(baseInfo[bi].meshType == 1)
                 mt = AVT_UNSTRUCTURED_MESH;
            else
                validVariable = false;

            avtMeshMetaData *mmd = new avtMeshMetaData(it->second,
                1, 1, 1, 0, baseInfo[bi].physicalDim, baseInfo[bi].cellDim, mt);

            stringVector domainNames;
            for(size_t di = 0; di < it->first.size(); ++di)
            {
                int idx = it->first[di] - 1;
                domainNames.push_back(baseInfo[bi].zoneNames[idx]);
            }
            mmd->blockNames = domainNames;
            mmd->numBlocks = domainNames.size();
            mmd->blockOrigin = 1;
            mmd->groupOrigin = 1;
            mmd->cellOrigin = 1;
            mmd->blockPieceName = "zone";
            mmd->blockTitle = "zones";
            mmd->validVariable = validVariable;
            // Get the mesh coordinate units...
            md->Add(mmd);

            // Remember the list of zones that make up the mesh so we can use it
            // later in GetMesh.
            BaseAndZoneList bzl;
            bzl.base = bi+1;
            bzl.zones = it->first;
            MeshDomainMapping[it->second] = bzl;

            // Print the entry we just created in MeshDomainMapping
            debug4 << mName << "Step 3: Creating mesh " << it->second.c_str() << " for base "
                   << bzl.base << " for zones [";
            for(size_t zi = 0; zi < it->first.size(); ++zi)
            {
                debug4 << it->first[zi];
                if(zi <  it->first.size()-1)
                    debug4 << ", ";
            }
            debug4 << "]" << endl;
        }

        //
        // STEP 4: Create scalar metadata for each variable in the current base.
        //
        bool haveVelocity[3] = {false, false, false};
        bool haveMomentum[3] = {false, false, false};
        for(StringVarInfoMap::const_iterator it = baseInfo[bi].vars.begin();
            it !=  baseInfo[bi].vars.end(); ++it)
        {
            std::string fieldName(MakeSafeVariableName(it->first));
            if(fieldName != it->first)
                VisItNameToCGNSName[fieldName] = it->first;

            // See if we have Velocity and Momentum components.
            haveVelocity[0] |= (fieldName == "VelocityX");
            haveVelocity[1] |= (fieldName == "VelocityY");
            haveVelocity[2] |= (fieldName == "VelocityZ");
            haveMomentum[0] |= (fieldName == "MomentumX");
            haveMomentum[1] |= (fieldName == "MomentumY");
            haveMomentum[2] |= (fieldName == "MomentumZ");

            // If there is more than 1 base, prepend the base name to the
            // field name to create the variable name.
            if(baseInfo.size() > 1)
                fieldName = baseName + "/" + fieldName;

            // Determine the centering
            avtCentering centering;
            bool validVariable = true;
            if(it->second.badCentering > 0)
            {
                centering = AVT_ZONECENT;
                validVariable = false;
                someInvalidCenterings = true;
            }
            else if(it->second.cellCentering > 0)
                centering = AVT_ZONECENT; // Force to zonecent if there is mixed centering
            else
                centering = AVT_NODECENT;

            // Get the name of the mesh to use for this variable.
            std::string varMesh(meshDef[it->second.zoneList]);

            // Create the scalar metadata.
            avtScalarMetaData *smd = new avtScalarMetaData(fieldName,
                        varMesh, centering);
            smd->validVariable = validVariable;
            smd->hasUnits = it->second.hasUnits;
            smd->units = it->second.units;
            md->Add(smd);

            debug4 << mName << "Step 4: Adding scalar " << fieldName.c_str()
                   << " on mesh " << varMesh.c_str() << endl;
        }

        //
        // STEP 5: Create Velocity and Momentum vectors if present.
        //
        AddVectorExpressions(md, haveVelocity, haveMomentum, baseInfo.size(),
            baseName);

        //
        // STEP 6: Create expressions for reference state variables.
        //
        AddReferenceStateExpressions(md, bi+1, baseInfo.size(),
            baseName, meshName);
    }

    // If some variables had unsupported centerings then issue a warning.
    if(someInvalidCenterings)
    {
        avtCallback::IssueWarning("Some variables have been disabled because "
            "their grid locations (variable centerings) are not supported by "
            "VisIt. VisIt currently supports node and cell centered variables.");
    }

    // Indicate that we've initialized maps.
    initializedMaps = true;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::InitializeMaps
//
// Purpose:
//   Populate a dummy metadata with side-effect of initializing variable maps
//   that we need to read data.
//
// Arguments:
//   timeState : The time state.
//
// Returns:
//
// Note:       We call this method from GetMesh, GetVar so we can group files
//             since PopulateDatabaseMetaData gets skipped for grouped files.
//
// Programmer: Brad Whitlock
// Creation:   Thu Oct 13 11:11:11 PDT 2011
//
// Modifications:
//
// ****************************************************************************

void
avtCGNSFileFormat::InitializeMaps(int timeState)
{
    if(!initializedMaps)
    {
        avtDatabaseMetaData md;
        PopulateDatabaseMetaData(&md, timeState);
    }
}

// ****************************************************************************
//  Method: avtCGNSFileFormat::GetMesh
//
//  Purpose:
//      Gets the mesh associated with this file.  The mesh is returned as a
//      derived type of vtkDataSet (ie vtkRectilinearGrid, vtkStructuredGrid,
//      vtkUnstructuredGrid, etc).
//
//  Arguments:
//      timestate   The index of the timestate.  If GetNTimesteps returned
//                  'N' time steps, this is guaranteed to be between 0 and N-1.
//      domain      The index of the domain.  If there are NDomains, this
//                  value is guaranteed to be between 0 and NDomains-1,
//                  regardless of block origin.
//      meshname    The name of the mesh of interest.  This can be ignored if
//                  there is only one mesh.
//
//  Programmer: Brad Whitlock
//  Creation:   Tue Aug 30 16:08:44 PST 2005
//
//  Modifications:
//    Brad Whitlock, Wed Apr 16 10:06:46 PDT 2008
//    Changed how we search MeshDomainMapping.
//
//    Brad Whitlock, Thu Oct 13 11:13:30 PDT 2011
//    Call InitializeMaps so we can group files.
//
// ****************************************************************************

vtkDataSet *
avtCGNSFileFormat::GetMesh(int timestate, int domain, const char *meshname)
{
    const char *mName = "avtCGNSFileFormat::GetMesh: ";
    debug4 << mName << "ts=" << timestate << ", dom=" << domain
           << ", mesh=" << meshname << endl;

    InitializeMaps(timestate);

    //
    // See if this domain is turned off by default for this mesh.
    //
    std::map<std::string, BaseAndZoneList>::const_iterator pos =
        MeshDomainMapping.find(meshname);
    if(pos == MeshDomainMapping.end())
        return 0;
    int base = pos->second.base;
    int zone = domain + 1;
    const intVector &zones = pos->second.zones;
    debug4 << mName << "Checking if zone " << zone << " is part of "
           << meshname << endl;
    debug4 << "zones = {";
    for(size_t i = 0; i < zones.size(); ++i)
        debug4 << zones[i] << ", ";
    debug4 << "}" << endl;
    if(std::find(zones.begin(), zones.end(), zone) == zones.end())
    {
        debug4 << mName << "No, the mesh does not contain zone " << zone << endl;
        return 0;
    }
    debug4 << mName << "Yes, the mesh contains zone " << zone << endl;
    debug4 << mName << "Mesh " << meshname << " exists in base " << base << endl;

    vtkDataSet *retval = 0;
    char zonename[33];
    cgsize_t zsize[9];
    memset(zonename, 0, 33);
    memset(zsize, 0, 9 * sizeof(int));

    //
    // Determine the topological and spatial dimensions.
    //
    char namebase[33];
    int cell_dim = 2, phys_dim = 2;
    if(cg_base_read(GetFileHandle(), base, namebase, &cell_dim, &phys_dim) != CG_OK)
    {
        debug4 << cg_get_error() << endl;
        EXCEPTION1(InvalidFilesException, cgnsFileName);
    }
    else
    {
        debug4 << mName << " name=" << namebase << " cell_dim=" << cell_dim
               << " phys_dim=" << phys_dim << endl;
    }

    if(cg_zone_read(GetFileHandle(), base, zone, zonename, zsize) != CG_OK)
    {
        debug4 << mName << cg_get_error() << endl;
        EXCEPTION1(InvalidVariableException, meshname);
    }
    else
    {
        // Print the zone info.
        debug4 << mName << " name=" << zonename << " size=[";
        for(int zi = 0; zi < 9; ++zi)
        {
            if(zi > 0) debug4 << ", ";
            debug4 << zsize[zi];
        }
        debug4 << "]\n";

        ZoneType_t zt = ZoneTypeNull;
        if(cg_zone_type(GetFileHandle(), base, zone, &zt) != CG_OK)
        {
            debug4 << mName << cg_get_error() << endl;
            EXCEPTION1(InvalidVariableException, meshname);
        }
        else
        {
            switch(zt)
            {
            case ZoneTypeNull:
                EXCEPTION1(InvalidVariableException,
                           "Meshes with ZoneTypeNull are not supported.");
                break;
            case ZoneTypeUserDefined:
                EXCEPTION1(InvalidVariableException,
                           "Meshes with ZoneTypeUserDefined are not supported.");
                break;
            case Structured:
                retval = GetCurvilinearMesh(timestate, base, zone, meshname, zsize, cell_dim, phys_dim);
                break;
            case Unstructured:
                retval = GetUnstructuredMesh(timestate, base, zone, meshname, zsize, cell_dim, phys_dim);
                break;
            }
        }
    }

    return retval;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::GetCoords
//
// Purpose:
//   Read the coordinates for the specified zone.
//
// Arguments:
//   base       : The base to use
//   zone       : The zone (mesh) that whose coordinates we want.
//   zsize      : Zone size information.
//   structured : Whether the mesh is structured.
//   coords     : Return array for the coordinates.
//
// Returns:    True if the coordinates were read; false otherwise.
//
// Note:
//
// Programmer: Brad Whitlock
// Creation:   Wed Aug 31 11:45:55 PDT 2005
//
// Modifications:
//   Brad Whitlock, Mon Dec 11 09:28:52 PDT 2006
//   Prevent the coordinate arrays from being too large in the structured
//   1D, 2D cases.
//
//   Maxim Loginov, Thu Feb 28 13:36:46 PST 2008
//   Bugfix for too large arrays in the structured 1D, 2D case
//
//   Brad Whitlock, Mon Jun 18 15:21:02 PDT 2012
//   Don't pass out ncoords.
//
// ****************************************************************************

bool
avtCGNSFileFormat::GetCoords(int timestate, int base, int zone, const cgsize_t *zsize,
    int cell_dim, int phys_dim, bool structured, float **coords)
{
    const char *mName = "avtCGNSFileFormat::GetCoords: ";
    bool err = false;

    // Init the coord array
    coords[0] = 0;
    coords[1] = 0;
    coords[2] = 0;

    // Iterate through the coordinates and read them in.
    int ncoords = 0;
    if(cg_ncoords(GetFileHandle(), base, zone, &ncoords) != CG_OK)
    {
        debug4 << mName << "\t\tCould not get the number of coords" << endl;
        debug4 << mName << cg_get_error() << endl;
    }
    else
    {
        debug4 << mName << "ncoords = " << ncoords << endl;
        if(ncoords > 3)
            ncoords = 3;
        err = (ncoords != phys_dim);

        unsigned int nPts = 0;
        cgsize_t rmax[3] = {1,1,1};
        if(structured)
        {
            if(cell_dim == 1)
            {
                rmax[0] = zsize[0];
            }
            else if(cell_dim == 2)
            {
                rmax[0] = zsize[0];
                rmax[1] = zsize[1];
            }
            else
            {
                rmax[0] = zsize[0];
                rmax[1] = zsize[1];
                rmax[2] = zsize[2];
            }
            nPts = rmax[0] * rmax[1] * rmax[2];
        }
        else
        {
            rmax[0] = zsize[0];
            nPts = zsize[0];
        }

        // Check the number of grids stored in zone
        int ngrids = 0;
        if(cg_ngrids(GetFileHandle(), base, zone, &ngrids) != CG_OK)
        {
          debug4 << mName << "Could not get number of grids in zone "
                 << zone << endl;
          debug4 << cg_get_error() << endl;
        }
        // If the solution is unsteady but not the mesh, timestate will change but requiredgrid
        // should remain bounded.
        int requiredgrid = (timestate < ngrids) ? (timestate + 1) : ngrids;

        char GridCoordName[33];
        cg_grid_read(GetFileHandle(), base, zone, requiredgrid, GridCoordName);

        debug4 << "Reading mesh node " << GridCoordName << endl;
        if (cg_goto(GetFileHandle(), base, "Zone_t", zone, GridCoordName, 0, "end") != CG_OK)
        {
            debug4 << cg_get_error() << endl;
        }

        int narrays=0;
        cg_narrays(&narrays);
        if(narrays < ncoords)
        {
            debug4 << "Not enough coordinates in node " << GridCoordName << endl;
            err = true;
        }
        // Every grid is read through cg_array. However, "GridCoordinates" node should always be present
        // to describe reference state according to CGNS Grid Specification.
        for(int c = 1; c <= ncoords; ++c)
        {
            char coordname[33];
            DataType_t ct;
            if(err == true) break;
            if(cg_coord_info(GetFileHandle(), base, zone, c, &ct,
                coordname) != CG_OK)
            {
                debug4 << mName << cg_get_error() << endl;
            }
            else
            {
                debug5 << mName << "Array for " << coordname
                       << " has " << nPts << " points." << endl;
                coords[c-1] = new float[nPts];
                // Read the various coordinates as float
                debug4 << mName << "Reading " << coordname
                       << " as a float array." << endl;
                if(cg_array_read_as(c, RealSingle, (void*)coords[c-1] ) != CG_OK)
                {
                    debug4 << mName << cg_get_error() << endl;
                    err = true;
                }
            }
        }

        if(err)
        {
            delete [] coords[0];
            delete [] coords[1];
            delete [] coords[2];
            coords[0] = 0;
            coords[1] = 0;
            coords[2] = 0;
        }
    }

    return !err;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::GetCurvilinearMesh
//
// Purpose:
//   Reads a curvilinear mesh from the file.
//
// Arguments:
//   base     : The CGNS base to use.
//   zone     : The CGNS zone to use (The domain number)
//   meshname : The name of the mesh to get. (unused currently)
//   zsize    : The size information associated with the zone.
//
// Returns:    A curvilinear mesh or 0 if we can't read it from the file.
//
// Note:
//
// Programmer: Brad Whitlock
// Creation:   Wed Aug 31 09:30:30 PDT 2005
//
// Modifications:
//   Brad Whitlock, Mon Dec 11 09:42:35 PDT 2006
//   Corrected support for 2D.
//
//   Mickael Philit, Mon Jun 18 15:23:47 PDT 2012
//   Work with meshes whose tdim != sdim.
//
// ****************************************************************************

vtkDataSet *
avtCGNSFileFormat::GetCurvilinearMesh(int timestate, int base, int zone, const char *meshname,
    const cgsize_t *zsize, int cell_dim, int phys_dim)
{
    vtkDataSet *retval = 0;

    // Get the coords
    float *coords[3] = {0,0,0};
    if(GetCoords(timestate, base, zone, zsize, cell_dim, phys_dim, true, coords))
    {
        // Create the curvilinear mesh.
        vtkStructuredGrid *sgrid   = vtkStructuredGrid::New();
        vtkPoints         *points  = vtkPoints::New();
        sgrid->SetPoints(points);
        points->Delete();

        // Populate the points array
        int dims[3];
        dims[0] = zsize[0];
        dims[1] = (cell_dim >= 2) ? zsize[1] : 1;
        dims[2] = (cell_dim == 3) ? zsize[2] : 1;
        sgrid->SetDimensions(dims);
        points->SetNumberOfPoints(dims[0] * dims[1] * dims[2]);
        float *pts = (float *) points->GetVoidPointer(0);
        float *xc = coords[0];
        float *yc = coords[1];
        if(phys_dim == 3)
        {
            float *zc = coords[2];
            for(int k = 0; k < dims[2]; ++k)
            {
                for(int j = 0; j < dims[1]; ++j)
                {
                    for(int i = 0; i < dims[0]; ++i)
                    {
                        *pts++ = *xc++;
                        *pts++ = *yc++;
                        *pts++ = *zc++;
                    }
                }
            }
        }
        else if(phys_dim == 2)
        {
            for(int j = 0; j < dims[1]; ++j)
            {
                for(int i = 0; i < dims[0]; ++i)
                {
                    *pts++ = *xc++;
                    *pts++ = *yc++;
                    *pts++ = 0.;
                }
            }
        }
        else if(phys_dim == 1)
        {
            for(int i = 0; i < dims[0]; ++i)
            {
                *pts++ = *xc++;
                *pts++ = 0.;
                *pts++ = 0.;
            }
        }
        retval = sgrid;

        delete [] coords[0];
        delete [] coords[1];
        delete [] coords[2];
    }
    else
    {
        EXCEPTION1(InvalidVariableException, meshname);
    }

    return retval;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::GetUnstructuredMesh
//
// Purpose:
//   Reads an unstructured mesh from the file.
//
// Arguments:
//   base     : The CGNS base to use.
//   zone     : The CGNS zone to use (The domain number)
//   meshname : The name of the mesh to get. (unused currently)
//   zsize    : The size information associated with the zone.
//
// Returns:    An unstructured mesh or 0 if we can't read it from the file.
//
// Note:
//
// Programmer: Brad Whitlock
// Creation:   Wed Aug 31 09:30:30 PDT 2005
//
// Modifications:
//   Kathleen Bonnell, Wed Feb  8 09:41:45 PST 2006
//   Don't retrieve zcoords if ncoords != 3.
//
//   Brad Whitlock, Wed Jun  4 14:34:17 PDT 2008
//   Iterate over all of the sections but skip those that set parent_flag>0
//   since they are probably boundary conditions or things we don't really
//   care about.
//
//   Jeremy Meredith, Thu Aug  7 14:14:00 EDT 2008
//   Added some missing cases for switch.
//
//   Mickael Philit, Mon Jun 18 15:25:55 PDT 2012
//   Pass in number of spatial dimensions.
//
// ****************************************************************************

vtkDataSet *
avtCGNSFileFormat::GetUnstructuredMesh(int timestate, int base, int zone, const char *meshname,
    const cgsize_t *zsize, int cell_dim, int phys_dim)
{
    const char *mName = "avtCGNSFileFormat::GetUnstructuredMesh: ";
    vtkDataSet *retval = 0;

    // Get the number of coords
    float *coords[3] = {0,0,0};
    if(GetCoords(timestate, base, zone, zsize, 0, phys_dim, false, coords))
    {
        // Read the number of sections, for the zone.
        int nsections = 0;
        if(cg_nsections(GetFileHandle(), base, zone, &nsections) != CG_OK)
        {
            debug4 << mName << cg_get_error() << endl;
            delete [] coords[0];
            delete [] coords[1];
            delete [] coords[2];
            EXCEPTION1(InvalidVariableException, meshname);
        }
        else
        {
            // Populate the points array.
            unsigned int nPts = zsize[0];
            vtkPoints *pts = vtkPoints::New();
            pts->SetNumberOfPoints(nPts);
            const float *xc = coords[0];
            const float *yc = coords[1];
            const float *zc = NULL;
            if (phys_dim == 3)
            {
                zc = coords[2];
            }
            for(unsigned int i = 0; i < nPts; ++i)
            {
                float pt[3];
                pt[0] = *xc++;
                pt[1] = *yc++;
                if (phys_dim == 3)
                    pt[2] = *zc++;
                else
                    pt[2] = 0.;
                pts->SetPoint(i, pt);
            }

            // Create an unstructured grid to contain the points.
            vtkUnstructuredGrid *ugrid = vtkUnstructuredGrid::New();
            ugrid->SetPoints(pts);
            ugrid->Allocate(zsize[1]);
            pts->Delete();
            bool higherOrderWarning = false;

            // Iterate over each of the sections.
            for(int sec = 1; sec <= nsections; ++sec)
            {
                char sectionname[33];
                ElementType_t et = ElementTypeNull;
                cgsize_t start = 1, end = 1;
                cgsize_t elementSizeInterior = 0;
                int bound = 0, parent_flag = 0;
                if(cg_section_read(GetFileHandle(), base, zone, sec, sectionname, &et,
                    &start, &end, &bound, &parent_flag) != CG_OK)
                {
                    debug4 << mName << cg_get_error() << endl;
                    continue;
                }

                if(parent_flag > 0)
                {
                    debug4 << mName << "parent_flag = " << parent_flag << endl;
                    continue;
                }
                if(cell_dim == phys_dim)
                    elementSizeInterior = (end-start+1)-bound;
                else
                    elementSizeInterior = (end-start+1);

                cgsize_t eDataSize = 0;
                if(cg_ElementDataSize(GetFileHandle(), base, zone, sec, &eDataSize) != CG_OK)
                {
                    debug4 << mName << "Could not determine ElementDataSize\n";
                    continue;
                }
                debug4 << "Element data size for sec " << sec << " is:" << eDataSize << endl;

                cgsize_t *elements = new cgsize_t[eDataSize];
                if(elements == 0)
                {
                    debug4 << mName << "Could not allocate memory for connectivity\n";
                    continue;
                }

                if(cg_elements_read(GetFileHandle(), base, zone, sec, elements, NULL)
                   != CG_OK)
                {
                    delete [] elements;
                    elements = 0;
                    debug4 << mName << cg_get_error() << endl;
                    continue;
                }

                debug4 << "section " << sec << ": elementType=";
                PrintElementType(et);
                debug4 << " start=" << start << " end=" << end << " bound=" << bound
                       << " interior elements=" << elementSizeInterior
                       << " parent_flag=" << parent_flag << endl;

                //
                // Iterate over the elements and insert them into ugrid.
                //
                vtkIdType verts[27];
                const cgsize_t *elem = elements;
                for(cgsize_t icell = 0; icell < elementSizeInterior; ++icell)
                {
                    // If we're reading mixed elements then the element type
                    // comes first.
                    ElementType_t currentType = et;
                    if(currentType == MIXED)
                    {
                        currentType = (ElementType_t)(*elem++);
#if 0
                        debug4 << "et[" << icell << "] = ";
                        PrintElementType(currentType);
                        debug4 << endl;
#endif
                    }

                    // Process the connectivity information for the cell.
                    switch(currentType)
                    {
                    case NODE:
                        verts[0] = elem[0]-1;
                        ugrid->InsertNextCell(VTK_VERTEX, 1, verts);
                        ++elem;
                        break;
                    case BAR_2:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        ugrid->InsertNextCell(VTK_LINE, 2, verts);
                        elem += 2;
                        break;
                    case BAR_3:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        ugrid->InsertNextCell(VTK_LINE, 2, verts);
                        higherOrderWarning = true;
                        elem += 3;
                        break;
                    case TRI_3:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        //debug4 << "TRI3 [" << verts[0] << ", " << verts[1] << ", "
                        //       << verts[2] << "]" << endl;
                        ugrid->InsertNextCell(VTK_TRIANGLE, 3, verts);
                        elem += 3;
                        break;
                    case TRI_6:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        ugrid->InsertNextCell(VTK_LINE, 3, verts);
                        higherOrderWarning = true;
                        elem += 6;
                        break;
                    case QUAD_4:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        ugrid->InsertNextCell(VTK_QUAD, 4, verts);
                        elem += 4;
                        break;
                    case QUAD_8:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        ugrid->InsertNextCell(VTK_QUAD, 4, verts);
                        higherOrderWarning = true;
                        elem += 8;
                        break;
                    case QUAD_9:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        ugrid->InsertNextCell(VTK_QUAD, 4, verts);
                        higherOrderWarning = true;
                        elem += 9;
                        break;
                    case TETRA_4:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        ugrid->InsertNextCell(VTK_TETRA, 4, verts);
                        elem += 4;
                        break;
                    case TETRA_10:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        ugrid->InsertNextCell(VTK_TETRA, 4, verts);
                        higherOrderWarning = true;
                        elem += 10;
                        break;
                    case PYRA_5:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        verts[4] = elem[4]-1;
                        ugrid->InsertNextCell(VTK_PYRAMID, 5, verts);
                        elem += 5;
                        break;
                    case PYRA_14:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        verts[4] = elem[4]-1;
                        ugrid->InsertNextCell(VTK_PYRAMID, 5, verts);
                        higherOrderWarning = true;
                        elem += 15;
                        break;
                    case PENTA_6:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        verts[4] = elem[4]-1;
                        verts[5] = elem[5]-1;
                        ugrid->InsertNextCell(VTK_WEDGE, 6, verts);
                        elem += 6;
                        break;
                    case PENTA_15:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        verts[4] = elem[4]-1;
                        verts[5] = elem[5]-1;
                        ugrid->InsertNextCell(VTK_WEDGE, 6, verts);
                        higherOrderWarning = true;
                        elem += 16;
                        break;
                    case PENTA_18:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        verts[4] = elem[4]-1;
                        verts[5] = elem[5]-1;
                        ugrid->InsertNextCell(VTK_WEDGE, 6, verts);
                        higherOrderWarning = true;
                        elem += 18;
                        break;
                    case HEXA_8:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        verts[4] = elem[4]-1;
                        verts[5] = elem[5]-1;
                        verts[6] = elem[6]-1;
                        verts[7] = elem[7]-1;
                        ugrid->InsertNextCell(VTK_HEXAHEDRON, 8, verts);
                        elem += 8;
                        break;
                    case HEXA_20:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        verts[4] = elem[4]-1;
                        verts[5] = elem[5]-1;
                        verts[6] = elem[6]-1;
                        verts[7] = elem[7]-1;
                        ugrid->InsertNextCell(VTK_HEXAHEDRON, 8, verts);
                        higherOrderWarning = true;
                        elem += 20;
                        break;
                    case HEXA_27:
                        verts[0] = elem[0]-1;
                        verts[1] = elem[1]-1;
                        verts[2] = elem[2]-1;
                        verts[3] = elem[3]-1;
                        verts[4] = elem[4]-1;
                        verts[5] = elem[5]-1;
                        verts[6] = elem[6]-1;
                        verts[7] = elem[7]-1;
                        ugrid->InsertNextCell(VTK_HEXAHEDRON, 8, verts);
                        higherOrderWarning = true;
                        elem += 27;
                        break;
                    case ElementTypeUserDefined:
                    case NGON_n:
                        delete [] coords[0];
                        delete [] coords[1];
                        delete [] coords[2];
                        delete [] elements;
                        elements = 0;
                        ugrid->Delete();
                        EXCEPTION1(InvalidVariableException, meshname);
                        break;
                    case ElementTypeNull:
                    case MIXED:
                    case PYRA_13:
                    case NFACE_n:
                        // What to do here?
                        break;
                    }
                }

                debug4 << mName << "Done reading cell connectivity." << endl;
                delete [] elements;
            }

            // Tell the user if we found any higher order elements.
            if(higherOrderWarning)
            {
                avtCallback::IssueWarning("VisIt found quadratic or cubic cells "
                    "in the mesh and reduced them to linear cells. Contact "
                    "visit-users@ornl.gov if you would like VisIt to natively "
                    "process higher order elements.");
            }

            retval = ugrid;
        }

        delete [] coords[0];
        delete [] coords[1];
        delete [] coords[2];
    }
    else
    {
        EXCEPTION1(InvalidVariableException, meshname);
    }

    return retval;
}

// ****************************************************************************
//  Method: avtCGNSFileFormat::GetVar
//
//  Purpose:
//      Gets a scalar variable associated with this file.  Although VTK has
//      support for many different types, the best bet is vtkFloatArray, since
//      that is supported everywhere through VisIt.
//
//  Arguments:
//      timestate  The index of the timestate.  If GetNTimesteps returned
//                 'N' time steps, this is guaranteed to be between 0 and N-1.
//      domain     The index of the domain.  If there are NDomains, this
//                 value is guaranteed to be between 0 and NDomains-1,
//                 regardless of block origin.
//      varname    The name of the variable requested.
//
//  Programmer: Brad Whitlock
//  Creation:   Tue Aug 30 16:08:44 PST 2005
//
//  Modifications:
//    Brad Whitlock, Mon Dec 11 09:33:15 PDT 2006
//    Changed interpretation of zsize array for 1D, 2D cases so we allocate
//    and read the right number of values.
//
//    Maxim Loginov, Tue Mar  4 12:28:12 NOVT 2008
//    Read proper solution in accordance with ZoneIterativeData_t node
//
//    Brad Whitlock, Wed Apr 16 11:51:12 PDT 2008
//    Adjust how the base is selected since we can read data from multiple
//    bases now.
//
//    Jeremy Meredith, Thu Aug  7 15:56:52 EDT 2008
//    Added a default case for a switch.
//
//    Brad Whitlock, Thu Oct 13 11:13:30 PDT 2011
//    Call InitializeMaps so we can group files.
//
// ****************************************************************************

vtkDataArray *
avtCGNSFileFormat::GetVar(int timestate, int domain, const char *varname)
{
    const char *mName = "avtCGNSFileFormat::GetVar: ";
    debug4 << mName << "ts=" << timestate << ", dom=" << domain
           << ", var=" << varname << endl;

    InitializeMaps(timestate);

    // Look up the base that contains the variable.
    int base = 1;
    std::string sVarName(varname);
    int slashIndex = sVarName.find("/");
    if(slashIndex != -1)
    {
        std::string baseName = sVarName.substr(0,slashIndex);
        sVarName = sVarName.substr(slashIndex+1, sVarName.size() - slashIndex);
        baseName = VisItNameToCGNSName[baseName];
        if(BaseNameToIndices.find(baseName) == BaseNameToIndices.end())
        {
            debug4 << mName << "Basename " << baseName.c_str()
                   << " not found in the BaseNameToIndices map" << endl;
        }
        else
            base = BaseNameToIndices[baseName];
        debug4 << mName << "Using base " << base << " for the variable "
               << sVarName.c_str() << endl;
    }
    // Look up the real variable name in case it's been made safe for VisIt.
    bool requireCellCenter = false;
    if(sVarName.substr(0,5) == "CELL_")
    {
        sVarName = sVarName.substr(5);
        requireCellCenter = true;
    }

    // Look up the real variable name in case it's been made safe for VisIt.
    if(VisItNameToCGNSName.find(sVarName) != VisItNameToCGNSName.end())
        sVarName = VisItNameToCGNSName[sVarName];

    vtkDataArray *retval = 0;
    int zone = domain + 1;
    char zonename[33];
    cgsize_t zsize[9];

    memset(zonename, 0, 33);
    memset(zsize, 0, 9 * sizeof(int));

    //
    // Determine the topological and spatial dimensions.
    //
    char namebase[33];
    int cell_dim = 2, phys_dim = 2;
    if(cg_base_read(GetFileHandle(), base, namebase, &cell_dim, &phys_dim) != CG_OK)
    {
        debug4 << cg_get_error() << endl;
        EXCEPTION1(InvalidFilesException, cgnsFileName);
    }
    else
    {
        debug4 << mName << " name=" << namebase << " cell_dim=" << cell_dim
               << " phys_dim=" << phys_dim << endl;
    }

    //
    // Read the zone information
    //
    if(cg_zone_read(GetFileHandle(), base, zone, zonename, zsize) != CG_OK)
    {
        debug4 << mName << cg_get_error() << endl;
        EXCEPTION1(InvalidVariableException, varname);
    }
    else
    {
        // Print the zone info.
        debug4 << mName << " name=" << zonename << " size=[";
        for(int zi = 0; zi < 9; ++zi)
        {
            if(zi > 0) debug4 << ", ";
            debug4 << zsize[zi];
        }
        debug4 << "]\n";

        // Get the zone type because we need to know how many data points to
        // allocate using the zsize array and it is used differently for
        // structured vs. unstructured.
        ZoneType_t zt = ZoneTypeNull;
        if(cg_zone_type(GetFileHandle(), base, zone, &zt) != CG_OK)
        {
            debug4 << mName << cg_get_error() << endl;
            EXCEPTION1(InvalidVariableException, varname);
        }
        else
        {
            switch(zt)
            {
            case ZoneTypeNull:
                EXCEPTION1(InvalidVariableException,
                           "ZoneTypeNull is not supported.");
                break;
            case ZoneTypeUserDefined:
                EXCEPTION1(InvalidVariableException,
                           "ZoneTypeUserDefined is not supported.");
                break;
            default:
                // fall out
                break;
            }
        }

        int nsols = 0;
        if(cg_nsols(GetFileHandle(), base, zone, &nsols) != CG_OK)
        {
            debug4 << mName << "Could not get number of solutions in zone "
                 << zone << endl;
            debug4 << cg_get_error() << endl;
            EXCEPTION1(InvalidVariableException, varname);
        }

        debug5 << mName << "found " << nsols << " solutions in zone "
               << zone << endl;

        // find the requred solution from ZoneIterativeData_t
        // TODO currently we rely on the alphabetical sorting of the
        // solutions names in the zone and in FlowSolutionPointers,
        // e.g. the number of the required solution in the
        // FlowSolutionPointers array is the same as node number of
        // the solution, which is not necessarily true
        int requiredsol = (timestate < nsols) ? timestate + 1: nsols;

        // Iterate through the solutions until we find the variable that we're
        // looking for or required solution by number.
        bool fieldNotFound = true;
        for(int sol = 1; sol <= nsols && fieldNotFound; ++sol)
        {
            if(sol < requiredsol)
                continue;

            char solname[33];
            GridLocation_t varcentering;
            if(cg_sol_info(GetFileHandle(), base, zone, sol, solname,
                &varcentering) != CG_OK)
            {
                debug4 << "Could not get solution " << sol << "'s info."
                     << endl;
                debug4 << cg_get_error() << endl;
                continue;
            }

            if((varcentering == Vertex) && requireCellCenter)
                continue;

            debug5 << mName << "solution " << sol << " in zone "
                   << zone << " taken." << endl;

            if(varcentering == Vertex || varcentering == CellCenter)
            {
                int nfields = 0;
                if(cg_nfields(GetFileHandle(), base, zone, sol, &nfields) != CG_OK)
                {
                    debug4 << "Could not get number of fields for solution "
                           << sol << endl;
                    debug4 << cg_get_error() << endl;
                    continue;
                }

                for(int f = 1; f <= nfields && fieldNotFound; ++f)
                {
                    DataType_t dt;
                    char fieldname[33];

                    if(cg_field_info(GetFileHandle(), base, zone, sol, f, &dt, fieldname) != CG_OK)
                    {
                        debug4 << mName << "Could not get number of fields for "
                               << "solution " << sol << endl;
                        debug4 << cg_get_error() << endl;
                        continue;
                    }

                    //
                    // We found a matching field. Read it into a VTK data array.
                    if(sVarName == fieldname)
                    {
                        vtkDataArray *arr = 0;
                        switch(dt)
                        {
                        case DataTypeNull:
                        case DataTypeUserDefined:
                            debug4 << "Unsupported variable type: ";
                            PrintDataType(dt);
                            debug4 << endl;
                            break;
                        case Integer:
                            arr = vtkIntArray::New();
                            break;
                        case RealSingle:
                            arr = vtkFloatArray::New();
                            break;
                        case RealDouble:
                            arr = vtkDoubleArray::New();
                            break;
                        case Character:
                            arr = vtkCharArray::New();
                            break;
                        }

                        if(arr != 0)
                        {
                            //
                            // Set up the number of tuples, etc. This code works
                            // for structured meshes but may need some alterations
                            // for unstructured meshes.
                            //
                            int nvals = 0;
                            cgsize_t rmin[3] = {1,1,1};
                            cgsize_t rmax[3] = {1,1,1};
                            if(zt == Structured)
                            {
                                if(varcentering == Vertex)
                                {
                                    if(cell_dim == 1)
                                    {
                                        rmax[0] = zsize[0];
                                    }
                                    else if(cell_dim == 2)
                                    {
                                        rmax[0] = zsize[0];
                                        rmax[1] = zsize[1];
                                    }
                                    else
                                    {
                                        rmax[0] = zsize[0];
                                        rmax[1] = zsize[1];
                                        rmax[2] = zsize[2];
                                    }
                                }
                                else
                                {
                                    if(cell_dim == 1)
                                    {
                                        rmax[0] = zsize[1];
                                    }
                                    else if(cell_dim == 2)
                                    {
                                        rmax[0] = zsize[2];
                                        rmax[1] = zsize[3];
                                    }
                                    else
                                    {
                                        rmax[0] = zsize[3];
                                        rmax[1] = zsize[4];
                                        rmax[2] = zsize[5];
                                    }
                                }
                                nvals = rmax[0] * rmax[1] * rmax[2];
                            }
                            else // Unstructured
                            {
                                if(varcentering == Vertex)
                                    nvals = zsize[0];
                                else
                                    nvals = zsize[1];
                                rmax[0] = nvals;
                            }
                            arr->SetNumberOfTuples(nvals);

                            if(cg_field_read(GetFileHandle(), base, zone, sol,
                               fieldname, dt, rmin, rmax,
                               (void*)arr->GetVoidPointer(0)) != CG_OK)
                            {
                                arr->Delete();
                                arr = 0;
                                debug4 << mName << "Could not read " << fieldname
                                       << ": " << cg_get_error() << endl;
                            }
                        }

                        retval = arr;
                        fieldNotFound = false;
                    }
                }
            }
        }

        // If we failed to read the variable, throw an exception.
        if(retval == 0)
        {
            EXCEPTION1(InvalidVariableException, varname);
        }
    }

    return retval;
}


// ****************************************************************************
//  Method: avtCGNSFileFormat::GetVectorVar
//
//  Purpose:
//      Gets a vector variable associated with this file.  Although VTK has
//      support for many different types, the best bet is vtkFloatArray, since
//      that is supported everywhere through VisIt.
//
//  Arguments:
//      timestate  The index of the timestate.  If GetNTimesteps returned
//                 'N' time steps, this is guaranteed to be between 0 and N-1.
//      domain     The index of the domain.  If there are NDomains, this
//                 value is guaranteed to be between 0 and NDomains-1,
//                 regardless of block origin.
//      varname    The name of the variable requested.
//
//  Programmer: Brad Whitlock
//  Creation:   Tue Aug 30 16:08:44 PST 2005
//
// ****************************************************************************

vtkDataArray *
avtCGNSFileFormat::GetVectorVar(int timestate, int domain, const char *varname)
{
    EXCEPTION1(InvalidVariableException, varname);
}

// ****************************************************************************
// Method: avtCGNSFileFormat::PrintVarInfo
//
// Purpose:
//   Prints variable information to a stream.
//
// Arguments:
//   out    : The stream to which we'll print.
//   var    : The var to print.
//   indent : The indentation level.
//
// Programmer: Brad Whitlock
// Creation:   Thu Apr 17 10:23:39 PDT 2008
//
// Modifications:
//
// ****************************************************************************

void
avtCGNSFileFormat::PrintVarInfo(ostream &out, const avtCGNSFileFormat::VarInfo &var, const char *indent)
{
    out << indent << "zoneList = {";
    for(size_t i = 0; i < var.zoneList.size(); ++i)
    {
        out << var.zoneList[i];
        if(i < var.zoneList.size()-1)
            out << ", ";
    }
    out << "}" << endl;
    out << indent << "cellCentering = " << var.cellCentering << endl;
    out << indent << "nodeCentering = " << var.nodeCentering << endl;
    out << indent << "badCentering = " << var.badCentering << endl;
    out << indent << "hasUnits = " << (var.hasUnits?"true":"false") << endl;
    out << indent << "units = \"" << var.units.c_str() << "\"" << endl;
}

// ****************************************************************************
// Method: avtCGNSFileFormat::PrintStringVarInfoMap
//
// Purpose:
//   Prints all variable information to a stream.
//
// Arguments:
//   out    : The stream to which we'll print.
//   vars   : The vars to print.
//   indent : The indentation level.
//
// Programmer: Brad Whitlock
// Creation:   Thu Apr 17 10:23:39 PDT 2008
//
// Modifications:
//
// ****************************************************************************


void
avtCGNSFileFormat::PrintStringVarInfoMap(ostream &out, const avtCGNSFileFormat::StringVarInfoMap &vars, const char *indent)
{
    std::string indent2(std::string(indent) + std::string(indent));
    for(StringVarInfoMap::const_iterator pos = vars.begin();
        pos != vars.end(); ++pos)
    {
        out << indent << pos->first.c_str() << " = {" << endl;
        PrintVarInfo(out, pos->second, indent2.c_str());
        out << indent << "}" << endl;
    }
}

// ****************************************************************************
// Method: avtCGNSFileFormat::PrintBaseInformation
//
// Purpose:
//   Prints base information to a stream.
//
// Arguments:
//   out      : The stream to which we'll print.
//   baseInfo : The base information that we'll print.
//
// Programmer: Brad Whitlock
// Creation:   Thu Apr 17 10:23:39 PDT 2008
//
// Modifications:
//
// ****************************************************************************

void
avtCGNSFileFormat::PrintBaseInformation(ostream &out, const avtCGNSFileFormat::BaseInformation &baseInfo)
{
    out << "name = " << baseInfo.name.c_str() << endl;
    out << "cellDim = " << baseInfo.cellDim << endl;
    out << "physicalDim = " << baseInfo.physicalDim << endl;
    out << "meshType = " << baseInfo.meshType << " 0=curv, 1=ucd, -1,-2=unsupported" << endl;
    out << "zoneNames = {";
    for(size_t i = 0; i < baseInfo.zoneNames.size(); ++i)
    {
        out << baseInfo.zoneNames[i];
        if(i < baseInfo.zoneNames.size()-1)
            out << ", ";
    }
    out << "}" << endl;
    out << "vars = {" << endl;
    PrintStringVarInfoMap(out, baseInfo.vars, "    ");
    out << "}" << endl;
}