This file is indexed.

/usr/share/ncarg/nclscripts/wrf/WRFUserARW.ncl is in libncarg-data 6.1.2-7.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"

;--------------------------------------------------------------------------------
; function wrf_user_set_xy( var:numeric, xp:numeric, yp:numeric, x1:numeric, \
;                           y1:numeric,angle:numeric ,opts )
; function wrf_user_intrp3d( var3d:numeric, z:numeric, plot_type:string, \
;                            loc_param:numeric, angle:numeric, opts:logical )
; function wrf_user_intrp2d( var2d:numeric, \
;                            loc_param:numeric, angle:numeric, opts:logical )
; function wrf_user_getvar( file_handle, variable:string, time:integer )
; function wrf_user_list_times( file_handle )
; function wrf_user_ll_to_ij( nc_file:file, longitude:numeric, latitude:numeric, \
;                             opts:logical )
; function wrf_user_ij_to_ll( nc_file:file, i:numeric, j:numeric \
;                             opts:logical )
; function wrf_contour(nc_file:file,wks[1]: graphic, data[*][*]:numeric, \
;                      opt_args[1]:logical)
; function wrf_vector(nc_file:file,wks[1]: graphic, data_u[*][*]:numeric, \
;                     data_v[*][*]:numeric, opt_args[1]:logical)
; function wrf_map_resources(in_file[1]:file,opt_args[1]:logical)   
; function wrf_map(wks[1]:graphic,in_file[1]:file,opt_args[1]:logical)   
; function wrf_map_overlays(in_file[1]:file,wks:graphic,base[1]:graphic, \
;                           plots[*]:graphic,opt_arg[1]:logical,mp_arg[1]:logical)
; function wrf_overlays(in_file[1]:file,wks:graphic, plots[*]:graphic, \
;                       opt_arg[1]:logical)
; function wrf_user_unstagger( varin:numeric, unstagDim:string )
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Thse functions are still experimental
; function wrf_wps_dom(wks[1]:graphic,mpres[1]:logical,lnres[1]:logical,txres[1]:logical)   
; function wrf_contour_ps(nc_file:file,wks[1]: graphic, data[*][*]:numeric, \
;                         opt_args[1]:logical)
; function wrf_vector_ps(nc_file:file,wks[1]: graphic, \
;                        data_u[*][*]:numeric, data_v[*][*]:numeric, \
;                        opt_args[1]:logical)
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; These functions/procedures are obsolete as of version 5.0.1 of NCL.
; Do not use them. 
; Use wrf_overlays instead of wrf_overlay
; Use wrf_map_overlays instead of wrf_map_overlay
; Use wrf_user_ll_to_ij instead of wrf_user_latlon_to_ij
;
; function wrf_map_zoom(wks[1]:graphic,in_file[1]:file,opt_args[1]:logical, \
;                       y1:integer,y2:integer,x1:integer,x2:integer)
; procedure wrf_map_overlay(wks:graphic,base[1]:graphic, \
;                           plots[*]:graphic, \
;                           opt_arg[1]:logical)
; procedure wrf_overlay(wks:graphic, plots[*]:graphic, \
;                           opt_arg[1]:logical)
; function wrf_user_latlon_to_ij( nc_file:file, latitude:numeric, 
;                                 longitude:numeric )
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; function add_white_space(str:string,maxlen:integer)
; procedure print_opts(opts_name,opts,debug)
; procedure print_header(icount:integer,debug)
;
;--------------------------------------------------------------------------------
 
;--------------------------------------------------------------------------------
undef("wrf_user_set_xy")
function wrf_user_set_xy( var:numeric, xp:numeric, yp:numeric, x1:numeric, \
                          y1:numeric, angle:numeric, opts )

;  mass coordinate version of ncl user routines

local dims,x,y,slope,intercept,distance,dx,dy,dxy,npts,xy

begin

; find intersection of line and domain boundaries

  dims = dimsizes(var)

  if (.not. opts) then        ; We have a pivot point and location and 
			      ; need to calculate the start and end points of 
			      ; the cross section

     if ((angle .gt. 315.) .or. (angle .lt. 45.) .or. \
         ((angle .gt. 135.) .and. (angle .lt. 225.)) )  then

;  x = y*slope + intercept

          slope = -(360.-angle)/45.
          if( angle .lt. 45. ) then
            slope = angle/45.
          end if
          if( angle .gt. 135.) then
            slope = (angle-180.)/45.
          end if
          intercept = xp - yp*slope

; find intersections with domain boundaries

          y0 = 0.
          x0 = y0*slope + intercept
   
          if( x0 .lt. 0.) then  ; intersect outside of left boundary
            x0 = 0.
            y0 =  (x0 - intercept)/slope
          end if
          if( x0 .gt. dims(2)-1) then  ; intersect outside of right boundary
            x0 = dims(2)-1
            y0 =  (x0 - intercept)/slope
          end if
   
          y1 = dims(1)-1.  ;  need to make sure this will be a float?
          x1 = y1*slope + intercept
   
          if( x1 .lt. 0.) then  ; intersect outside of left boundary
            x1 = 0.
            y1 =  (x1 - intercept)/slope
          end if
          if( x1 .gt. dims(2)-1) then  ; intersect outside of right boundary
            x1 = dims(2)-1
            y1 =  (x1 - intercept)/slope
          end if

     else

;  y = x*slope + intercept

          slope = (90.-angle)/45.
          if( angle .gt. 225. ) then
            slope = (270.-angle)/45.
          end if
          intercept = yp - xp*slope

; find intersections with domain boundaries

          x0 = 0.
          y0 = x0*slope + intercept
   
          if( y0 .lt. 0.) then  ; intersect outside of bottom boundary
            y0 = 0.
            x0 =  (y0 - intercept)/slope
          end if
          if( y0 .gt. dims(1)-1) then  ; intersect outside of top boundary
            y0 = dims(1)-1
            x0 =  (y0 - intercept)/slope
          end if

          x1 = dims(2)-1.  ;  need to make sure this will be a float?
          y1 = x1*slope + intercept
   
          if( y1 .lt. 0.) then  ; intersect outside of bottom boundary
            y1 = 0.
            x1 =  (y1 - intercept)/slope
          end if
          if( y1 .gt. dims(1)-1) then  ; intersect outside of top boundary
            y1 = dims(1)-1
            x1 =  (y1 - intercept)/slope
          end if
   
     end if  ; we have beginning and ending points

  end if


  if (opts) then   	; We have a specified start and end point
    x0 = xp
    y0 = yp
    if ( x1 .gt. dims(2)-1 ) then 
      x1 = dims(2)
    end if
    if ( y1 .gt. dims(1)-1 ) then 
      y1 = dims(1)
    end if
  end if

  dx = x1 - x0
  dy = y1 - y0
  distance = (dx*dx + dy*dy)^0.5
  npts = tointeger(distance)
  dxy = new(1,typeof(distance))
  dxy = distance/npts

  xy = new((/ npts, 2 /),typeof(x1))

  dx = dx/npts
  dy = dy/npts

  do i=0,npts-1
    xy(i,0) = x0 + i*dx
    xy(i,1) = y0 + i*dy
  end do

; print(xy)
  return(xy)

end

;--------------------------------------------------------------------------------
 
undef("wrf_user_intrp3d")
function wrf_user_intrp3d( var3d:numeric, z_in:numeric, \
                           plot_type:string, \
                           loc_param:numeric, angle:numeric, opts:logical )

; var3d      - 3d field to interpolate (all input fields must be unstaggered)
; z_in       - interpolate to this field (either p/z)
; plot_type  - interpolate horizontally "h", or vertically "v"
; loc_param  - level(s) for horizontal plots (eg. 500hPa ; 3000m - scalar), 
;              plane for vertical plots (2 values representing an xy point 
;              on the model domain through which the vertical plane will pass
;              OR 4 values specifying start and end values
; angle      - 0.0 for horizontal plots, and 
;              an angle for vertical plots - 90 represent a WE cross section
; opts         Used IF opts is TRUE, else use loc_param and angle to determine crosssection

begin

  if(plot_type .eq. "h" ) then   ;  horizontal cross section needed

     dimL = dimsizes(loc_param)

     dims = dimsizes(var3d)
     nd = dimsizes(dims)

     dimX = dims(nd-1)
     dimY = dims(nd-2)
     dimZ = dims(nd-3)
     dim4 = 1
     dim5 = 1
     if ( nd .eq. 4 ) then
       dim4 = dims(nd-4)
     end if
     if ( nd .eq. 5 ) then
       dim4 = dims(nd-4)
       dim5 = dims(nd-5)
     end if

     var3  = new ( (/ dim5, dim4, dimZ, dimY, dimX /) , typeof(var3d) )
     z     = new ( (/ dim5, dim4, dimZ, dimY, dimX /) , typeof(var3d) )
     var2d = new ( (/ dim5, dim4, dimL, dimY, dimX /) , typeof(var3d) )

     if ( nd .eq. 5 ) then
       var3 = var3d
          z =  z_in
     end if
     if ( nd .eq. 4 ) then
       var3(0,:,:,:,:) = var3d(:,:,:,:)
          z(0,:,:,:,:) =  z_in(:,:,:,:)
     end if
     if ( nd .eq. 3 ) then
       var3(0,0,:,:,:) = var3d(:,:,:)
          z(0,0,:,:,:) =  z_in(:,:,:)
     end if


     if ( z(0,0,dimZ-1,0,0) .lt. z(0,0,dimZ-2,0,0) ) then
       ; We must be interpolating to pressure
       ; This routine needs input field and level in hPa - lets make sure of this
       if ( max(z) .gt. 2000. ) then
         ; looks like we have Pa as input - make this hPa
         z = z * 0.01
       end if
       if ( loc_param(0) .gt. 2000. ) then
         ; looks like the input was specified in Pa - change this
         loc_param = loc_param * 0.01
       end if
     end if

     do il = 0,dimL-1
       var = wrf_interp_3d_z(var3,z,loc_param(il))
       var2d(:,:,il,:,:) = var(:,:,:,:)
     end do

     copy_VarAtts(var3d,var3)
     if(isatt(var3,"description")) then
       delete_VarAtts(var3,(/"description"/))
     end if
     if(isatt(var3,"units")) then
       delete_VarAtts(var3,(/"units"/))
     end if
     if(isatt(var3,"MemoryOrder")) then
       delete_VarAtts(var3,(/"MemoryOrder"/))
     end if
     if(isatt(var3,"_FillValue")) then
       delete_VarAtts(var3,(/"_FillValue"/))
     end if
     copy_VarAtts(var3,var2d)

     nn = nd-2
     var2d!nn = "plevs"

     if ( dimL .gt. 1 ) then
       if ( nd .eq. 5 ) then
         return( var2d )
       end if
       if ( nd .eq. 4 ) then
         return( var2d(0,:,:,:,:) )
       end if
       if ( nd .eq. 3 ) then
         return( var2d(0,0,:,:,:) )
       end if
     else
       if ( z(0,0,dimZ-1,0,0) .lt. z(0,0,dimZ-2,0,0) ) then
          var2d@PlotLevelID = loc_param + " hPa"
       else
          var2d@PlotLevelID = .001*loc_param + " km"
       end if
       if ( nd .eq. 5 ) then
         return( var2d(:,:,0,:,:) )
       end if
       if ( nd .eq. 4 ) then
         return( var2d(0,:,0,:,:) )
       end if
       if ( nd .eq. 3 ) then
         return( var2d(0,0,0,:,:) )
       end if
     end if


  end if




  if(plot_type .eq. "v" ) then   ;  vertical cross section needed

     dims = dimsizes(var3d)
     nd = dimsizes(dims)

     dimX = dims(nd-1)
     dimY = dims(nd-2)
     dimZ = dims(nd-3)

     if ( nd .eq. 4 ) then
       if ( z_in(0,dimZ-1,0,0) .lt. z_in(0,dimZ-2,0,0) ) then
         ; We must be interpolating to pressure
           ; This routine needs input field and level in hPa - lets make sure of this
         if ( max(z_in) .gt. 2000. ) then
           ; looks like we have Pa as input - make this hPa
           z_in = z_in * 0.01
         end if
       end if
       z = z_in(0,:,:,:)
     else
       if ( z_in(dimZ-1,0,0) .lt. z_in(dimZ-2,0,0) ) then
         ; We must be interpolating to pressure
           ; This routine needs input field and level in hPa - lets make sure of this
         if ( z_in(0,0,0) .gt. 2000. ) then
           ; looks like we have Pa as input - make this hPa
           z_in = z_in * 0.01
         end if
       end if
       z = z_in
     end if

       
; set vertical cross section
     if (opts) then
       xy = wrf_user_set_xy( z, loc_param(0)-1, loc_param(2)-1, \    ; the -1 is for NCL dimensions
                                loc_param(1)-1, loc_param(3)-1, \
                                angle, opts )
     else
       xy = wrf_user_set_xy( z, loc_param(0), loc_param(1), \
                                0.0, 0.0, angle, opts )
     end if
     xp = dimsizes(xy)
  
  
; first we interp z
     var2dz   = wrf_interp_2d_xy( z, xy)

;  interp to constant z grid
     if(var2dz(0,0) .gt. var2dz(1,0) ) then  ; monotonically decreasing coordinate
        z_max = floor(max(z)/10)*10     ; bottom value
        z_min = ceil(min(z)/10)*10      ; top value
        dz = 10
        nlevels = tointeger( (z_max-z_min)/dz)
        z_var2d = new( (/nlevels/), typeof(z))
        z_var2d(0) = z_max
        dz = -dz
     else
        z_max = max(z)
        z_min = 0.
        dz = 0.01 * z_max
        nlevels = tointeger( z_max/dz )
        z_var2d = new( (/nlevels/), typeof(z))
        z_var2d(0) = z_min
     end if
  
     do i=1, nlevels-1
        z_var2d(i) = z_var2d(0)+i*dz
     end do
  

; interp the variable
     if ( dimsizes(dims) .eq. 4 ) then
       var2d = new( (/dims(0), nlevels, xp(0)/), typeof(var2dz))
       do it = 0,dims(0)-1
         var2dtmp = wrf_interp_2d_xy( var3d(it,:,:,:), xy)
         do i=0,xp(0)-1
            var2d(it,:,i) = wrf_interp_1d( var2dtmp(:,i), var2dz(:,i), z_var2d)
         end do
       end do
       var2d!0 = var3d!0
       var2d!1 = "Vertical"
       var2d!2 = "Horizontal"
     else
       var2d = new( (/nlevels, xp(0)/), typeof(var2dz))
       var2dtmp = wrf_interp_2d_xy( var3d, xy)
       do i=0,xp(0)-1
          var2d(:,i) = wrf_interp_1d( var2dtmp(:,i), var2dz(:,i), z_var2d)
       end do
       var2d!0 = "Vertical"
       var2d!1 = "Horizontal"
     end if



     st_x = tointeger(xy(0,0)) + 1
     st_y = tointeger(xy(0,1)) + 1
     ed_x = tointeger(xy(xp(0)-1,0)) + 1
     ed_y = tointeger(xy(xp(0)-1,1)) + 1
     if (opts) then
       var2d@Orientation = "Cross-Section: (" + \
                            st_x + "," + st_y + ") to (" + \
                            ed_x + "," + ed_y + ")"
     else
       var2d@Orientation = "Cross-Section: (" + \
                            st_x + "," + st_y + ") to (" + \
                            ed_x + "," + ed_y + ") ; center=(" + \
                            loc_param(0) + "," + loc_param(1) + \
                            ") ; angle=" + angle
     end if

     return(var2d)
  end if



end

;--------------------------------------------------------------------------------
 
undef("wrf_user_intrp2d")
function wrf_user_intrp2d( var2d:numeric, \
                           loc_param:numeric, angle:numeric, opts:logical )

; var2d      - 2d field to interpolate 
; loc_param  - plane for vertical plots (2 values representing an xy point 
;              on the model domain through which the vertical plane will pass
;              OR 4 values specifying start and end values
; angle      - 0.0 for horizontal plots, and 
;              an angle for vertical plots - 90 represent a WE cross section
; opts         Used IF opts is TRUE, else use loc_param and angle to determine crosssection

begin

     dims = dimsizes(var2d)
     nd = dimsizes(dims)
     dimX = dims(nd-1)
     dimY = dims(nd-2)
     dimT = 1
     if ( nd .eq. 3 ) then
       dimT = dims(nd-3)
     end if
     var2dtmp = new( (/ 1, dimY, dimX /), typeof(var2d) )
     

; set vertical cross section
     if ( nd .eq. 3 ) then
       var2dtmp(0,:,:) = var2d(0,:,:)
     else
       var2dtmp(0,:,:) = var2d(:,:)
     end if
     if (opts) then
       xy = wrf_user_set_xy( var2dtmp, \
                             loc_param(0)-1, loc_param(2)-1, \    ; the -1 is for NCL dimensions
                             loc_param(1)-1, loc_param(3)-1, \
                             angle, opts )
     else
       xy = wrf_user_set_xy( var2dtmp, \
                             loc_param(0), loc_param(1), \
                             0.0, 0.0, angle, opts )
     end if
     xp = dimsizes(xy)

     var2dout = new( (/ dimT, xp(0) /), typeof(var2d) )

     var1dtmp = wrf_interp_2d_xy( var2dtmp, xy )
     var2dout(0,:) = var1dtmp(0,:)
     if ( dimT .eq. 1 ) then
       var2dout!1 = "Horizontal"
       return ( var2dout(0,:) )
     end if

     do it = 1,dimT-1
       var2dtmp(0,:,:) = var2d(it,:,:)
       var1dtmp = wrf_interp_2d_xy( var2dtmp, xy )
       var2dout(it,:) = var1dtmp(0,:)
     end do
     var2dout!0 = "Time"
     var2dout!1 = "Horizontal"
     return(var2dout)

end

;--------------------------------------------------------------------------------

undef("wrf_user_unstagger")
function wrf_user_unstagger( varin:numeric, unstagDim:string )

begin

  dims = dimsizes(varin)
  nd = dimsizes(dims)

  if ( unstagDim .eq. "X" .or. unstagDim .eq. "U" ) then
    dimU = dims(nd-1)
    if ( nd .eq. 5 ) then
      varout = 0.5*(varin(:,:,:,:,:dimU-2) + varin(:,:,:,:,1:dimU-1))
    end if
    if ( nd .eq. 4 ) then
      varout = 0.5*(varin(:,:,:,:dimU-2) + varin(:,:,:,1:dimU-1))
    end if
    if ( nd .eq. 3 ) then
      varout = 0.5*(varin(:,:,:dimU-2) + varin(:,:,1:dimU-1))
    end if
    if ( nd .eq. 2 ) then
      varout = 0.5*(varin(:,:dimU-2) + varin(:,1:dimU-1))
    end if
    do i = 0,nd-2
      varout!i = varin!i
    end do
    i = nd-1
    varout!i = "west_east"
    copy_VarAtts(varin,varout)
    varout@coordinates = "XLONG XLAT"
    varout@stagger = " "
  end if

  if ( unstagDim .eq. "Y" .or. unstagDim .eq. "V" ) then
    dimV = dims(nd-2)
    if ( nd .eq. 5 ) then
      varout = 0.5*(varin(:,:,:,:dimV-2,:)+varin(:,:,:,1:dimV-1,:))
    end if
    if ( nd .eq. 4 ) then
      varout = 0.5*(varin(:,:,:dimV-2,:)+varin(:,:,1:dimV-1,:))
    end if
    if ( nd .eq. 3 ) then
      varout = 0.5*(varin(:,:dimV-2,:)+varin(:,1:dimV-1,:))
    end if
    if ( nd .eq. 2 ) then
      varout = 0.5*(varin(:dimV-2,:)+varin(1:dimV-1,:))
    end if
    do i = 0,nd-1
      varout!i = varin!i
    end do
    i = nd-2
    varout!i = "south_north"
    copy_VarAtts(varin,varout)
    varout@coordinates = "XLONG XLAT"
    varout@stagger = " "
  end if

  if ( unstagDim .eq. "Z" ) then
    dimW = dims(nd-3)
    if ( nd .eq. 5 ) then
      varout = 0.5*(varin(:,:,0:dimW-2,:,:)+varin(:,:,1:dimW-1,:,:))
    end if
    if ( nd .eq. 4 ) then
      varout = 0.5*(varin(:,0:dimW-2,:,:)+varin(:,1:dimW-1,:,:))
    end if
    if ( nd .eq. 3 ) then
      varout = 0.5*(varin(0:dimW-2,:,:)+varin(1:dimW-1,:,:))
    end if
    do i = 0,nd-1
      varout!i = varin!i
    end do
    i = nd-3
    varout!i = "bottom_top" 
    copy_VarAtts(varin,varout)
    varout@coordinates = "XLONG XLAT"
    varout@stagger = " "
  end if

  if( any( unstagDim .eq. (/"X","U","Y","V","Z"/) ) ) then
    return(varout) 
  else
    print("NOTE: No unstaggering required, as the input field is already on mass points.")
    return(varin)
  end if

end

;--------------------------------------------------------------------------------
; This function was modified in May 2011 to allow a list of files.
;
undef("wrf_user_getvar")
function wrf_user_getvar( file_handle, varin[*]:string, time_in:integer )
local variable, time, var, u, v, u_in, v_in, pii, radians_per_degree, \
dims, nd, latitude, longitude, rank
begin

;---As of NCL V6.0.0, wrf_user_getvar can now handle a file or a list of files.
  if(typeof(file_handle).eq."file") then
    ISFILE = True
    nc_file = file_handle
  else if(typeof(file_handle).eq."list") then
    ISFILE = False
    nc_file = file_handle[0]
  else
    print("wrf_user_getvar: error: the first argument must be a file or a list of files opened with addfile or addfiles")
    return
  end if
  end if

  variable = varin(0)
  time = time_in(0)

  if( (variable .eq. "uvmet") .or. (variable .eq. "uvmet10") ) then
       ;; Calculate winds rotated to earth coord. 

       pii = 3.14159265
       radians_per_degree = pii/180.

       if( (variable .eq. "uvmet") )  then
         getU = "U" 
         getV = "V" 
         if(.not. isfilevar(nc_file,"U")) then
           if(isfilevar(nc_file,"UU")) then
             getU = "UU"
             getV = "VV"
           end if
         end if
         if ( time .eq. -1 ) then
           if(ISFILE) then
             u_in = nc_file->$getU$
             v_in = nc_file->$getV$
           else
             u_in = file_handle[:]->$getU$
             v_in = file_handle[:]->$getV$
           end if
           u = wrf_user_unstagger(u_in,u_in@stagger)
           v = wrf_user_unstagger(v_in,v_in@stagger)
       else
           if(ISFILE) then
             u_in   = nc_file->$getU$(time_in,:,:,:)
             v_in   = nc_file->$getV$(time_in,:,:,:)
           else
             u_in   = file_handle[:]->$getU$(time_in,:,:,:)
             v_in   = file_handle[:]->$getV$(time_in,:,:,:)
           end if
           u = wrf_user_unstagger(u_in,u_in@stagger)
           v = wrf_user_unstagger(v_in,v_in@stagger)
         end if
       end if  

       if( (variable .eq. "uvmet10") )  then
         if(isfilevar(nc_file,"U10")) then
           if ( time .eq. -1 ) then
             if(ISFILE) then
               u_in   = nc_file->U10
               v_in   = nc_file->V10
             else
               u_in   = file_handle[:]->U10
               v_in   = file_handle[:]->V10
             end if
             u = wrf_user_unstagger(u_in,u_in@stagger)
             v = wrf_user_unstagger(v_in,v_in@stagger)
           else
             if(ISFILE) then
               u_in  = nc_file->U10(time_in,:,:)
               v_in  = nc_file->V10(time_in,:,:)
             else
               u_in  = file_handle[:]->U10(time_in,:,:)
               v_in  = file_handle[:]->V10(time_in,:,:)
             end if
             u = wrf_user_unstagger(u_in,u_in@stagger)
             v = wrf_user_unstagger(v_in,v_in@stagger)
           end if
         else  ; may be a met file, so get lowest level of UU and VV
           if(isfilevar(nc_file,"UU")) then
             print("wrf_user_getvar: Assume this is a met_em file - getting lowest level from UU and VV fields")
             if ( time .eq. -1 ) then
               if(ISFILE) then
                 u_in  = nc_file->UU(:,0,:,:)
                 v_in  = nc_file->VV(:,0,:,:)
               else
                 u_in  = file_handle[:]->UU(:,0,:,:)
                 v_in  = file_handle[:]->VV(:,0,:,:)
               end if
               u = wrf_user_unstagger(u_in,u_in@stagger)
               v = wrf_user_unstagger(v_in,v_in@stagger)
             else
               if(ISFILE) then
                 u_in  = nc_file->UU(time_in,0,:,:)
                 v_in  = nc_file->VV(time_in,0,:,:)
               else
                 u_in  = file_handle[:]->UU(time_in,0,:,:)
                 v_in  = file_handle[:]->VV(time_in,0,:,:)
               end if
               u = wrf_user_unstagger(u_in,u_in@stagger)
               v = wrf_user_unstagger(v_in,v_in@stagger)
             end if
           end if
         end if  
       end if  


       map_projection = nc_file@MAP_PROJ


       if( any(map_projection.eq.(/0,3,6/)) ) then  ; no rotation needed
         dims = dimsizes(u)
         nd = dimsizes(dims)
         if ( nd .eq. 5 ) then
           uvmet = new( (/ 2, dims(0), dims(1), dims(2), dims(3), dims(4) /), typeof(u))
           uvmet(0,:,:,:,:,:) = u(:,:,:,:,:) 
           uvmet(1,:,:,:,:,:) = v(:,:,:,:,:)
         end if
         if ( nd .eq. 4 ) then
           uvmet = new( (/ 2, dims(0), dims(1), dims(2), dims(3) /), typeof(u))
           uvmet(0,:,:,:,:) = u(:,:,:,:) 
           uvmet(1,:,:,:,:) = v(:,:,:,:)
         end if
         if ( nd .eq. 3 ) then
           uvmet = new( (/ 2, dims(0), dims(1), dims(2) /), typeof(u))
           uvmet(0,:,:,:) = u(:,:,:) 
           uvmet(1,:,:,:) = v(:,:,:)
         end if
         if ( nd .eq. 2 ) then
           uvmet = new( (/ 2, dims(0), dims(1) /), typeof(u))
           uvmet(0,:,:) = u(:,:) 
           uvmet(1,:,:) = v(:,:)
         end if
         delete_VarAtts(u,(/"description","units"/))
         copy_VarAtts(u,uvmet)
         uvmet@description = " u,v met velocity"
         uvmet!0 = "u_v"
       end if


       if( any(map_projection.eq.(/1,2/)) ) then  ; no rotation needed
         cen_lat  = nc_file@CEN_LAT
         if(isatt(nc_file,"STAND_LON")) then
             cen_long = nc_file@STAND_LON
         else
             cen_long = nc_file@CEN_LON
         end if
         true_lat1 = nc_file@TRUELAT1
         true_lat2 = nc_file@TRUELAT2
  
         getLAT = "XLAT" 
         getLON = "XLONG" 
         if(.not. isfilevar(nc_file,"XLAT")) then
           if(isfilevar(nc_file,"XLAT_M")) then
             getLAT = "XLAT_M"
             getLON = "XLONG_M"
           end if
         end if
         if ( time .eq. -1 ) then
           if(ISFILE) then
             latitude  = nc_file->$getLAT$
             longitude = nc_file->$getLON$
           else
             latitude  = file_handle[:]->$getLAT$
             longitude = file_handle[:]->$getLON$
           end if
         else
           if(ISFILE) then
             latitude  = nc_file->$getLAT$(time_in,:,:)
             longitude = nc_file->$getLON$(time_in,:,:)
           else
             latitude  = file_handle[:]->$getLAT$(time_in,:,:)
             longitude = file_handle[:]->$getLON$(time_in,:,:)
           end if
         end if

         cone = 1.
         if( map_projection .eq. 1) then    ; Lambert Conformal mapping
           if( (fabs(true_lat1 - true_lat2) .gt. 0.1) .and.  \
               (fabs(true_lat2 - 90. )      .gt. 0.1)       ) then
               cone = log(cos(true_lat1*radians_per_degree)) \ 
                     -log(cos(true_lat2*radians_per_degree)) 
               cone = cone/( log(tan(( 45. -fabs(true_lat1/2.))*radians_per_degree)) - \ 
                             log(tan((45. -fabs(true_lat2/2.))*radians_per_degree)) ) 
           else
               cone = sin(fabs(true_lat1)*radians_per_degree)
           end if
         end if
         if(map_projection .eq. 2) then      ; polar stereographic
           cone = 1.
         end if
         if(map_projection .eq. 3) then      ; Mercator
           cone = 0.
         end if

         uvmet = wrf_uvmet( u, v, latitude, longitude, cen_long, cone )
         delete_VarAtts(u,(/"description","units"/))
         copy_VarAtts(u,uvmet)

       end if  
       
       if( (variable .eq. "uvmet10") )  then
         uvmet@description = " u10,v10 met velocity"
       end if
       return(uvmet)

  end if



  if( variable .eq. "ua" ) then
       ;  U interpolated to mass points
       getTHIS = "U" 
       if(.not. isfilevar(nc_file,"U")) then
         if(isfilevar(nc_file,"UU")) then
           getTHIS = "UU"
         end if
       end if
       if ( time .eq. -1 ) then
         if(ISFILE) then
           var = nc_file->$getTHIS$
         else
           var = file_handle[:]->$getTHIS$
         end if
       else
         if(ISFILE) then
           var = nc_file->$getTHIS$(time_in,:,:,:)
         else
           var = file_handle[:]->$getTHIS$(time_in,:,:,:)
         end if
       end if

       ua = wrf_user_unstagger(var,var@stagger)

       return(ua)
  end if



  if( variable .eq. "va" ) then
       ; V interpolated to mass points
       getTHIS = "V" 
       if(.not. isfilevar(nc_file,"V")) then
         if(isfilevar(nc_file,"VV")) then
           getTHIS = "VV"
         end if
       end if
       if ( time .eq. -1 ) then
         if(ISFILE) then
           var = nc_file->$getTHIS$
         else
           var = file_handle[:]->$getTHIS$
         end if
       else
         if(ISFILE) then
           var = nc_file->$getTHIS$(time_in,:,:,:)
         else
           var = file_handle[:]->$getTHIS$(time_in,:,:,:)
         end if
       end if

       va = wrf_user_unstagger(var,var@stagger)

       return(va)
  end if



  if( variable .eq. "wa" ) then
       ; W interpolated to mass points
       if ( time .eq. -1 ) then
         if(ISFILE) then
           var = nc_file->W
         else
           var = file_handle[:]->W
         end if
       else
         if(ISFILE) then
           var = nc_file->W(time_in,:,:,:)
         else
           var = file_handle[:]->W(time_in,:,:,:)
         end if
       end if

       wa = wrf_user_unstagger(var,var@stagger)

       return(wa)
  end if



  if( any( variable .eq. (/"p","pres","pressure"/) ) ) then
       ; Full model pressure [=base pressure (PB) + pertubation pressure (P)]
       if(isfilevar(nc_file,"P")) then
         if ( time .eq. -1 ) then
           if(ISFILE) then
             var = nc_file->P
             PB  = nc_file->PB
           else
             var = file_handle[:]->P
             PB  = file_handle[:]->PB
           end if
         else
           if(ISFILE) then
             var = nc_file->P(time_in,:,:,:)
             PB  = nc_file->PB(time_in,:,:,:)
           else
             var = file_handle[:]->P(time_in,:,:,:)
             PB  = file_handle[:]->PB(time_in,:,:,:)
           end if
         end if
         var = var + PB
       else
         ;; may be a met_em file - see if we can get PRES
         if(isfilevar(nc_file,"PRES")) then
           if ( time .eq. -1 ) then
             if(ISFILE) then
               var = nc_file->PRES
             else
               var = file_handle[:]->PRES
             end if
           else
             if(ISFILE) then
               var = nc_file->PRES(time_in,:,:,:)
             else
               var = file_handle[:]->PRES(time_in,:,:,:)
             end if
           end if
         end if
       end if
       var@description = "Pressure"
       if( variable .eq. "pressure" ) then
         var = var * 0.01
         var@units = "hPa"
       end if
       return(var)
  end if



  if( any( variable .eq. (/"geopt","geopotential","z","height"/) ) ) then
       ; Height [=full geopotentail height / 9.81]
       if(isfilevar(nc_file,"PH")) then
         if ( time .eq. -1 ) then
           if(ISFILE) then
             var = nc_file->PH
             PHB = nc_file->PHB
           else
             var = file_handle[:]->PH
             PHB = file_handle[:]->PHB
           end if
         else
           if(ISFILE) then
             var = nc_file->PH(time,:,:,:)
             PHB = nc_file->PHB(time,:,:,:)
           else
             var = file_handle[:]->PH(time,:,:,:)
             PHB = file_handle[:]->PHB(time,:,:,:)
           end if
         end if

         var = var + PHB
         z = wrf_user_unstagger(var,var@stagger)
         z@description = "Geopotential"

       else
         ;; may be a met_em file - see if we can get GHT - data in met_em file is Height in M
         if(isfilevar(nc_file,"GHT")) then
           if ( time .eq. -1 ) then
             if(ISFILE) then
               z = nc_file->GHT
             else
               z = file_handle[:]->GHT
             end if
           else
             if(ISFILE) then
               z = nc_file->GHT(time,:,:,:)
             else
               z = file_handle[:]->GHT(time,:,:,:)
             end if
           end if
           z = z * 9.81
           z@description = "Geopotential"
           z@units       = "m2 s-2"
         end if
       end if

       if( any( variable .eq. (/"z","height"/) ) ) then
         z = z / 9.81
         z@description = "Height"
         z@units       = "m"
       end if
       return(z)
  end if



  if( any( variable .eq. (/"th","theta"/) ) ) then
       ; Potentail Temperature is model output T + 300K
       if ( time .eq. -1 ) then
         if(ISFILE) then
           var = nc_file->T
         else
           var = file_handle[:]->T
         end if
       else
         if(ISFILE) then
           var = nc_file->T(time_in,:,:,:)
         else
           var = file_handle[:]->T(time_in,:,:,:)
         end if
       end if  
       var = var + 300.
       var@description = "Potential Temperature (theta) "
       return(var)
  end if



  if( any( variable .eq. (/"tk","tc"/) ) ) then
       ;; function wrf_tk needs theta and pressure (Pa) on input and returns temperature in K on return
       if(isfilevar(nc_file,"T")) then
         if ( time .eq. -1 ) then
           if(ISFILE) then
             T  = nc_file->T
             P  = nc_file->P
             PB = nc_file->PB
           else
             T  = file_handle[:]->T
             P  = file_handle[:]->P
             PB = file_handle[:]->PB
           end if
         else
           if(ISFILE) then
             T  = nc_file->T(time_in,:,:,:)
             P  = nc_file->P(time_in,:,:,:)
             PB = nc_file->PB(time_in,:,:,:)
           else
             T  = file_handle[:]->T(time_in,:,:,:)
             P  = file_handle[:]->P(time_in,:,:,:)
             PB = file_handle[:]->PB(time_in,:,:,:)
           end if
         end if  
         T = T + 300.
         P = P + PB
         t = wrf_tk( P , T )
         delete_VarAtts(T,(/"description"/))
         copy_VarAtts(T,t)
       else
         ;; may be a met_em file - see if we can get TT
         if(isfilevar(nc_file,"TT")) then
           if ( time .eq. -1 ) then
             if(ISFILE) then
               t = nc_file->TT
             else
               t = file_handle[:]->TT
             end if
           else
             if(ISFILE) then
               t = nc_file->TT(time_in,:,:,:)
             else
               t = file_handle[:]->TT(time_in,:,:,:)
             end if
           end if  
         end if  
       end if  
       if( variable .eq. "tc" ) then
         t = t - 273.16
         t@units = "C"     ; Overwrite return units
       end if
       return(t)
  end if



   if( variable .eq. "eth" ) then
   ;Equivalent Potential Temperature in degrees K
       if(isfilevar(nc_file,"T")) then
         if ( time .eq. -1 ) then
           if(ISFILE) then
             T  = nc_file->T
             P  = nc_file->P
             PB = nc_file->PB
             QV = nc_file->QVAPOR
           else
             T  = file_handle[:]->T
             P  = file_handle[:]->P
             PB = file_handle[:]->PB
             QV = file_handle[:]->QVAPOR
           end if
         else
           if(ISFILE) then
             T  = nc_file->T(time_in,:,:,:)
             P  = nc_file->P(time_in,:,:,:)
             PB = nc_file->PB(time_in,:,:,:)
             QV = nc_file->QVAPOR(time_in,:,:,:)
           else
             T  = file_handle[:]->T(time_in,:,:,:)
             P  = file_handle[:]->P(time_in,:,:,:)
             PB = file_handle[:]->PB(time_in,:,:,:)
             QV = file_handle[:]->QVAPOR(time_in,:,:,:)
           end if
         end if  
         T  = T + 300.        ; potential temperature in K.
         P  = P + PB          ; full pressure in Pa.   
         tk = wrf_tk( P , T ) ; temperature in K.
         eth = wrf_eth ( QV, tk, P )
         delete_VarAtts(T,(/"description"/))
         copy_VarAtts(T,eth)
         return(eth)
       else
         print("This diagnostic only for with WRF data file and not for WPS files")
         exit
       end if  

   end if



  if( variable .eq. "td" ) then
       ;; function wrf_td needs qv and pressure (Pa) on input and returns dewpoint temperature on return
       if ( time .eq. -1 ) then
         if(ISFILE) then
           P      = nc_file->P
           PB     = nc_file->PB
           QVAPOR = nc_file->QVAPOR
         else
           P      = file_handle[:]->P
           PB     = file_handle[:]->PB
           QVAPOR = file_handle[:]->QVAPOR
         end if
       else
         if(ISFILE) then
           P      = nc_file->P(time_in,:,:,:)
           PB     = nc_file->PB(time_in,:,:,:)
           QVAPOR = nc_file->QVAPOR(time_in,:,:,:)
         else
           P      = file_handle[:]->P(time_in,:,:,:)
           PB     = file_handle[:]->PB(time_in,:,:,:)
           QVAPOR = file_handle[:]->QVAPOR(time_in,:,:,:)
         end if
       end if
       P = P + PB
       td  = wrf_td( P , QVAPOR )
       delete_VarAtts(QVAPOR,(/"description","units"/))
       copy_VarAtts(QVAPOR,td)
       return(td)
  end if



  if( variable .eq. "td2" ) then
       ;; function wrf_td needs qv and pressure (Pa) on input and returns dewpoint temperature on return
       if ( time .eq. -1 ) then
         if(ISFILE) then
           PSFC = nc_file->PSFC
           Q2   = nc_file->Q2
         else
           PSFC = file_handle[:]->PSFC
           Q2   = file_handle[:]->Q2
         end if
       else
         if(ISFILE) then
           PSFC = nc_file->PSFC(time_in,:,:) 
           Q2   = nc_file->Q2(time_in,:,:)
         else
           PSFC = file_handle[:]->PSFC(time_in,:,:) 
           Q2   = file_handle[:]->Q2(time_in,:,:)
         end if
       end if
       td = wrf_td( PSFC , Q2 )
       delete_VarAtts(Q2,(/"description","units"/))
       copy_VarAtts(Q2,td)
       td@description = "2m Dewpoint Temperature"   ; Overwrite return description
       return(td)
  end if



  if( variable .eq. "slp" ) then
       if(isfilevar(nc_file,"T")) then
         ;; first compute theta - function wrf_tk needs theta and pressure (Pa) on input
         ;; THEN compute sea level pressure, from qv, p (Pa), tk, z
         if ( time .eq. -1 ) then
           if(ISFILE) then
             T      = nc_file->T
             P      = nc_file->P
             PB     = nc_file->PB
             QVAPOR = nc_file->QVAPOR
             PH     = nc_file->PH
             PHB    = nc_file->PHB
           else
             T      = file_handle[:]->T
             P      = file_handle[:]->P
             PB     = file_handle[:]->PB
             QVAPOR = file_handle[:]->QVAPOR
             PH     = file_handle[:]->PH
             PHB    = file_handle[:]->PHB
           end if
         else
           if(ISFILE) then
             T      = nc_file->T(time_in,:,:,:)
             P      = nc_file->P(time_in,:,:,:)
             PB     = nc_file->PB(time_in,:,:,:)
             QVAPOR = nc_file->QVAPOR(time_in,:,:,:)
             PH     = nc_file->PH(time_in,:,:,:)
             PHB    = nc_file->PHB(time_in,:,:,:)
           else
             T      = file_handle[:]->T(time_in,:,:,:)
             P      = file_handle[:]->P(time_in,:,:,:)
             PB     = file_handle[:]->PB(time_in,:,:,:)
             QVAPOR = file_handle[:]->QVAPOR(time_in,:,:,:)
             PH     = file_handle[:]->PH(time_in,:,:,:)
             PHB    = file_handle[:]->PHB(time_in,:,:,:)
           end if
         end if
         T = T + 300.
         P = P + PB
         QVAPOR = QVAPOR > 0.000
         PH    = ( PH + PHB ) / 9.81
         z = wrf_user_unstagger(PH,PH@stagger)

         tk = wrf_tk( P , T )    ; calculate TK
         slp   = wrf_slp( z, tk, P, QVAPOR )  ; calculate slp
         delete_VarAtts(T,(/"description","units"/))
         copy_VarAtts(T,slp)
       else
         ;; may be a met_em file - see if we can get PMSL
         if(isfilevar(nc_file,"PMSL")) then
           if ( time .eq. -1 ) then
             if(ISFILE) then
               slp = nc_file->PMSL
             else
               slp = file_handle[:]->PMSL
             end if
           else
             if(ISFILE) then
               slp = nc_file->PMSL(time_in,:,:)
             else
               slp = file_handle[:]->PMSL(time_in,:,:)
             end if
           end if
         end if
       end if  

       return(slp)
  end if



  if( variable .eq. "rh" ) then
       if(isfilevar(nc_file,"T")) then
         ;; first compute theta - function wrf_tk needs theta and pressure (Pa) on input
         ;; THEN compute rh, using tk, p (Pa), QVAPOR
         if ( time .eq. -1 ) then
           if(ISFILE) then
             T      = nc_file->T
             P      = nc_file->P
             PB     = nc_file->PB
             QVAPOR = nc_file->QVAPOR
           else
             T      = file_handle[:]->T
             P      = file_handle[:]->P
             PB     = file_handle[:]->PB
             QVAPOR = file_handle[:]->QVAPOR
           end if
         else
           if(ISFILE) then
             T      = nc_file->T(time_in,:,:,:)
             P      = nc_file->P(time_in,:,:,:)
             PB     = nc_file->PB(time_in,:,:,:)
             QVAPOR = nc_file->QVAPOR(time_in,:,:,:)
           else
             T      = file_handle[:]->T(time_in,:,:,:)
             P      = file_handle[:]->P(time_in,:,:,:)
             PB     = file_handle[:]->PB(time_in,:,:,:)
             QVAPOR = file_handle[:]->QVAPOR(time_in,:,:,:)
           end if
         end if  
         T = T + 300.
         P  = P + PB
         QVAPOR = QVAPOR > 0.000
         tk = wrf_tk( P , T )
         rh = wrf_rh( QVAPOR, P, tk )
         delete_VarAtts(T,(/"description","units"/))
         copy_VarAtts(T,rh)
       else
         ;; may be a met_em file - see if we can get RH
         if(isfilevar(nc_file,"RH")) then
           if ( time .eq. -1 ) then
             if(ISFILE) then
               rh = nc_file->RH
             else
               rh = file_handle[:]->RH
             end if
           else
             if(ISFILE) then
               rh = nc_file->RH(time_in,:,:,:)
             else
               rh = file_handle[:]->RH(time_in,:,:,:)
             end if
           end if
         end if
       end if  
       return(rh)
  end if



  if( variable .eq. "rh2" ) then
       if(isfilevar(nc_file,"T2")) then
         ;; Compute rh2, using T2, PSFC, Q2
         if ( time .eq. -1 ) then
           if(ISFILE) then
             T2   = nc_file->T2
             PSFC = nc_file->PSFC
             Q2   = nc_file->Q2
           else
             T2   = file_handle[:]->T2
             PSFC = file_handle[:]->PSFC
             Q2   = file_handle[:]->Q2
           end if
         else
           if(ISFILE) then
             T2   = nc_file->T2(time_in,:,:)
             PSFC = nc_file->PSFC(time_in,:,:)
             Q2   = nc_file->Q2(time_in,:,:)
           else
             T2   = file_handle[:]->T2(time_in,:,:)
             PSFC = file_handle[:]->PSFC(time_in,:,:)
             Q2   = file_handle[:]->Q2(time_in,:,:)
           end if
         end if  
         Q2 = Q2 > 0.000
         rh = wrf_rh( Q2, PSFC, T2 )
         delete_VarAtts(T2,(/"description","units"/))
         copy_VarAtts(T2,rh)
         rh@description = "2m Relative Humidity"           
       else
         ;; may be a met_em file - see if we can get RH
         if(isfilevar(nc_file,"RH")) then
           print("Probably a met_em file - get lowerst level from RH field")
           if ( time .eq. -1 ) then
             if(ISFILE) then
               rh2 = nc_file->RH(:,0,:,:)
             else
               rh2 = file_handle[:]->RH(:,0,:,:)
             end if
           else
             if(ISFILE) then
               rh2 = nc_file->RH(time_in,0,:,:)
             else
               rh2 = file_handle[:]->RH(time_in,0,:,:)
             end if
           end if
         end if
       end if  
       return(rh)
  end if



  if( variable .eq. "pvo" ) then
       if ( time .eq. -1 ) then
         if(ISFILE) then
           U    = nc_file->U
           V    = nc_file->V
           T    = nc_file->T
           P    = nc_file->P
           PB   = nc_file->PB
           MSFU = nc_file->MAPFAC_U
           MSFV = nc_file->MAPFAC_V
           MSFM = nc_file->MAPFAC_M
           COR  = nc_file->F
         else
           U    = file_handle[:]->U
           V    = file_handle[:]->V
           T    = file_handle[:]->T
           P    = file_handle[:]->P
           PB   = file_handle[:]->PB
           MSFU = file_handle[:]->MAPFAC_U
           MSFV = file_handle[:]->MAPFAC_V
           MSFM = file_handle[:]->MAPFAC_M
           COR  = file_handle[:]->F
         end if
       else
         if(ISFILE) then
           U    = nc_file->U(time_in,:,:,:)
           V    = nc_file->V(time_in,:,:,:)
           T    = nc_file->T(time_in,:,:,:)
           P    = nc_file->P(time_in,:,:,:)
           PB   = nc_file->PB(time_in,:,:,:)
           MSFU = nc_file->MAPFAC_U(time_in,:,:)
           MSFV = nc_file->MAPFAC_V(time_in,:,:)
           MSFM = nc_file->MAPFAC_M(time_in,:,:)
           COR  = nc_file->F(time_in,:,:)
         else
           U    = file_handle[:]->U(time_in,:,:,:)
           V    = file_handle[:]->V(time_in,:,:,:)
           T    = file_handle[:]->T(time_in,:,:,:)
           P    = file_handle[:]->P(time_in,:,:,:)
           PB   = file_handle[:]->PB(time_in,:,:,:)
           MSFU = file_handle[:]->MAPFAC_U(time_in,:,:)
           MSFV = file_handle[:]->MAPFAC_V(time_in,:,:)
           MSFM = file_handle[:]->MAPFAC_M(time_in,:,:)
           COR  = file_handle[:]->F(time_in,:,:)
         end if
       end if  
       T = T + 300.
       P = P + PB
       DX = nc_file@DX
       DY = nc_file@DY

       pvo = wrf_pvo( U, V, T, P, MSFU, MSFV, MSFM, COR, DX, DY, 0)

       delete_VarAtts(T,(/"description","units"/))
       copy_VarAtts(T,pvo)
       return(pvo)
  end if



  if( variable .eq. "avo" ) then
       if ( time .eq. -1 ) then
         if(ISFILE) then
           U    = nc_file->U
           V    = nc_file->V
           MSFU = nc_file->MAPFAC_U
           MSFV = nc_file->MAPFAC_V
           MSFM = nc_file->MAPFAC_M
           COR  = nc_file->F
         else
           U    = file_handle[:]->U
           V    = file_handle[:]->V
           MSFU = file_handle[:]->MAPFAC_U
           MSFV = file_handle[:]->MAPFAC_V
           MSFM = file_handle[:]->MAPFAC_M
           COR  = file_handle[:]->F
         end if
       else
         if(ISFILE) then
           U    = nc_file->U(time_in,:,:,:)
           V    = nc_file->V(time_in,:,:,:)
           MSFU = nc_file->MAPFAC_U(time_in,:,:)
           MSFV = nc_file->MAPFAC_V(time_in,:,:)
           MSFM = nc_file->MAPFAC_M(time_in,:,:)
           COR  = nc_file->F(time_in,:,:)
         else
           U    = file_handle[:]->U(time_in,:,:,:)
           V    = file_handle[:]->V(time_in,:,:,:)
           MSFU = file_handle[:]->MAPFAC_U(time_in,:,:)
           MSFV = file_handle[:]->MAPFAC_V(time_in,:,:)
           MSFM = file_handle[:]->MAPFAC_M(time_in,:,:)
           COR  = file_handle[:]->F(time_in,:,:)
         end if
       end if  
       DX = nc_file@DX
       DY = nc_file@DY

       avo = wrf_avo( U, V, MSFU, MSFV, MSFM, COR, DX, DY, 0)

       delete_VarAtts(COR,(/"description","units"/))
       copy_VarAtts(COR,avo)
       return(avo)
  end if



  if( variable .eq. "dbz" .or. variable .eq. "mdbz" ) then
       ; calculate dbz
       ivarint  = 0 
       iliqskin = 0
       dim_vars = dimsizes(varin)
       do idims = 1,dim_vars-1
         if ( idims .eq. 1 ) then
           if ( varin(idims) .eq. "1" ) then
             ivarint = 1
           end if
         end if
         if ( idims .eq. 2 ) then
           if ( varin(idims) .eq. "1" ) then
             iliqskin = 1
           end if
         end if
       end do

       if ( time .eq. -1 ) then
         if(ISFILE) then
           T  = nc_file->T
           P  = nc_file->P
           PB = nc_file->PB
           qv = nc_file->QVAPOR
           qr = nc_file->QRAIN
         else
           T  = file_handle[:]->T
           P  = file_handle[:]->P
           PB = file_handle[:]->PB
           qv = file_handle[:]->QVAPOR
           qr = file_handle[:]->QRAIN
         end if
         if(isfilevar(nc_file,"QSNOW"))
           if(ISFILE) then
             qs = nc_file->QSNOW
           else
             qs = file_handle[:]->QSNOW
           end if
         end if
         if(isfilevar(nc_file,"QGRAUP"))
           if(ISFILE) then
             qg = nc_file->QGRAUP
           else
             qg = file_handle[:]->QGRAUP
           end if
         end if
       else
         if(ISFILE) then
           T  = nc_file->T(time_in,:,:,:)
           P  = nc_file->P(time_in,:,:,:)
           PB = nc_file->PB(time_in,:,:,:)
           qv = nc_file->QVAPOR(time_in,:,:,:)
           qr = nc_file->QRAIN(time_in,:,:,:)
         else
           T  = file_handle[:]->T(time_in,:,:,:)
           P  = file_handle[:]->P(time_in,:,:,:)
           PB = file_handle[:]->PB(time_in,:,:,:)
           qv = file_handle[:]->QVAPOR(time_in,:,:,:)
           qr = file_handle[:]->QRAIN(time_in,:,:,:)
         end if
         if(isfilevar(nc_file,"QSNOW"))
           if(ISFILE) then
             qs = nc_file->QSNOW(time_in,:,:,:)
           else
             qs = file_handle[:]->QSNOW(time_in,:,:,:)
           end if
         end if
         if(isfilevar(nc_file,"QGRAUP"))
           if(ISFILE) then
             qg = nc_file->QGRAUP(time_in,:,:,:)
           else
             qg = file_handle[:]->QGRAUP(time_in,:,:,:)
           end if
         end if
       end if
       T  = T + 300.
       P  = P + PB
       tk = wrf_tk( P , T )

       if ( .not. isvar("qs") ) then
         qs = qv
         qs = 0.0
       end if
       if ( .not. isvar("qg") ) then
         qg = qv
         qg = 0.0
       end if

       dbz = wrf_dbz ( P, tk, qv, qr, qs, qg, ivarint, iliqskin)
       delete(qs)
       delete(qg)

       delete_VarAtts(T,(/"description","units"/))
       copy_VarAtts(T,dbz)


       if ( variable .eq. "mdbz") then
         dims = getvardims(dbz)
         rank = dimsizes(dims)
         if ( rank .eq. 5 ) then
            mdbz = dim_max ( dbz($dims(0)$|:,$dims(1)$|:,$dims(3)$|:,$dims(4)$|:,$dims(2)$|:) )
            mdbz!0 = dbz!0
            mdbz!1 = dbz!1
         end if
         if ( rank .eq. 4 ) then
            mdbz = dim_max ( dbz($dims(0)$|:,$dims(2)$|:,$dims(3)$|:,$dims(1)$|:) )
            mdbz!0 = dbz!0
         end if
         if ( rank .eq. 3 ) then
            mdbz = dim_max ( dbz($dims(1)$|:,$dims(2)$|:,$dims(0)$|:) )
         end if
         nn = rank-1
         nm = rank-2
         mdbz!nm = dbz!nn
         nn = rank-2
         nm = rank-3
         mdbz!nm = dbz!nn
         copy_VarAtts(dbz,mdbz)
         mdbz@description = "Max Reflectivity"
         return(mdbz)
       else
         return(dbz)
       end if

  end if



  if( any( variable .eq. (/"cape_3d","cape_2d"/) ) ) then
       if ( time .eq. -1 ) then
         if(ISFILE) then
           T  = nc_file->T
           P  = nc_file->P
           PB = nc_file->PB
           QV = nc_file->QVAPOR
           PH  = nc_file->PH
           PHB = nc_file->PHB
           HGT = nc_file->HGT
           PSFC = nc_file->PSFC
         else
           T  = file_handle[:]->T
           P  = file_handle[:]->P
           PB = file_handle[:]->PB
           QV = file_handle[:]->QVAPOR
           PH  = file_handle[:]->PH
           PHB = file_handle[:]->PHB
           HGT = file_handle[:]->HGT
           PSFC = file_handle[:]->PSFC
         end if
       else
         if(ISFILE) then
           T  = nc_file->T(time_in,:,:,:)
           P  = nc_file->P(time_in,:,:,:)
           PB = nc_file->PB(time_in,:,:,:)
           QV = nc_file->QVAPOR(time_in,:,:,:)
           PH  = nc_file->PH(time_in,:,:,:)
           PHB = nc_file->PHB(time_in,:,:,:)
           HGT = nc_file->HGT(time_in,:,:)
           PSFC = nc_file->PSFC(time_in,:,:)
         else
           T  = file_handle[:]->T(time_in,:,:,:)
           P  = file_handle[:]->P(time_in,:,:,:)
           PB = file_handle[:]->PB(time_in,:,:,:)
           QV = file_handle[:]->QVAPOR(time_in,:,:,:)
           PH  = file_handle[:]->PH(time_in,:,:,:)
           PHB = file_handle[:]->PHB(time_in,:,:,:)
           HGT = file_handle[:]->HGT(time_in,:,:)
           PSFC = file_handle[:]->PSFC(time_in,:,:)
         end if
       end if
       T = T + 300.
       P  = P + PB 
       tk = wrf_tk( P , T )
       PH =  PH + PHB 
       z = wrf_user_unstagger(PH,PH@stagger)
       z = z/9.81

       if( variable .eq. "cape_3d" ) then
         cape = wrf_cape_3d( P, tk, QV, z, HGT, PSFC, True )
         cape@description = "cape ; cin"
       end if
       if( variable .eq. "cape_2d" ) then
         cape = wrf_cape_2d( P, tk, QV, z, HGT, PSFC, True )
         delete_VarAtts(T,(/"MemoryOrder"/))
         cape@MemoryOrder = "XY"
         cape@description = "mcape ; mcin ; lcl ; lfc"
       end if
       delete_VarAtts(T,(/"description","units"/))
       copy_VarAtts(T,cape)

       return(cape)
  end if



  if( any( variable .eq. (/"pw"/) ) ) then
       ;Precipitable Water 
        print("calculating precipitable water")
        gas_const = 287.  ; J/K/kg
        Cp        = 1004. ; J/K/kg     
       if ( time .eq. -1 ) then
        if(ISFILE) then
          T   = nc_file->T
          P   = nc_file->P
          PB  = nc_file->PB
          QV  = nc_file->QVAPOR
          PH  = nc_file->PH
          PHB = nc_file->PHB
          QV  = nc_file->QVAPOR
        else
          T   = file_handle[:]->T
          P   = file_handle[:]->P
          PB  = file_handle[:]->PB
          QV  = file_handle[:]->QVAPOR
          PH  = file_handle[:]->PH
          PHB = file_handle[:]->PHB
          QV  = file_handle[:]->QVAPOR
        end if
       else
        if(ISFILE) then
          T   = nc_file->T(time_in,:,:,:)
          P   = nc_file->P(time_in,:,:,:)
          PB  = nc_file->PB(time_in,:,:,:)
          QV  = nc_file->QVAPOR(time_in,:,:,:)
          PH  = nc_file->PH(time_in,:,:,:)
          PHB = nc_file->PHB(time_in,:,:,:)
          QV  = nc_file->QVAPOR(time_in,:,:,:)
        else
          T   = file_handle[:]->T(time_in,:,:,:)
          P   = file_handle[:]->P(time_in,:,:,:)
          PB  = file_handle[:]->PB(time_in,:,:,:)
          QV  = file_handle[:]->QVAPOR(time_in,:,:,:)
          PH  = file_handle[:]->PH(time_in,:,:,:)
          PHB = file_handle[:]->PHB(time_in,:,:,:)
          QV  = file_handle[:]->QVAPOR(time_in,:,:,:)
        end if
       end if  
       
       pres   =  P + PB
       height = (PH + PHB)/9.8           ; height at full levels 
       theta  =  T + 300.
       temp   = theta * (pres/100000) ^ (gas_const/Cp)
       vtemp  = (1 + 0.61*QV) * temp  ; virtual temp

       dims = dimsizes(T)
       nd = dimsizes(dims)

       if ( nd .eq. 4 ) then
         zdiff  = height(:,0,:,:)
         zdiff  = 0.
         pw_sfc_ptop = height(:,0,:,:)
         pw_sfc_ptop = 0.
         do k = 0,dims(1)-1
           zdiff(:,:,:) = (height(:,k+1,:,:) - height(:,k,:,:))
           pw_sfc_ptop(:,:,:) =  pw_sfc_ptop(:,:,:) + ((pres(:,k,:,:)/(gas_const * vtemp(:,k,:,:))) * QV(:,k,:,:) * zdiff(:,:,:))
         end do
       end if
       if ( nd .eq. 3 ) then
         zdiff  = height(0,:,:)
         zdiff  = 0.
         pw_sfc_ptop = height(0,:,:)
         pw_sfc_ptop = 0.
         do k = 0,dims(0)-1
           zdiff(:,:) = (height(k+1,:,:) - height(k,:,:))
           pw_sfc_ptop(:,:) =  pw_sfc_ptop(:,:) + ((pres(k,:,:)/(gas_const * vtemp(k,:,:))) * QV(k,:,:) * zdiff(:,:))
         end do
       end if

       pw_sfc_ptop@description = "Precipitable Water"
       return(pw_sfc_ptop)
  end if



  if( any( variable .eq. (/"helicity"/) ) ) then
       getU = "U" 
       getV = "V" 
       if(.not. isfilevar(nc_file,"U")) then
         if(isfilevar(nc_file,"UU")) then
           getU = "UU"
           getV = "VV"
        end if
       end if
       if ( time .eq. -1 ) then
        if(ISFILE) then
          u_in  = nc_file->$getU$
          v_in  = nc_file->$getV$
          PH    = nc_file->PH
          geopt = nc_file->PHB 
          ter   = nc_file->HGT
        else
          u_in  = file_handle[:]->$getU$
          v_in  = file_handle[:]->$getV$
          PH    = file_handle[:]->PH
          geopt = file_handle[:]->PHB 
          ter   = file_handle[:]->HGT
        end if
       else
        if(ISFILE) then
          u_in  = nc_file->$getU$(time_in,:,:,:)
          v_in  = nc_file->$getV$(time_in,:,:,:)
          PH    = nc_file->PH(time_in,:,:,:)
          geopt = nc_file->PHB(time_in,:,:,:)
          ter   = nc_file->HGT(time_in,:,:)
        else
          u_in  = file_handle[:]->$getU$(time_in,:,:,:)
          v_in  = file_handle[:]->$getV$(time_in,:,:,:)
          PH    = file_handle[:]->PH(time_in,:,:,:)
          geopt = file_handle[:]->PHB(time_in,:,:,:)
          ter   = file_handle[:]->HGT(time_in,:,:)
        end if
       end if

       ua    = wrf_user_unstagger(u_in,u_in@stagger)
       va    = wrf_user_unstagger(v_in,v_in@stagger)
       geopt  = geopt + PH
       za     = wrf_user_unstagger(geopt,geopt@stagger)
       za     = za / 9.81  ; change to height

       ua1    = ua(::-1,:,:)
       va1    = va(::-1,:,:)
       za1    = za(::-1,:,:)

       top_ok = 0
       top = 3000.

       dim_vars = dimsizes(varin)
       if(dim_vars .eq. 2) then
        if( varin(1) .eq. "3000" ) then
           top = 3000.
           top_ok = 1
        end if

        if( varin(1) .eq. "1000" ) then
           top = 1000.
           top_ok = 1
        end if

        if(top_ok .eq. 0) then
          print("Top values of 1000 or 3000 are accepted.")
          top = 3000.
        end if
       end if

       print("Calculations are done with a top of " + top)
       sreh = wrf_helicity(ua1, va1, za1, ter, top)
       return(sreh)
  end if



  if( any(variable .eq. (/"updraft_helicity"/) ) )then
       getU = "U"
       getV = "V"
       if(.not. isfilevar(nc_file,"U")) then
         if(isfilevar(nc_file,"UU")) then
           getU = "UU"
           getV = "VV"
         end if
       end if
       if ( time .eq. -1 ) then
         if(ISFILE) then
            u_in = nc_file->$getU$
            v_in = nc_file->$getV$
            w    = nc_file->W
            ph   = nc_file->PH
            phb  = nc_file->PHB
         else
            u_in = file_handle[:]->$getU$
            v_in = file_handle[:]->$getV$
            w    = file_handle[:]->W
            ph   = file_handle[:]->PH
            phb  = file_handle[:]->PHB
         end if
       else
         if(ISFILE) then
            u_in = nc_file->$getU$(time_in,:,:,:)
            v_in = nc_file->$getV$(time_in,:,:,:)
            w    = nc_file->W(time_in,:,:,:)
            ph   = nc_file->PH(time_in,:,:,:)
            phb  = nc_file->PHB(time_in,:,:,:)
         else
            u_in = file_handle[:]->$getU$(time_in,:,:,:)
            v_in = file_handle[:]->$getV$(time_in,:,:,:)
            w    = file_handle[:]->W(time_in,:,:,:)
            ph   = file_handle[:]->PH(time_in,:,:,:)
            phb  = file_handle[:]->PHB(time_in,:,:,:)
         end if
       end if
       ua   = wrf_user_unstagger(u_in,u_in@stagger)
       va   = wrf_user_unstagger(v_in,v_in@stagger)
       mapfct = nc_file->MAPFAC_M(0,:,:)
       zp = ph + phb
       dx = nc_file@DX
       dy = nc_file@DY

       uh_opt = True
       uh_opt@uhmnhgt = 2000.
       uh_opt@uhmxhgt = 5000.
       dim_vars = dimsizes(varin)

       print("Calculating updraft helicity")
       if(dim_vars .eq. 1) then
         print("  Using defaults for the integration limits")
       end if
       
       if(dim_vars .eq. 2) then
         print("  Please enter both the minimum and maximum integration limits")
         print("  Going to use defaults for the integration limits")
       end if
       
       if(dim_vars .eq. 3) then
         if ( stringtofloat(varin(1)) .lt. 1000. ) then
           print("  Integration limits needs to be greater than 1000 meter")
           print("  Going to use defaults for the integration limits")
         else
           uh_opt@uhmnhgt = stringtofloat(varin(1))
           uh_opt@uhmxhgt = stringtofloat(varin(2))
           print("  Setting custom integration limits")
         end if
       end if
       
       print("  min = "+uh_opt@uhmnhgt+" max = "+uh_opt@uhmxhgt)
       uh = wrf_updraft_helicity(zp, mapfct, ua, va, w, dx, dy, uh_opt)
       delete(uh_opt)
       
       return(uh)
  end if




  if( any( variable .eq. (/"ter","HGT","HGT_M"/) ) ) then
    variable = "HGT" 
    if(.not. isfilevar(nc_file,"HGT")) then
      variable = "HGT_M"
    end if
  end if


  if( any( variable .eq. (/"lat","XLAT","XLAT_M"/) ) ) then
    variable = "XLAT" 
    if(.not. isfilevar(nc_file,"XLAT")) then
      variable = "XLAT_M"
    end if
  end if


  if( any( variable .eq. (/"lon","long","XLONG","XLONG_M"/) ) ) then
    variable = "XLONG" 
    if(.not. isfilevar(nc_file,"XLONG")) then
      variable = "XLONG_M"
    end if
  end if


  if( any( variable .eq. (/"times"/) ) ) then
    if ( time .eq. -1 ) then
      if(ISFILE) then
        var = nc_file->Times
      else
        var = file_handle[:]->Times
      end if
    else
      if(ISFILE) then
        var = nc_file->Times(time_in,:)
      else
        var = file_handle[:]->Times(time_in,:)
      end if
    end if
    dims = dimsizes(var)
    times = new(dims(0),string)
    do i=0,dims(0)-1
      times(i) = chartostring(var(i,:))
    end do
    times@description = "times in file"
    return (times)
  end if



;  end of diagnostic variable list - we must want a variable already in the file.  

  if ( time .eq. -1 ) then
    if(ISFILE) then
      var = nc_file->$variable$
    else
      var = file_handle[:]->$variable$
    end if
  else
    ;  check variable dimensionality and pull proper time  out of file
    ndims = dimsizes(filevardimsizes(nc_file,variable))
    if( ndims .eq. 4) then
      if(ISFILE) then
        var = nc_file->$variable$(time_in,:,:,:)
      else
        var = file_handle[:]->$variable$(time_in,:,:,:)
      end if
    end if
    if( ndims .eq. 3) then
      if(ISFILE) then
        var = nc_file->$variable$(time_in,:,:)
      else
        var = file_handle[:]->$variable$(time_in,:,:)
      end if
    end if
    if( ndims .eq. 2) then
      if(ISFILE) then
        var = nc_file->$variable$(time_in,:)
      else
        var = file_handle[:]->$variable$(time_in,:)
      end if
    end if
    if( ndims .eq. 1) then
      if(ISFILE) then
      var = nc_file->$variable$(time_in)
      else
      var = file_handle[:]->$variable$(time_in)
      end if
    end if
  end if

  return(var)

end


;--------------------------------------------------------------------------------
undef("wrf_user_getvar_from_files")
function wrf_user_getvar_from_files( nc_files:string, varin[*]:string, time[*]:integer, opts_args:logical )

begin

  numFiles = dimsizes(nc_files)
  f = addfiles(nc_files,"r")

  var_tmp = wrf_user_getvar(f[0],varin,-1)
  varDims = dimsizes(var_tmp)
  varRank = dimsizes(varDims)
  time_req = 0
  time_inc = 1
  time_end = varDims(0)*numFiles
  if ( dimsizes(time) .eq. 1 ) then
    if ( time(0) .ge. 0 ) then
      numTimes = 1
      time_req = time(0)
      time_end = time(0)
      time_inc = 1
    else
      numTimes = varDims(0)*numFiles
    end if
  end if
  if ( dimsizes(time) .eq. 2 ) then
    if ( time(0) .ge. 0 ) then
      numTimes = (time(1)-time(0))+1
      time_req = time(0)
      time_end = time(1)
      time_inc = 1
    else
      numTimes = varDims(0)*numFiles
    end if
  end if
  if ( dimsizes(time) .eq. 3 ) then
    if ( time(0) .ge. 0 ) then
      numTimes = ((time(1)-time(0))+1)/time(2)
      time_req = time(0)
      time_end = time(1)
      time_inc = time(2)
    else
      numTimes = varDims(0)*numFiles
    end if
  end if
  outtime = 0
  outtime_avail = 0


  if ( varRank .eq. 4 )
    varout = new ( (/numTimes,varDims(1),varDims(2),varDims(3)/), typeof(var_tmp) )
    varout = 0
    do it = 0,varDims(0)-1
      if ( (outtime_avail.eq.time_req) .and. (time_req.le.time_end) ) then
        varout(outtime,:,:,:) = var_tmp(it,:,:,:)
        outtime = outtime + 1
        time_req = time_req + time_inc
      end if
      outtime_avail = outtime_avail + 1
    end do
    delete(var_tmp)
    do ifil = 1,numFiles-1
      var_tmp = wrf_user_getvar(f[ifil],varin,-1)
      dimLoop = dimsizes(var_tmp)
      do it = 0,dimLoop(0)-1
        if ( (outtime_avail.eq.time_req) .and. (time_req.le.time_end) ) then
          varout(outtime,:,:,:) = var_tmp(it,:,:,:)
          outtime = outtime + 1
          time_req = time_req + time_inc
        end if
        outtime_avail = outtime_avail + 1
      end do
      delete(var_tmp)
    end do
  end if
  if ( varRank .eq. 3 )
    varout = new ( (/numTimes,varDims(1),varDims(2)/), typeof(var_tmp) )
    varout = 0
    do it = 0,varDims(0)-1
      if ( (outtime_avail.eq.time_req) .and. (time_req.le.time_end) ) then
        varout(outtime,:,:) = var_tmp(it,:,:)
        outtime = outtime + 1
        time_req = time_req + time_inc
      end if
      outtime_avail = outtime_avail + 1
    end do
    delete(var_tmp)
    do ifil = 1,numFiles-1
      var_tmp = wrf_user_getvar(f[ifil],varin,-1)
      dimLoop = dimsizes(var_tmp)
      do it = 0,dimLoop(0)-1
        if ( (outtime_avail.eq.time_req) .and. (time_req.le.time_end) ) then
          varout(outtime,:,:) = var_tmp(it,:,:)
          outtime = outtime + 1
          time_req = time_req + time_inc
        end if
        outtime_avail = outtime_avail + 1
      end do
      delete(var_tmp)
    end do
  end if
  if ( varRank .eq. 2 )
    varout = new ( (/numTimes,varDims(1)/), typeof(var_tmp) )
    if ( typeof(var_tmp) .eq. "float" .or. typeof(var_tmp) .eq. "integer" ) then
      varout = 0
    end if
    do it = 0,varDims(0)-1
      if ( (outtime_avail.eq.time_req) .and. (time_req.le.time_end) ) then
        varout(outtime,:) = var_tmp(it,:)
        outtime = outtime + 1
        time_req = time_req + time_inc
      end if
      outtime_avail = outtime_avail + 1
    end do
    delete(var_tmp)
    do ifil = 1,numFiles-1
      var_tmp = wrf_user_getvar(f[ifil],varin,-1)
      dimLoop = dimsizes(var_tmp)
      do it = 0,dimLoop(0)-1
        if ( (outtime_avail.eq.time_req) .and. (time_req.le.time_end) ) then
          varout(outtime,:) = var_tmp(it,:)
          outtime = outtime + 1
          time_req = time_req + time_inc
        end if
        outtime_avail = outtime_avail + 1
      end do
      delete(var_tmp)
    end do
  end if
  if ( varRank .eq. 1 )
    varout = new ( (/numTimes/), typeof(var_tmp) )
    if ( typeof(var_tmp) .eq. "float" .or. typeof(var_tmp) .eq. "integer" ) then
      varout = 0
    end if
    do it = 0,varDims(0)-1
      if ( (outtime_avail.eq.time_req) .and. (time_req.le.time_end) ) then
        varout(outtime) = var_tmp(it)
        outtime = outtime + 1
        time_req = time_req + time_inc
      end if
      outtime_avail = outtime_avail + 1
    end do
    delete(var_tmp)
    do ifil = 1,numFiles-1
      var_tmp = wrf_user_getvar(f[ifil],varin,-1)
      dimLoop = dimsizes(var_tmp)
      do it = 0,dimLoop(0)-1
        if ( (outtime_avail.eq.time_req) .and. (time_req.le.time_end) ) then
          varout(outtime) = var_tmp(it)
          outtime = outtime + 1
          time_req = time_req + time_inc
        end if
        outtime_avail = outtime_avail + 1
      end do
      delete(var_tmp)
    end do
  end if

  return(varout)
end




;--------------------------------------------------------------------------------
; This function was modified in May 2011 to allow a list of files.
;
undef("wrf_user_list_times")
function wrf_user_list_times( nc_file )

local times, times_in_file, dims, i
begin

;---As of NCL V6.0.0, wrf_user_getvar can now handle a file or a list of files.
  if(all(typeof(nc_file).ne.(/"file","list"/))) then
    print("wrf_user_list_times: error: the input argument must be a file or a list of files opened with addfile or addfiles")
    return
  end if

  if(typeof(nc_file).eq."file") then
    times_in_file = nc_file->Times
  else
    times_in_file = nc_file[:]->Times
  end if
  dims = dimsizes(times_in_file)
  times = new(dims(0),string)
  do i=0,dims(0)-1
    times(i) = chartostring(times_in_file(i,:))
  end do
  times@description = "times in file"
  print(times)
  return(times)

end

;--------------------------------------------------------------------------------

undef("wrf_user_latlon_to_ij")
function wrf_user_latlon_to_ij( nc_file:file, latitude:numeric, \
                                longitude:numeric )

begin
  WE       = "WEST-EAST_GRID_DIMENSION"
  SN       = "SOUTH-NORTH_GRID_DIMENSION"
  wedim    = nc_file@$WE$
  sndim    = nc_file@$SN$

  if(isfilevar(nc_file,"XLAT"))
    XLAT  = nc_file->XLAT(0,:,:)
    XLONG = nc_file->XLONG(0,:,:)
  else
    XLAT  = nc_file->XLAT_M(0,:,:)
    XLONG = nc_file->XLONG_M(0,:,:)
  end if

  loc = wrf_latlon_to_ij( XLAT, XLONG, latitude, longitude )

  loc!0 = "j & i locations"
  return(loc)

end

;--------------------------------------------------------------------------------

undef("wrf_user_ll_to_ij")
function wrf_user_ll_to_ij( file_handle, longitude:numeric, latitude:numeric, \
                            opts_args:logical )

begin
;
; As of NCL V6.0.0, wrf_user_ll_to_ij can now handle a file 
; or a list of files.
;
  if(typeof(file_handle).eq."file") then
    ISFILE = True
    nc_file = file_handle
  else if(typeof(file_handle).eq."list") then
    ISFILE = False
    nc_file = file_handle[0]
  else
    print("wrf_user_ll_to_ij: error: the first argument must be a file or a list of files opened with addfile or addfiles")
    return
  end if
  end if

  opts = opts_args
  useT  = get_res_value(opts,"useTime",0)
  returnI= get_res_value(opts,"returnInt",True)

  res = True
  res@MAP_PROJ  = nc_file@MAP_PROJ
  res@TRUELAT1  = nc_file@TRUELAT1
  res@TRUELAT2  = nc_file@TRUELAT2
  res@STAND_LON = nc_file@STAND_LON
  res@DX        = nc_file@DX
  res@DY        = nc_file@DY

  if (res@MAP_PROJ .eq. 6) then
    res@POLE_LAT  = nc_file@POLE_LAT
    res@POLE_LON  = nc_file@POLE_LON
    res@LATINC = (res@DY*360.)/2.0/3.141592653589793/6370000.
    res@LONINC = (res@DX*360.)/2.0/3.141592653589793/6370000.
  else
    res@POLE_LAT = 90.0
    res@POLE_LON =  0.0
    res@LATINC = 0.0
    res@LONINC = 0.0
  end if

  if(isfilevar(nc_file,"XLAT"))
    if(ISFILE) then
      XLAT  = nc_file->XLAT(useT,:,:)
      XLONG = nc_file->XLONG(useT,:,:)
    else
      XLAT  = file_handle[useT]->XLAT
      XLONG = file_handle[useT]->XLONG
    end if
  else
    if(ISFILE) then
      XLAT  = nc_file->XLAT_M(useT,:,:)
      XLONG = nc_file->XLONG_M(useT,:,:)
    else
      XLAT  = file_handle[useT]->XLAT_M
      XLONG = file_handle[useT]->XLONG_M
    end if
  end if


  if(dimsizes(dimsizes(XLAT)).eq.2) then
; Rank 2
    res@REF_LAT = XLAT(0,0)
    res@REF_LON = XLONG(0,0)
  else
; Rank 3
    res@REF_LAT = XLAT(0,0,0)
    res@REF_LON = XLONG(0,0,0)
  end if
  res@KNOWNI  = 1.0
  res@KNOWNJ  = 1.0

  loc = wrf_ll_to_ij (longitude, latitude, res)

  if ( returnI  ) then
    loci = new(dimsizes(loc),integer)
    ;loci@_FillValue = default_fillvalue("integer")   ; was -999
    loci = tointeger(loc + .5)
    loci!0 = loc!0
    return(loci)
  else
    return(loc)
  end if


end

;--------------------------------------------------------------------------------

undef("wrf_user_ij_to_ll")
function wrf_user_ij_to_ll( file_handle, i:numeric, j:numeric, \
                            opts_args:logical )

begin
;
; As of NCL V6.0.0, wrf_user_ll_to_ij can now handle a file 
; or a list of files.
;
  if(typeof(file_handle).eq."file") then
    ISFILE = True
    nc_file = file_handle
  else if(typeof(file_handle).eq."list") then
    ISFILE = False
    nc_file = file_handle[0]
  else
    print("wrf_user_ij_to_ll: error: the first argument must be a file or a list of files opened with addfile or addfiles")
    return
  end if
  end if

  opts = opts_args
  useT  = get_res_value(opts,"useTime",0)

  res = True
  res@MAP_PROJ  = nc_file@MAP_PROJ
  res@TRUELAT1  = nc_file@TRUELAT1
  res@TRUELAT2  = nc_file@TRUELAT2
  res@STAND_LON = nc_file@STAND_LON
  res@DX        = nc_file@DX
  res@DY        = nc_file@DY

  if (res@MAP_PROJ .eq. 6) then
    res@POLE_LAT  = nc_file@POLE_LAT
    res@POLE_LON  = nc_file@POLE_LON
    res@LATINC = (res@DY*360.)/2.0/3.141592653589793/6370000.
    res@LONINC = (res@DX*360.)/2.0/3.141592653589793/6370000.
  else
    res@POLE_LAT = 90.0
    res@POLE_LON =  0.0
    res@LATINC = 0.0
    res@LONINC = 0.0
  end if


  if(isfilevar(nc_file,"XLAT")) then
    if(ISFILE) then
      XLAT  = nc_file->XLAT(useT,:,:)
      XLONG = nc_file->XLONG(useT,:,:)
    else
      XLAT  = file_handle[useT]->XLAT
      XLONG = file_handle[useT]->XLONG
    end if
  else
    if(ISFILE) then
      XLAT  = nc_file->XLAT_M(useT,:,:)
      XLONG = nc_file->XLONG_M(useT,:,:)
    else
      XLAT  = file_handle[useT]->XLAT_M
      XLONG = file_handle[useT]->XLONG_M
    end if
  end if

  if(dimsizes(dimsizes(XLAT)).eq.2) then
; Rank 2
    res@REF_LAT = XLAT(0,0)
    res@REF_LON = XLONG(0,0)
  else
; Rank 3
    res@REF_LAT = XLAT(0,0,0)
    res@REF_LON = XLONG(0,0,0)
  end if
  res@KNOWNI  = 1.0
  res@KNOWNJ  = 1.0

  loc = wrf_ij_to_ll (i,j,res)

  return(loc)


end

;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------

undef("write_wrf_debug_info")
procedure write_wrf_debug_info(wks[1]:graphic,data1,data2, \
                               debug_file[1]:string, \
                               wrf_opts,wrf_func_name[1]:string)
;
; This procedure writes resources and data variables used to
; create a WRF plot to a NetCDF file. This file can be read
; in later to recreate the NCL script that created that plot,
; using gsn_xxx functions. This is for debug purposes. You can't
; tell what resources a WRF script is using, so this is a way
; of seeing them all in a NetCDF file.
;
begin
  if(.not.isatt(wks,"WRFDebug")) then
    first_time = True
    wks@WRFDebug = True
  else
    first_time = False
  end if
;
; The default will be "wrfdebug.ncl" and "wrfdebug.nc" 
; unless otherwise specified.
;
  cdf_debug_file = debug_file +  ".nc"
  ncl_debug_file = debug_file +  ".ncl"
  res_debug_file = debug_file +  ".res"

;
; If this is the first time writing debug information to the file,
; then create the file and add the first set of information.
;
; Make sure the files don't already exist.
;
  if(first_time) then
    if(isfilepresent(cdf_debug_file).or.isfilepresent(ncl_debug_file).or.\
       isfilepresent(res_debug_file)) then
      print("write_wrf_debug_info: error: debug files '" + cdf_debug_file + "',")
      print("'" + ncl_debug_file + "' and/or " + res_debug_file + " exist.")
      print("Please remove file(s) and start script again.")
      exit
    end if
    dbgfile = addfile(cdf_debug_file,"c")
  else
;
; If this is not the first time, open the file as read/write.
;
    dbgfile = addfile(cdf_debug_file,"w")
  end if

;
; If this is not the first time, then we need to append the information.
;  
  if(.not.first_time) then
;
; The variables should be wrf_var_1, wrf_var_2, etc. We need to get the
; highest one already in use, so we can create the next highest one.
;
    wrf_debug_vars = getfilevarnames(dbgfile)
    max_num = max(stringtointeger(str_get_field(wrf_debug_vars,3,"_"))) + 1
  else
    max_num = 1
  end if

; This will be name of the logical variable to hold all the resources
; for this dataset.
  wrf_res_name  = "wrf_res_" + max_num

;
; Write the plot data to the netCDF file.  If the data contains the
; special 2D lat2d/lon2d arrays, we have to write these as 1D arrays
; and reconstruct them as 2D later.
;
  if(typeof(data1).ne."logical".and.typeof(data2).eq."logical") then
; For non u,v data
    wrf_data_name = "wrf_data_" + max_num
    add_latlon2d_debug_info(data1)
    dbgfile->$wrf_data_name$ = (/data1/)           ; Write the data
  end if
  if(typeof(data1).ne."logical".and.typeof(data2).ne."logical") then
; For u,v data
    add_latlon2d_debug_info(data1)
    add_latlon2d_debug_info(data2)
    wrf_data_name = "wrf_udata_" + max_num
    dbgfile->$wrf_data_name$ = (/data1/)           ; Write the U data
    wrf_data_name = "wrf_vdata_" + max_num
    dbgfile->$wrf_data_name$ = (/data2/)           ; Write the V data
  end if

; Retain the name of the wrf function that called this routine.
  tmp = "wrf_func_name_" + max_num
  dbgfile@$tmp$ = wrf_func_name

;
; Get plot resources, if any.
;
  wattnames = getvaratts(wrf_opts)
  if(.not.any(ismissing(wattnames))) then
    natt = dimsizes(wattnames)
  else
    natt = 0
  end if

;
; Check if any of the plot attributes are ones that can contain
; big data arrays, like sfXArray, vfYArray, etc.
;
; If so, then write these to the netCDF file. Otherwise, write them
; to the file as attributes.
;
  array_resources = (/"sfXArray","sfYArray","vfXArray","vfYArray"/)

  if(natt.gt.0) then
    tmp_opts = 1
    do i=0,natt-1
      if(any(wattnames(i).eq.array_resources)) then
        tmp = "wrf_data_coord_name_" + wattnames(i) + "_" + max_num
        dbgfile->$tmp$ = wrf_opts@$wattnames(i)$
      else
; Can't write "logical" to a NetCDF file.
        if(typeof(wrf_opts@$wattnames(i)$).eq."logical") then
          if(wrf_opts@$wattnames(i)$) then
            tmp_opts@$wattnames(i)$ = 1
          else
            tmp_opts@$wattnames(i)$ = 0
          end if
        else
; Just write the resource.
          tmp_opts@$wattnames(i)$ = wrf_opts@$wattnames(i)$
        end if
      end if
    end do
    dbgfile->$wrf_res_name$ = tmp_opts
  end if

; Close the NetCDF file
  delete(dbgfile)
end

undef("write_wrf_debug_script")
procedure write_wrf_debug_script(wks,debug_file,wrf_func_name)
begin
  dbgfile = addfile(debug_file+".nc","r")
  print(getvaratts(dbgfile))
end

undef("delete_attrs")
procedure delete_attrs(opts:logical)

; This procedure does some cleanup by removing unneeded attributes
; so they don't get passed to other routines by accident.

begin
  list_attrs = (/"MainTitle","MainTitlePos","MainTitlePosF", \
                 "InitTime","ValidTime","TimePos","TimePosF", \
                 "NoHeaderFooter","TimeLabel","LevelLabel", \
                 "FieldTitle","UnitLabel","NumVectors","AspectRatio", \
                 "SubFieldTitle","PlotOrientation","PlotLevelID", \
                 "mpNestTime","ContourParameters","FontHeightF","Footer", \
                 "start_lat","start_lon","end_lat","end_lon", \
                 "proj","map_proj","stand_lon","truelat1","truelat2","cenlat", \
                 "pole_lat","pole_lon","ref_lat","ref_lon","ref_x","ref_y", \
                 "e_we","e_sn","parent_id","parent_grid_ratio", \
                 "i_parent_start","j_parent_start", \
                 "dx","dy","max_dom" \
                 /)

  do i=0,dimsizes(list_attrs)-1
    if(isatt(opts,list_attrs(i))) then
      delete(opts@$list_attrs(i)$)
    end if
  end do
end

;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
undef("set_cn_resources")
function set_cn_resources (data[*][*]:numeric, res:logical)

begin

  opts = res

; The ContourParameters resource can either be a scalar that
; represents the contour level spacing, or it can be an array
; of three elements that represent the minimum level, the maximum
; level, and the level spacing.
;
  mx = max(data)
  mn = min(data)

  if(mn.ne.mx.and.opts.and.isatt(opts,"ContourParameters")) then
    if(dimsizes(opts@ContourParameters) .eq. 1) then

; Only the contour interval is specified.
      nlev   = tointeger((mx-mn)/opts@ContourParameters)+1
      levels = nice_mnmxintvl(mn,mx,nlev,True)
      if(levels(0) .lt. 0.) then
        ; Set a zero contour.
        nlev = tointeger(levels(0)/opts@ContourParameters) - 1
        levels(0) = nlev*opts@ContourParameters
      end if
      nlev = tointeger((levels(1)-levels(0))/opts@ContourParameters)+1
      levels(1) = levels(0) + nlev*opts@ContourParameters
      levels(2) = opts@ContourParameters

; Min level, max level, and level spacing are specified by user.
    else
      if(dimsizes(opts@ContourParameters) .eq. 3) then
        levels = opts@ContourParameters
      else
        print("wrf_contour: Warning: illegal setting for ContourParameters attribute")
      end if
    end if

  end if

; Contour levels
  if(isvar("levels")) then
    opts@cnLevelSelectionMode = get_res_value_keep(opts, "cnLevelSelectionMode", "ManualLevels")
    opts@cnMinLevelValF       = get_res_value_keep(opts, "cnMinLevelValF", levels(0))
    opts@cnMaxLevelValF       = get_res_value_keep(opts, "cnMaxLevelValF", levels(1))
    opts@cnLevelSpacingF      = get_res_value_keep(opts, "cnLevelSpacingF",levels(2))
    delete(levels)
  end if


; Set the default zero line thickness to 2, and the negative contour
; line dash pattern to 1 (0 is solid).
  opts@gsnContourZeroLineThicknessF = get_res_value_keep(opts, "gsnContourZeroLineThicknessF",2.0)
  opts@gsnContourNegLineDashPattern = get_res_value_keep(opts, "gsnContourNegLineDashPattern",1)


; Set resources that apply for both filled and line contour plots.
  opts@cnFillDrawOrder            = get_res_value_keep(opts,"cnFillDrawOrder", "PreDraw")


  opts@cnLineLabelAngleF          = get_res_value_keep(opts,"cnLineLabelAngleF", 0.0)
  opts@cnLineLabelFontHeightF     = get_res_value_keep(opts,"cnLineLabelFontHeightF", 0.015)
  opts@cnInfoLabelFontHeightF     = get_res_value_keep(opts,"cnInfoLabelFontHeightF", 0.015)
  opts@cnLineLabelPerimOn         = get_res_value_keep(opts,"cnLineLabelPerimOn", True)
  opts@cnInfoLabelPerimOn         = get_res_value_keep(opts,"cnInfoLabelPerimOn", False)
  opts@cnLineLabelBackgroundColor = get_res_value_keep(opts,"cnLineLabelBackgroundColor", -1)
  opts@cnHighLabelBackgroundColor = get_res_value_keep(opts,"cnHighLabelBackgroundColor", -1)
  opts@cnLowLabelBackgroundColor  = get_res_value_keep(opts,"cnLowLabelBackgroundColor", -1)
  opts@cnLineColor                = get_res_value_keep(opts,"cnLineColor", "Black")
  opts@cnLineLabelFontColor       = opts@cnLineColor
  opts@cnLineLabelPerimColor      = opts@cnLineColor
  opts@cnInfoLabelFontColor       = opts@cnLineColor
  opts@cnHighLabelFontColor       = opts@cnLineColor
  opts@cnLowLabelFontColor        = opts@cnLineColor


; Set field Title and levels if available
  if(isatt(opts,"FieldTitle")) then
    opts@cnInfoLabelString     = opts@FieldTitle + " Contours: $CMN$ to $CMX$ by $CIU$"
  else
    if(isatt(data,"description")) then
      opts@cnInfoLabelString     = data@description + " Contours: $CMN$ to $CMX$ by $CIU$"
    else
      opts@cnInfoLabelString     = " Contours: $CMN$ to $CMX$ by $CIU$"
    end if
  end if


  return(opts)
end
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
undef("set_lb_resources")
function set_lb_resources (data[*][*]:numeric, res:logical)

begin

  opts = res


; Somewhat convoluted way to see if a labelbar is not desired.
  if(check_attr(opts,"pmTickMarkDisplayMode","Never",True).or.\
     check_attr(opts,"pmTickMarkDisplayMode",-1,False).or.\
     check_attr(opts,"pmTickMarkDisplayMode",0,False).or. \
     check_attr(opts,"lbLabelBarOn",False,False).or.\
     check_attr(opts,"lbLabelBarOn",0,False)) then
    lbar_on = False
  else
    lbar_on = True
  end if
  atmp = get_res_value(opts,"lbLabelBarOn",True) ; Remove this resource
  delete(atmp)                                   ; just in case.


; Possible title for the labelbar
  if(isatt(opts,"FieldTitle")) then
    lb_desc = opts@FieldTitle 
  else
    if(isatt(data,"description")) then
      lb_desc = data@description 
    else
      lb_desc = ""  
    end if
  end if

  if(isatt(opts,"UnitLabel") ) then
    lb_desc = lb_desc + "  (" + opts@UnitLabel + ")"
  else
    if(isatt(data,"units") .and. .not.(data@units.eq."")) then
      lb_desc = lb_desc + "  (" + data@units + ")"
    end if
  end if


  if(.not.isatt(opts,"cnFillColors")) then
    opts@gsnSpreadColors = get_res_value_keep(opts, "gsnSpreadColors", True)
  end if
  opts@cnInfoLabelOn   = get_res_value_keep(opts,"cnInfoLabelOn", False)
  opts@cnLinesOn       = get_res_value_keep(opts,"cnLinesOn", False)
  opts@cnLineLabelsOn  = get_res_value_keep(opts,"cnLineLabelsOn", False)

; Labelbar resources
  if(lbar_on) then
    opts@pmLabelBarDisplayMode    = get_res_value_keep(opts,"pmLabelBarDisplayMode", "Always")
    opts@pmLabelBarSide           = get_res_value_keep(opts,"pmLabelBarSide", "Bottom")
    opts@lbAutoManage             = get_res_value_keep(opts,"lbAutoManage",False)
    opts@lbOrientation            = get_res_value_keep(opts,"lbOrientation", "Horizontal")
    opts@lbPerimOn                = get_res_value_keep(opts,"lbPerimOn", False)
    opts@lbLabelJust              = get_res_value_keep(opts,"lbLabelJust", "BottomCenter")
    opts@lbLabelAutoStride        = get_res_value_keep(opts,"lbLabelAutoStride",True)
    opts@lbBoxMinorExtentF        = get_res_value_keep(opts,"lbBoxMinorExtentF", 0.13)
    opts@lbTitleFontHeightF       = get_res_value_keep(opts,"lbTitleFontHeightF", 0.015)
    opts@lbLabelFontHeightF       = get_res_value_keep(opts,"lbLabelFontHeightF", 0.015)
    opts@pmLabelBarOrthogonalPosF = get_res_value_keep(opts,"pmLabelBarOrthogonalPosF", -0.1)

    opts@lbTitleOn                = get_res_value_keep(opts,"lbTitleOn", True)
    if(lb_desc.ne."" .and. opts@lbTitleOn) then
      opts@lbTitleOn              = get_res_value_keep(opts,"lbTitleOn", True)
      opts@lbTitleString          = get_res_value_keep(opts,"lbTitleString", lb_desc)
      opts@lbTitleJust            = get_res_value_keep(opts,"lbTitleJust", "BottomCenter")
      opts@lbTitleOffsetF         = get_res_value_keep(opts,"lbTitleOffsetF", -0.5)
    else
      opts@lbTitleOn = False
    end if
  end if


  return(opts)
end
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
undef("set_title_resources")
function set_title_resources (data[*][*]:numeric, res:logical)

begin

  opts = res

; Set field Title and levels if available
  if(isatt(opts,"FieldTitle")) then
    SubTitles = opts@FieldTitle
  else
    if(isatt(data,"description")) then
      SubTitles = data@description
    else
      SubTitles = "UnKnown"
    end if
  end if

  if(isatt(opts,"SubFieldTitle")) then
    SubTitles = SubTitles + " " +  opts@SubFieldTitle
  end if
  if(isatt(opts,"UnitLabel")) then
    SubTitles = SubTitles + "   (" +  opts@UnitLabel + ")"
  else
     if(isatt(data,"units") .and. .not.(data@units.eq."")) then
      SubTitles = SubTitles + "   (" +  data@units + ")"
    end if
  end if
  if (isatt(opts,"PlotLevelID")) then
    SubTitles = SubTitles + "     at   " +  opts@PlotLevelID 
  else
    if (isatt(data,"PlotLevelID")) then
       SubTitles = SubTitles + "     at   " +  data@PlotLevelID 
    end if
  end if
  opts@tiMainString = SubTitles      

  return(opts)
end
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
undef("set_vc_resources")
function set_vc_resources (res:logical)

begin

  opts = res

  if ( isatt(opts,"vpWidthF") ) then
  ; num_vectors is used for vcMinDistanceF and vcRefLengthF
    width = opts@vpWidthF
    num_vectors = get_res_value(opts,"NumVectors",25.0)
    opts@vcMinDistanceF   = get_res_value_keep(opts,"vcMinDistanceF", width/num_vectors)
    opts@vcRefLengthF     = get_res_value_keep(opts,"vcRefLengthF", width/num_vectors)
  else
    opts@vcMinDistanceF   = get_res_value_keep(opts,"vcMinDistanceF", 0.02)
    opts@vcRefLengthF     = get_res_value_keep(opts,"vcRefLengthF", 0.02)
  end if


  opts@vcGlyphStyle     = get_res_value_keep(opts,"vcGlyphStyle", "WindBarb")
  opts@vcWindBarbColor  = get_res_value_keep(opts,"vcWindBarbColor", "Black")
  opts@vcRefAnnoOn      = get_res_value_keep(opts,"vcRefAnnoOn", False)
  opts@vcMinFracLengthF = get_res_value_keep(opts,"vcMinFracLengthF", .2)
 
  return(opts)
end
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
undef("set_mp_resources")
function set_mp_resources (res:logical)

begin

  opts = res

; "LowRes" is the default that NCL uses, so you don't need to
; set it here. However, if you want a higher resolution, use 
; "MediumRes". If you want higher resolution for the coastlines,
; then set it to "HighRes", but then you also need to download
; the RANGS-GSHHS database.  Higher resolutions take longer to
; draw.

      opts@mpDataBaseVersion     = get_res_value_keep(opts, "mpDataBaseVersion","MediumRes")
     ;opts@mpOutlineBoundarySets = get_res_value_keep(opts, "mpOutlineBoundarySets", "AllBoundaries")
      opts@mpOutlineBoundarySets = get_res_value_keep(opts, "mpOutlineBoundarySets", "GeophysicalAndUSStates")
      opts@mpPerimLineThicknessF = get_res_value_keep(opts, "mpPerimLineThicknessF", 1.0)
      opts@tmXBLabelFontHeightF  = get_res_value_keep(opts, "tmXBLabelFontHeightF", 0.01)
      opts@tmYLLabelFontHeightF  = get_res_value_keep(opts, "tmYLLabelFontHeightF", 0.01)

; Select portion of the map to view.
      opts@mpLimitMode           = get_res_value_keep(opts, "mpLimitMode","Corners")
      opts@mpLeftCornerLatF      = get_res_value_keep(opts, "mpLeftCornerLatF", opts@start_lat)
      opts@mpLeftCornerLonF      = get_res_value_keep(opts, "mpLeftCornerLonF", opts@start_lon)
      opts@mpRightCornerLatF     = get_res_value_keep(opts, "mpRightCornerLatF",opts@end_lat)
      opts@mpRightCornerLonF     = get_res_value_keep(opts, "mpRightCornerLonF",opts@end_lon)

      if ( opts@mpRightCornerLonF .lt. 0.0 ) then
        opts@mpRightCornerLonF  = opts@mpRightCornerLonF + 360.0
      end if 

; Set some other resources for line colors and grid spacing.

      opts@mpGeophysicalLineColor      = get_res_value_keep(opts, "mpGeophysicalLineColor","Gray")
      opts@mpGeophysicalLineThicknessF = get_res_value_keep(opts, "mpGeophysicalLineThicknessF",0.5)
      opts@mpGridLineColor             = get_res_value_keep(opts, "mpGridLineColor","Gray")
      opts@mpGridLineThicknessF        = get_res_value_keep(opts, "mpGridLineThicknessF",0.5)
     ;opts@mpGridMaskMode              = get_res_value_keep(opts, "mpGridMaskMode",3)
      opts@mpGridSpacingF              = get_res_value_keep(opts, "mpGridSpacingF",5)
      opts@mpLimbLineColor             = get_res_value_keep(opts, "mpLimbLineColor","Gray")
      opts@mpLimbLineThicknessF        = get_res_value_keep(opts, "mpLimbLineThicknessF",0.5)
      opts@mpNationalLineColor         = get_res_value_keep(opts, "mpNationalLineColor","Gray")
      opts@mpNationalLineThicknessF    = get_res_value_keep(opts, "mpNationalLineThicknessF",0.5)
      opts@mpPerimLineColor            = get_res_value_keep(opts, "mpPerimLineColor","Gray")
      opts@mpPerimOn                   = get_res_value_keep(opts, "mpPerimOn",True)
      opts@mpUSStateLineColor          = get_res_value_keep(opts, "mpUSStateLineColor","Gray")
      opts@mpUSStateLineThicknessF     = get_res_value_keep(opts, "mpUSStateLineThicknessF",0.5)
      opts@pmTickMarkDisplayMode       = get_res_value_keep(opts, "pmTickMarkDisplayMode","Always")

; Tick mark resources

     ;opts@tmXBMajorLengthF      = get_res_value(opts, "tmXBMajorLengthF",-0.03)
     ;opts@tmYLMajorLengthF      = get_res_value(opts, "tmYLMajorLengthF",-0.03)
      opts@tmXTOn                = get_res_value(opts,"tmXTOn",False)
      opts@tmYROn                = get_res_value(opts,"tmYROn",False)
      opts@tmYRLabelsOn          = get_res_value(opts,"tmYRLabelsOn",True)
      opts@tmXBBorderOn          = get_res_value(opts,"tmXBBorderOn",True)
      opts@tmXTBorderOn          = get_res_value(opts,"tmXTBorderOn",True)
      opts@tmYLBorderOn          = get_res_value(opts,"tmYLBorderOn",True)
      opts@tmYRBorderOn          = get_res_value(opts,"tmYRBorderOn",True)

  return(opts)
end
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------

undef("_SetMainTitle")
procedure _SetMainTitle(nc_file:file,wks[1]:graphic,cn[1]:graphic,opts)
 
; This procedure checks the input data for certain attributes, and
; based on those, sets MainTitle, InitTime and ValidTime
;
;  Attributes recognized by this procedure:
;     MainTitle                 (main title - top left)
;                               (with Init time top right)
;     TimeLabel                 (valid time  - right  under init time)
;     NoHeaderFooter            (switch all headers and footers off - mainly for panels)
;
; If the "NoHeaderFooter" attribute exists and is set True, then
; don't create any titles.

begin
;
  if(opts.and.isatt(opts,"NoHeaderFooter").and.opts@NoHeaderFooter) then
    return
  end if

;
; Set basic plot font
;
  font_height = get_res_value_keep(opts,"FontHeightF",0.01)
;
;
; If a MainTitle attribute hasn't been set, then set to "WRF"
; Also set an Initial time
;
; MAIN Header of plot
  opts@MainTitle    = get_res_value_keep(opts,"MainTitle", " ") 
  opts@MainTitlePos = get_res_value_keep(opts,"MainTitlePos", "Left") 
  opts@InitTime     = get_res_value_keep(opts,"InitTime", True) 
  opts@ValidTime    = get_res_value_keep(opts,"ValidTime", True) 
  opts@TimePos      = get_res_value_keep(opts,"TimePos", "Right") 
  opts@Footer       = get_res_value_keep(opts,"Footer", True) 


  if (opts@MainTitlePos .eq. "Left")
    opts@MainTitlePos  = "CenterLeft"
    opts@MainTitlePosF = 0.0
  end if
  if (opts@MainTitlePos .eq. "Center")
    opts@MainTitlePos  = "CenterCenter"
    opts@MainTitlePosF = 0.5
  end if
  if (opts@MainTitlePos .eq. "Right")
    opts@MainTitlePos  = "CenterRight"
    opts@MainTitlePosF = 1.0
  end if

  if (opts@TimePos .eq. "Left")
    MTOPosF = 0.30
  else
    MTOPosF = 0.20
  end if

  txt0 = create "MainPlotTitle" textItemClass wks
    "txString"      : opts@MainTitle
    "txFontHeightF" : font_height*1.5
  end create
  anno = NhlAddAnnotation(cn,txt0)
  setvalues anno
    "amZone"           : 3
    "amSide"           : "Top"
    "amJust"           : opts@MainTitlePos
    "amParallelPosF"   : opts@MainTitlePosF
    "amOrthogonalPosF" : MTOPosF
    "amResizeNotify"   : False
  end setvalues

; Time information on plot
  if (opts@TimePos .eq. "Left")
    opts@TimePos  = "CenterLeft"
    opts@TimePosF = 0.0
    if (opts@MainTitlePos .eq. "CenterLeft")
     MTOPosF = MTOPosF - 0.05
    end if
  end if
  if (opts@TimePos .eq. "Right")
    opts@TimePos  = "CenterRight"
    opts@TimePosF = 1.0
    if (opts@MainTitlePos .eq. "CenterRight")
     MTOPosF = MTOPosF - 0.05
    end if
  end if

  if( isatt(nc_file,"START_DATE") ) then
     model_start_time = nc_file@START_DATE
  else
     if( isatt(nc_file,"SIMULATION_START_DATE") ) then
       model_start_time = nc_file@SIMULATION_START_DATE
     else
       opts@InitTime = False
     end if
  end if   
  if( opts@InitTime ) then
    InitTime = "Init: " + model_start_time
    txt1 = create "InitTime" textItemClass wks
      "txString"      : InitTime
      "txFontHeightF" : font_height
    end create
    anno = NhlAddAnnotation(cn,txt1)
    setvalues anno
      "amZone"           : 3
      "amSide"           : "Top"
      "amJust"           : opts@TimePos
      "amParallelPosF"   : opts@TimePosF        
      "amOrthogonalPosF" : MTOPosF
      "amResizeNotify"   : False
    end setvalues
  end if

  plot_narrow = False
  if((opts).and.(isatt(opts,"vpWidthF")).and.(isatt(opts,"vpHeightF"))) then
     ph = opts@vpHeightF  
     pw = opts@vpWidthF  
     phw = ph/pw
     if ( phw .gt. 1.8 ) then
       plot_narrow = True
     end if
  end if

  if( opts@ValidTime .and. isatt(opts,"TimeLabel") ) then

    ValidTime = "Valid: " + opts@TimeLabel

    MTOPosF = MTOPosF - 0.03
    txt2 = create "ValidTime" textItemClass wks
      "txString"      : ValidTime
      "txFontHeightF" : font_height
    end create
    anno = NhlAddAnnotation(cn,txt2)
    setvalues anno
      "amZone"           : 3
      "amSide"           : "Top"
      "amJust"           : opts@TimePos
      "amParallelPosF"   : opts@TimePosF        
      "amOrthogonalPosF" : MTOPosF           
      "amResizeNotify"   : False
    end setvalues
  end if


; Add Footer if called for
  if( opts@Footer ) then
    footer1 = nc_file@TITLE
    dis =  nc_file@DX / 1000.0
    WE = "WEST-EAST_GRID_DIMENSION"
    SN = "SOUTH-NORTH_GRID_DIMENSION"
    BT = "BOTTOM-TOP_GRID_DIMENSION"
    footer2 =  " WE = " + nc_file@$WE$ + \
               " ; SN = " + nc_file@$SN$ + \
               " ; Levels = " + nc_file@$BT$ + \
               " ; Dis = " + dis + "km"
    if ( isatt(nc_file,"MP_PHYSICS")) then
      footer2 = footer2 +  " ; Phys Opt = " + nc_file@MP_PHYSICS 
    end if
    if ( isatt(nc_file,"BL_PBL_PHYSICS")) then
      footer2 = footer2 +  " ; PBL Opt = " + nc_file@BL_PBL_PHYSICS 
    end if
    if ( isatt(nc_file,"CU_PHYSICS")) then
      footer2 = footer2 +  " ; Cu Opt = " + nc_file@CU_PHYSICS 
    end if
    Footer = footer1 + "~C~" + footer2
   else
     Footer = " "
   end if
    txt3 = create "Footer" textItemClass wks
      "txString"      : Footer 
      "txFontHeightF" : font_height*.9
    end create
    anno = NhlAddAnnotation(cn,txt3)
    setvalues anno
      "amZone"           : 1
;      "amZone"           : 7
      "amJust"           : "TopLeft"
      "amSide"           : "Bottom"
      "amParallelPosF"   : 0.0
      "amOrthogonalPosF" : -0.55
      "amResizeNotify"   : False
    end setvalues


; Add X-setion information if needed
  if(opts.and.isatt(opts,"PlotOrientation")) then
    ;Xsection = "Cross-Section Orientation : " + opts@PlotOrientation
    Xsection =  opts@PlotOrientation
    txt4 = create "Xsection" textItemClass wks
      "txString"      : Xsection 
      "txFontHeightF" : font_height*.9
    end create
    anno = NhlAddAnnotation(cn,txt4)
    setvalues anno
      "amZone"           : 3
      "amSide"           : "Top"
      "amJust"           : "CenterRight"
      "amParallelPosF"   : 1.0
      "amOrthogonalPosF" : 0.005
      "amResizeNotify"   : False
    end setvalues
  end if

end

;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
;--------------------------------------------------------------------------------
undef("set_mp_wrf_map_resources")
function set_mp_wrf_map_resources(in_file[1]:file,opt_args[1]:logical)   

begin
;
    opts = opt_args      ; Make a copy of the resource list

; Set some resources depending on what kind of map projection is 
; chosen.
;
;   MAP_PROJ = 0 : "CylindricalEquidistant"
;   MAP_PROJ = 1 : "LambertConformal"
;   MAP_PROJ = 2 : "Stereographic"
;   MAP_PROJ = 3 : "Mercator"
;   MAP_PROJ = 6 : "Lat/Lon"

    if(isatt(in_file,"MAP_PROJ"))

;   CylindricalEquidistant
      if(in_file@MAP_PROJ .eq. 0)
        projection          = "CylindricalEquidistant"
        opts@mpProjection = projection
        opts@mpGridSpacingF = 45
        opts@mpCenterLatF   = get_res_value_keep(opts, "mpCenterLatF", 0.0)
        if(isatt(in_file,"STAND_LON"))
          opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF",in_file@STAND_LON)
        else
          if(isatt(in_file,"CEN_LON"))
            opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF",in_file@CEN_LON)
          else
           print("ERROR: Found neither STAND_LON or CEN_LON in file")
          end if
        end if
      end if

;   LambertConformal projection
      if(in_file@MAP_PROJ .eq. 1)
        projection               = "LambertConformal"
        opts@mpProjection = projection
        opts@mpLambertParallel1F = get_res_value_keep(opts, "mpLambertParallel1F",in_file@TRUELAT1)
        opts@mpLambertParallel2F = get_res_value_keep(opts, "mpLambertParallel2F",in_file@TRUELAT2)
        if(isatt(in_file,"STAND_LON"))
          opts@mpLambertMeridianF  = get_res_value_keep(opts, "mpLambertMeridianF",in_file@STAND_LON)
        else
          if(isatt(in_file,"CEN_LON"))
            opts@mpLambertMeridianF  = get_res_value_keep(opts, "mpLambertMeridianF",in_file@CEN_LON)
          else
           print("ERROR: Found neither STAND_LON or CEN_LON in file")
          end if
        end if
      end if
  
;   Stereographic projection
      if(in_file@MAP_PROJ .eq. 2)
        projection          = "Stereographic"
        opts@mpProjection = projection
        opts@mpCenterLatF   = get_res_value_keep(opts, "mpCenterLatF", in_file@CEN_LAT)
        if(isatt(in_file,"STAND_LON"))
          opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF",in_file@STAND_LON)
        else
          if(isatt(in_file,"CEN_LON"))
            opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF",in_file@CEN_LON)
          else
           print("ERROR: Found neither STAND_LON or CEN_LON in file")
          end if
        end if
      end if
  
;   Mercator projection
      if(in_file@MAP_PROJ .eq. 3)
        projection          = "Mercator"
        opts@mpProjection = projection
        opts@mpCenterLatF   = get_res_value_keep(opts, "mpCenterLatF", 0.0)
        if(isatt(in_file,"STAND_LON"))
          opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF",in_file@STAND_LON)
        else
          if(isatt(in_file,"CEN_LON"))
            opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF",in_file@CEN_LON)
          else
           print("ERROR: Found neither STAND_LON or CEN_LON in file")
          end if
        end if
      end if
  
;    global WRF CylindricalEquidistant
      if(in_file@MAP_PROJ .eq. 6)
        projection          = "CylindricalEquidistant"
        opts@mpProjection = projection
        opts@mpGridSpacingF = 45
        opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF",in_file@CEN_LON)
        if( isatt(in_file,"POLE_LAT") ) then
          opts@mpCenterRotF = get_res_value_keep(opts, "mpCenterRotF", 90.0 - in_file@POLE_LAT) 
          delete(opts@mpCenterLonF)
          calcen = -190.
          opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF", calcen )
        end if
      end if
  
    end if

  return(opts)                                     ; Return.

end
;--------------------------------------------------------------------------------

undef("wrf_contour_ps")
function wrf_contour_ps(nc_file:file,wks[1]: graphic, data[*][*]:numeric, \
                     opt_args[1]:logical)

begin

  callFrame = True
  if ( isatt(opt_args,"FrameIT") ) then
    if ( .not.opt_args@FrameIT ) then
      callFrame = False
    end if
    delete (opt_args@FrameIT)
  end if

  lat2U = nc_file->XLAT_U(0,:,:)
  lon2U = nc_file->XLONG_U(0,:,:)

  opts = opt_args
  opts@sfXArray = lon2U
  opts@sfYArray = lat2U
  opts@sfDataArray = data
  opts@mpProjection         = "Stereographic"
  opts@mpEllipticalBoundary = True
  opts@mpFillOn = False
 
  opts@mpGeophysicalLineColor      = get_res_value_keep(opts, "mpGeophysicalLineColor","Gray")
  opts@mpGeophysicalLineThicknessF = get_res_value_keep(opts, "mpGeophysicalLineThicknessF",2.0)


  ; Set the contour resources
  opts = set_cn_resources(data,opts)
  opts@cnInfoLabelFontHeightF = 0.012
  opts@cnLineLabelPerimOn = False
  opts@cnInfoLabelPerimOn = True


  ; Find out if we are working with a contour or a shaded plot
  ; fill_on = False : line contour plot
  ; fill_on = True  : filled contour plot
  fill_on = get_res_value_keep(opts,"cnFillOn",False)
  if(fill_on) then      ; set lb resources if needed
    opts@pmLabelBarDisplayMode    = get_res_value_keep(opts,"pmLabelBarDisplayMode", "Never")
    opts = set_lb_resources(data,opts)
    opts@pmLabelBarOrthogonalPosF = 0.0
    opts@lbTitleJust = "BottomLeft"
  end if
  


  opts@gsnDraw = False   
  opts@gsnFrame = False
  opts@gsnMaximize = False
  delete_attrs(opts)
  cn = gsn_csm_contour_map_polar(wks,data,opts)          ; Create the plot.

  draw(cn)


  if ( callFrame ) then
    frame(wks)
  end if

return (cn)
end
;--------------------------------------------------------------------------------
undef("wrf_vector_ps")
function wrf_vector_ps(nc_file:file,wks[1]: graphic, \
                       data_u[*][*]:numeric, data_v[*][*]:numeric, \
                       opt_args[1]:logical)

begin

  callFrame = True
  if ( isatt(opt_args,"FrameIT") ) then
    if ( .not.opt_args@FrameIT ) then
      callFrame = False
    end if
    delete (opt_args@FrameIT)
  end if

  if(isfilevar(nc_file,"XLAT"))
    lat2T = nc_file->XLAT(0,:,:)
    lon2T = nc_file->XLONG(0,:,:)
  else
    lat2T = nc_file->XLAT_M(0,:,:)
    lon2T = nc_file->XLONG_M(0,:,:)
  end if

  opts = opt_args
  opts@vfXArray = lon2T
  opts@vfYArray = lat2T
  opts@vfUDataArray = data_u
  opts@vfVDataArray = data_v
  opts@mpProjection         = "Stereographic"
  opts@mpEllipticalBoundary = True
  opts@mpFillOn = False

  opts@mpGeophysicalLineColor      = get_res_value_keep(opts, "mpGeophysicalLineColor","Gray")
  opts@mpGeophysicalLineThicknessF = get_res_value_keep(opts, "mpGeophysicalLineThicknessF",2.0)


; Set vector resources
  opts = set_vc_resources(opts) 


 opts@gsnDraw = False   
 opts@gsnFrame = False
 opts@gsnMaximize = False
 delete_attrs(opts)
 cn = gsn_csm_vector_map_polar(wks,data_u,data_v,opts)          ; Create the plot.

  draw(cn)


  if ( callFrame ) then
    frame(wks)
  end if

return (cn)
end
;--------------------------------------------------------------------------------

undef("wrf_contour")
function wrf_contour(nc_file:file,wks[1]: graphic, data[*][*]:numeric, \
                     opt_args[1]:logical)
 
; This function creates a contour plot and adds some titles to it.
;
;   1. Determine width to height ratio of plot.
;
;   2. First determine if this is to be a filled or line
;      contour plot (fill_on)
;
;   3. If the ContourParameters attribute is set, then calculate
;      the contour levels.
;
;   4. Set two resources for setting the zero contour line to 
;      a larger thickness, and for changing the negative contour
;      lines to a dashed pattern.
;
;   5. If doing a filled contour plot, set a title for the labelbar
;      based on whether a units attribute is set.
;
;   6. Make a copy of the resource list, and set some additional
;      resources for filled contour plots.
;
;   7. Create the contour plot, attach the titles, and draw
;      and advance the frame (if requested).
 
local dims
begin
  opts = opt_args      ; Make a copy of the resource list.

  if(opts.and.isatt(opts,"gsnDebugWriteFileName")) then
    wrf_debug_file = get_res_value(opts,"gsnDebugWriteFileName",  "")    
  end if
    
  if(opts.and.isatt(opts,"mpOutlineBoundarySets")) then
    delete(opts@mpOutlineBoundarySets)
  end if


; Calculate ratio of plot width and height. Note that this doesn't
; affect the setting of gsnMaximize to True, because gsnMaximize will
; retain the aspect ratio of the plot.

  if(opts.and.isatt(opts,"AspectRatio")) then
    ratio = opts@AspectRatio
  else
    dims  = dimsizes(data)
    ratio = 1.*dims(0)/dims(1)
    if(ratio .gt. 1.2) then
      ratio = 1.2
    end if
    if(ratio .lt. 0.6667) then
      ratio = 0.6667
    end if
  end if

  if(ratio .gt. 1) 
    width  = 0.65 * 1.0/ratio
    height = 0.65
  else
    width  = 0.85 
    height = 0.85 * ratio
  end if

  opts@vpWidthF = get_res_value_keep(opts,"vpWidthF",  width)
  opts@vpHeightF = get_res_value_keep(opts,"vpHeightF", height)


; Set some basic contour resources 
  opts = set_cn_resources(data,opts)


; Find out if we are working with a contour or a shaded plot
; fill_on = False : line contour plot
; fill_on = True  : filled contour plot
  fill_on = get_res_value_keep(opts,"cnFillOn",False)
  if(fill_on) then      ; set lb resources if needed
    opts = set_lb_resources(data,opts)
    atmp = get_res_value(opts,"lbLabelBarOn",True) ; Remove this resource
    delete(atmp)                                   ; just in case.
  end if


; Set Title resources
  opts = set_title_resources(data,opts)


; Setting gsnScale to True ensures that the tickmark lengths and labels
; will be the same size on both axes.
  opts@gsnScale    = get_res_value_keep(opts,"gsnScale",    True)


; The default is not to draw the plot or advance the frame, and
; to maximize the plot in the frame.
  opts@gsnDraw          = False    ; Make sure don't draw or frame or,
  opts@gsnFrame         = False    ; maximize, b/c we'll do this later.
  opts@gsnMaximize      = False


  opts2 = opts
  delete_attrs(opts2)                       ; Clean up.
  cn = gsn_contour(wks,data,opts2)          ; Create the plot.
  _SetMainTitle(nc_file,wks,cn,opts)        ; Set some titles

  if(isvar("wrf_debug_file")) then
    write_wrf_debug_info(wks,data,False,wrf_debug_file,opts2,"wrf_contour")
  end if

  opts2@gsnDraw     = get_res_value_keep(opts2,"gsnDraw",     False)
  opts2@gsnFrame    = get_res_value_keep(opts2,"gsnFrame",    False)
  opts2@gsnMaximize = get_res_value_keep(opts2,"gsnMaximize", True)
  draw_and_frame(wks,cn,opts2@gsnDraw,opts2@gsnFrame,False,opts2@gsnMaximize)

  return(cn)                                ; Return

end

;--------------------------------------------------------------------------------

undef("wrf_vector")
function wrf_vector(nc_file:file,wks[1]: graphic, data_u[*][*]:numeric, \
                    data_v[*][*]:numeric, opt_args[1]:logical)
;
; This function creates a vector plot and adds some titles to it.
;
;   1. Determine width to height ratio of plot. Will also be use
;      to calculate values for vector resources later.
;
;   2. Make a copy of the resource list, and set some additional
;      resources.
;
;   3. Create the vector plot, attach the titles, and draw
;      and advance the frame (if requested).
 
local dims
begin
  opts = opt_args      ; Make a copy of the resource list.

  if(opts.and.isatt(opts,"gsnDebugWriteFileName")) then
    wrf_debug_file = get_res_value(opts,"gsnDebugWriteFileName",  "")    
  end if

  if(opts.and.isatt(opts,"mpOutlineBoundarySets")) then
    delete(opts@mpOutlineBoundarySets)
  end if
;
; The ratio is used to determine the width and height of the
; plot, and also to determine the value for the vcMinDistanceF
; resource.
;
  if(opts.and.isatt(opts,"AspectRatio")) then
    ratio = get_res_value(opts,"AspectRatio",0.)
  else
    dims  = dimsizes(data_u)
    ratio = 1.*dims(0)/dims(1)
    if(ratio .gt. 1.2) then
      ratio = 1.2
    end if
    if(ratio .lt. 0.6667) then
      ratio = 0.6667
    end if
  end if

  if(ratio .gt. 1) 
    width  = 0.65/ratio
    height = 0.65
  else
    width  = 0.95 
    height = 0.95 * ratio
  end if

  opts@vpWidthF  = get_res_value_keep(opts,"vpWidthF",  width)
  opts@vpHeightF = get_res_value_keep(opts,"vpHeightF", height)


; Set Title resources
  opts = set_title_resources(data_u,opts)


; Set vector resources
  opts = set_vc_resources(opts)


; Setting gsnScale to True ensures that the tickmark lengths and labels
; will be the same size on both axes.
  opts@gsnScale = get_res_value_keep(opts,"gsnScale",    True)


; The default is not to draw the plot or advance the frame, and
; to maximize the plot in the frame.
  opts@gsnDraw          = False    ; Make sure don't draw or frame or,
  opts@gsnFrame         = False    ; maximize, b/c we'll do this later.
  opts@gsnMaximize      = False

  opts2 = opts
  delete_attrs(opts2)                             ; Clean up.
  vct = gsn_vector(wks,data_u,data_v,opts2)       ; Create vector plot.
  _SetMainTitle(nc_file,wks,vct,opts) 

  if(isvar("wrf_debug_file")) then
    write_wrf_debug_info(wks,data_u,data_v,wrf_debug_file,opts2,"wrf_vector")
  end if

  opts2@gsnDraw     = get_res_value_keep(opts2,"gsnDraw",     False)
  opts2@gsnFrame    = get_res_value_keep(opts2,"gsnFrame",    False)
  opts2@gsnMaximize = get_res_value_keep(opts2,"gsnMaximize", True)
  draw_and_frame(wks,vct,opts2@gsnDraw,opts2@gsnFrame,False, \
                 opts2@gsnMaximize)

  return(vct)                                     ; Return.
end

;--------------------------------------------------------------------------------
undef("wrf_wps_map")
function wrf_wps_map(wks[1]:graphic,opt_args[1]:logical)   

begin
;
;   1. Make a copy of the resource list, and set some resources
;      common to all map projections.
;
;   2. Determine the projection being used, and set resources based
;      on that projection.
;
;   3. Create the map plot, and draw and advance the frame
;      (if requested).

    opts = opt_args      ; Make a copy of the resource list
    opts  = True

; Set some resources depending on what kind of map projection is 
; chosen.
;
;   MAP_PROJ = 0 : "CylindricalEquidistant"
;   MAP_PROJ = 1 : "LambertConformal"
;   MAP_PROJ = 2 : "Stereographic"
;   MAP_PROJ = 3 : "Mercator"
;   MAP_PROJ = 6 : "Lat/Lon"

;   CylindricalEquidistant
      if(opts@map_proj .eq. 0)
        projection          = "CylindricalEquidistant"
        opts@mpGridSpacingF = 45
        opts@mpCenterLatF   = get_res_value_keep(opts, "mpCenterLatF", 0.0)
        opts@mpCenterLonF   = get_res_value_keep(opts, "mpCenterLonF",opts@stand_lon)
      end if

;   LambertConformal projection
      if(opts@map_proj .eq. 1)
        projection               = "LambertConformal"
        opts@mpLambertParallel1F = get_res_value_keep(opts, "mpLambertParallel1F",opts@truelat1)
        opts@mpLambertParallel2F = get_res_value_keep(opts, "mpLambertParallel2F",opts@truelat2)
        opts@mpLambertMeridianF  = get_res_value_keep(opts, "mpLambertMeridianF",opts@stand_lon)
      end if
  
;   Stereographic projection
      if(opts@map_proj .eq. 2)
        projection          = "Stereographic"
        if( isatt(opts,"cenlat") ) then
          opts@mpCenterLatF  = get_res_value_keep(opts, "mpCenterLatF",opts@cenlat)
        else
          opts@mpCenterLatF  = get_res_value_keep(opts, "mpCenterLatF",opts@ref_lat)
        end if
        opts@mpCenterLonF   = get_res_value_keep(opts, "mpCenterLonF",opts@stand_lon)
      end if
  
;   Mercator projection
      if(opts@map_proj .eq. 3)
        projection          = "Mercator"
        opts@mpCenterLatF   = get_res_value_keep(opts, "mpCenterLatF", 0.0)
        opts@mpCenterLonF   = get_res_value_keep(opts, "mpCenterLonF",opts@stand_lon)
      end if
  
;    global WRF CylindricalEquidistant
      if(opts@map_proj .eq. 6)
        projection          = "CylindricalEquidistant"
        opts@mpGridSpacingF = 45
        if( isatt(opts,"cenlon") ) then
          opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF",opts@cenlon)
        else
          opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF",opts@ref_lon)
        end if
        if( isatt(opts,"pole_lat") ) then
          delete(opts@mpCenterLonF)
          opts@mpCenterLonF  = get_res_value_keep(opts, "mpCenterLonF", - 190. )
          opts@mpCenterRotF = get_res_value_keep(opts, "mpCenterRotF", 90.0 - opts@pole_lat) 
        else
          opts@mpCenterRotF = get_res_value_keep(opts, "mpCenterRotF", 0.0) 
        end if
      end if

; Set some resources common to all map projections.
  opts = set_mp_resources(opts)

; The default is not to draw the plot or advance the frame, and
; to maximize the plot in the frame.

  opts@gsnDraw       = get_res_value_keep(opts,"gsnDraw",     False)
  opts@gsnFrame      = get_res_value_keep(opts,"gsnFrame",    False)
  opts@gsnMaximize   = get_res_value_keep(opts,"gsnMaximize", True)

  delete_attrs(opts)                             ; Clean up.
  mp = gsn_map(wks,projection,opts)              ; Create map plot.
  return(mp)                                     ; Return.

end

;--------------------------------------------------------------------------------
undef("wrf_wps_dom")
function wrf_wps_dom(wks[1]:graphic,opt_args[1]:logical,lnres[1]:logical,txres[1]:logical) 

begin

  mpres = opt_args
  ;BPR BEGIN
  ;grid_to_plot = 0 => plot using the corner mass grid points
  ;grid_to_plot = 1 => plot using the edges of the corner grid cells
  ;  This uses the locations of the corner mass grid points +/- 0.5 grid cells
  ;  to get from the mass grid point to the edge of the grid cell
  grid_to_plot = 1
  ;grid_to_plot = mpres@grid_to_plot
  if(grid_to_plot.eq.0) then
  ; print("Plotting using corner mass grid points")
  else if(grid_to_plot.eq.1) then
  ; print("Plotting using edges of the corner grid cells")
  else
   print("ERROR: Invalid value for grid_to_plot = "+grid_to_plot)
  end if
  end if
  ;BPR END

  res = True
  res@DX = mpres@dx
  res@DY = mpres@dy
  res@LATINC = 0.0
  res@LONINC = 0.0
  if ( mpres@map_proj .eq. "lambert") then
    mpres@map_proj = 1
    res@MAP_PROJ = 1
  end if
  if ( mpres@map_proj .eq. "polar") then
    mpres@map_proj = 2
    res@MAP_PROJ = 2
  end if
  if ( mpres@map_proj .eq. "mercator") then
    mpres@map_proj = 3
    res@MAP_PROJ = 3
  end if
  if ( mpres@map_proj .eq. "lat-lon") then
    mpres@map_proj = 6
    res@MAP_PROJ = 6
    res@LATINC = mpres@dy
    res@LONINC = mpres@dx
  end if
  res@TRUELAT1 = mpres@truelat1
  res@TRUELAT2 = mpres@truelat2
  res@STAND_LON = mpres@stand_lon

  res@REF_LAT = mpres@ref_lat
  res@REF_LON = mpres@ref_lon
  if ( isatt(mpres,"ref_x") ) then
    res@KNOWNI = mpres@ref_x
  else
    res@KNOWNI = int2flt(mpres@e_we(0))/2.
  end if
  if ( isatt(mpres,"ref_y") ) then
    res@KNOWNJ = mpres@ref_y
  else
    res@KNOWNJ = int2flt(mpres@e_sn(0))/2.
  end if

  if ( isatt(mpres,"pole_lat") ) then
    res@POLE_LAT = mpres@pole_lat
  else
    res@POLE_LAT = 90.0
  end if
  if ( isatt(mpres,"pole_lon") ) then
    res@POLE_LON = mpres@pole_lon
  else
    res@POLE_LON = 0.0
  end if

  ;BPR BEGIN
  ;Determine adjustment needed to convert from mass grid to chosen grid
  if(grid_to_plot.eq.0) then
   adjust_grid = 0.0 
  else if(grid_to_plot.eq.1) then
   adjust_grid = 0.5 
  else 
   print("ERROR: Invalid value for grid_to_plot = "+grid_to_plot)
   adjust_grid = 0.0 
  end if
  end if

  xx = 1.0 - adjust_grid
  yy = 1.0 - adjust_grid
  ;xx = 1.0
  ;yy = 1.0
  ;BPR END
  loc = wrf_ij_to_ll (xx,yy,res)
  start_lon = loc(0)
  start_lat = loc(1)
  ;BPR BEGIN
  ;e_we is the largest U grid point and e_sn the largest V gridpoint
  ;xx = int2flt(mpres@e_we(0))
  ;yy = int2flt(mpres@e_sn(0))
  ;Change it so it is in terms of mass grid points since wrf_ij_to_ll is
  ;in terms of mass grid points 
  xx = int2flt(mpres@e_we(0)-1) + adjust_grid
  yy = int2flt(mpres@e_sn(0)-1) + adjust_grid
  ;BPR END
  loc = wrf_ij_to_ll (xx,yy,res)
  end_lon = loc(0)
  end_lat = loc(1)

  mpres@start_lat   = start_lat
  mpres@start_lon   = start_lon
  mpres@end_lat     = end_lat
  mpres@end_lon     = end_lon


  mp = wrf_wps_map(wks,mpres)
  draw(mp)


  if ( mpres@max_dom .gt. 1 ) then

    numLineColors = 0
    if ( isatt(lnres,"domLineColors") ) then
       numLineColors = dimsizes(lnres@domLineColors)
    end if

    do idom = 1,mpres@max_dom-1

      if ( numLineColors .gt. 0 ) then
        if ( numLineColors .ge. idom ) then
          lnres@gsLineColor = lnres@domLineColors(idom-1)
          txres@txFontColor = lnres@domLineColors(idom-1)
        else
          lnres@gsLineColor = lnres@domLineColors(numLineColors-1)
          txres@txFontColor = lnres@domLineColors(numLineColors-1)
        end if
      end if


      ; nest start and end points in large domain space
      if ( mpres@parent_id(idom) .eq. 1) then
        ; corner value
        ;BPR BEGIN
        ;Due to the alignment of nests we need goffset in order to
        ;find the location of (1,1) in the fine domain in coarse domain
        ;coordinates
        ;i_start = mpres@i_parent_start(idom)
        ;j_start = mpres@j_parent_start(idom)
        goffset = 0.5*(1-(1.0/mpres@parent_grid_ratio(idom)))
        i_start = mpres@i_parent_start(idom)-goffset
        j_start = mpres@j_parent_start(idom)-goffset
        ; end point
        ;Change to mass point
        ;i_end = (mpres@e_we(idom)-1)/mpres@parent_grid_ratio(idom) + i_start
        ;j_end = (mpres@e_sn(idom)-1)/mpres@parent_grid_ratio(idom) + j_start
        i_end = (mpres@e_we(idom)-2)/(1.0*mpres@parent_grid_ratio(idom)) + i_start
        j_end = (mpres@e_sn(idom)-2)/(1.0*mpres@parent_grid_ratio(idom)) + j_start
        
        if(grid_to_plot.eq.0) then
         adjust_grid = 0.0 
        else if(grid_to_plot.eq.1) then
         adjust_grid = 0.5/(1.0*mpres@parent_grid_ratio(idom))
        else 
         print("ERROR: Invalid value for grid_to_plot = "+grid_to_plot)
         adjust_grid = 0.0 
        end if
        end if
        
        ;BPR END
      end if
      if ( mpres@parent_id(idom) .ge. 2) then
        ; corner value
        nd = mpres@parent_id(idom)
        ;BPR BEGIN
        ;i_points = ((mpres@e_we(idom)-1)/mpres@parent_grid_ratio(idom))
        ;j_points = ((mpres@e_sn(idom)-1)/mpres@parent_grid_ratio(idom))
        i_points = ((mpres@e_we(idom)-2)/(1.0*mpres@parent_grid_ratio(idom)))
        j_points = ((mpres@e_sn(idom)-2)/(1.0*mpres@parent_grid_ratio(idom)))
        goffset = 0.5*(1-(1.0/(1.0*mpres@parent_grid_ratio(idom))))
        ai_start = mpres@i_parent_start(idom)*1.0-goffset
        aj_start = mpres@j_parent_start(idom)*1.0-goffset
        ;ai_start = mpres@i_parent_start(idom)*1.0
        ;aj_start = mpres@j_parent_start(idom)*1.0

        if(grid_to_plot.eq.0) then
         adjust_grid = 0.0 
        else if(grid_to_plot.eq.1) then
         adjust_grid = 0.5/(1.0*mpres@parent_grid_ratio(idom)) 
        else 
         print("ERROR: Invalid value for grid_to_plot = "+grid_to_plot)
         adjust_grid = 0.0 
        end if
        end if

        do while ( nd .gt. 1)
          ;Note that nd-1 is used in the following because the WPS namelist is
          ;one-based but arrays in NCL are zero-based
          goffset = 0.5*(1-(1.0/(1.0*mpres@parent_grid_ratio(nd-1))))
          ;ai_start = ai_start/mpres@parent_grid_ratio(nd-1) + mpres@i_parent_start(nd-1)
          ;aj_start = aj_start/mpres@parent_grid_ratio(nd-1) + mpres@j_parent_start(nd-1)
          ai_start = (ai_start-1)/(1.0*mpres@parent_grid_ratio(nd-1)) + mpres@i_parent_start(nd-1)-goffset
          aj_start = (aj_start-1)/(1.0*mpres@parent_grid_ratio(nd-1)) + mpres@j_parent_start(nd-1)-goffset
          ;i_points = (i_points/mpres@parent_grid_ratio(nd-1))
          ;j_points = (j_points/mpres@parent_grid_ratio(nd-1))
          i_points = (i_points/(1.0*mpres@parent_grid_ratio(nd-1)))
          j_points = (j_points/(1.0*mpres@parent_grid_ratio(nd-1)))
          if(grid_to_plot.eq.0) then
           adjust_grid = 0.0 
          else if(grid_to_plot.eq.1) then
           adjust_grid = adjust_grid/(1.0*mpres@parent_grid_ratio(nd-1))
          else 
           print("ERROR: Invalid value for grid_to_plot = "+grid_to_plot)
           adjust_grid = 0.0 
          end if
          end if

          ;nd = nd - 1
          nd = mpres@parent_id(nd-1)
        end do
        ;i_start = tointeger(ai_start + .5 )
        ;j_start = tointeger(aj_start + .5 )
        i_start = ai_start
        j_start = aj_start
        ; end point
        ;i_end = i_points + i_start + 1
        ;j_end = j_points + j_start + 1
        i_end = i_points + i_start
        j_end = j_points + j_start
        ;BPR END
      end if

      ; get the four corners

      xx = i_start - adjust_grid
      yy = j_start - adjust_grid
      ;xx = int2flt(i_start)
      ;yy = int2flt(j_start)
      loc = wrf_ij_to_ll (xx,yy,res)
      lon_SW = loc(0)
      lat_SW = loc(1)

      xx = i_end + adjust_grid
      yy = j_start - adjust_grid
      ;xx = int2flt(i_end)
      ;yy = int2flt(j_start)
      loc = wrf_ij_to_ll (xx,yy,res)
      lon_SE = loc(0)
      lat_SE = loc(1)

      xx = i_start - adjust_grid
      yy = j_end + adjust_grid
      ;xx = int2flt(i_start)
      ;yy = int2flt(j_end)
      loc = wrf_ij_to_ll (xx,yy,res)
      lon_NW = loc(0)
      lat_NW = loc(1)

      ;xx = int2flt(i_end)
      ;yy = int2flt(j_end)
      xx = i_end + adjust_grid
      yy = j_end + adjust_grid
      ;BPR END
      loc = wrf_ij_to_ll (xx,yy,res)
      lon_NE = loc(0)
      lat_NE = loc(1)

      xbox = (/lon_SW, lon_SE, lon_NE, lon_NW, lon_SW /)
      ybox = (/lat_SW, lat_SE, lat_NE, lat_NW, lat_SW /)
      x_out = new(dimsizes(xbox),typeof(xbox))
      y_out = new(dimsizes(ybox),typeof(ybox))
      datatondc(mp, xbox, ybox, x_out, y_out)
      gsn_polyline_ndc(wks, x_out, y_out, lnres)

      idd = idom + 1
      dom_text = "d0"+idd
      if ( txres@txJust .eq. "BottomLeft" ) then
        gsn_text(wks,mp,dom_text,lon_NW,lat_NW,txres)
      else
        gsn_text_ndc(wks,dom_text,x_out(3)+0.01,y_out(3)-0.01,txres)
      end if

    end do

  end if

  return(mp)

end

;--------------------------------------------------------------------------------
undef("wrf_map_resources")
function wrf_map_resources(in_file[1]:file,map_args[1]:logical)   
local lat, lon, x1, x2, y1, y2, dims, ii, jj
begin
;
; This function sets resources for a WRF map plot, basing the projection on
; the MAP_PROJ attribute in the given file. It's intended to be callable
; by users who need to set mpXXXX resources for other plotting scripts.
;

; Set some resources depending on what kind of map projection is 
; chosen.
;
;   MAP_PROJ = 0 : "CylindricalEquidistant"
;   MAP_PROJ = 1 : "LambertConformal"
;   MAP_PROJ = 2 : "Stereographic"
;   MAP_PROJ = 3 : "Mercator"
;   MAP_PROJ = 6 : "Lat/Lon"

    if(isatt(in_file,"MAP_PROJ"))

;   CylindricalEquidistant
      if(in_file@MAP_PROJ .eq. 0)
        map_args@mpProjection          = "CylindricalEquidistant"
        map_args@mpGridSpacingF = 45
        map_args@mpCenterLatF   = get_res_value_keep(map_args, "mpCenterLatF", 0.0)
        if(isatt(in_file,"STAND_LON"))
          map_args@mpCenterLonF  = get_res_value_keep(map_args, "mpCenterLonF",in_file@STAND_LON)
        else
          if(isatt(in_file,"CEN_LON"))
            map_args@mpCenterLonF  = get_res_value_keep(map_args, "mpCenterLonF",in_file@CEN_LON)
          else
           print("ERROR: Found neither STAND_LON or CEN_LON in file")
          end if
        end if
      end if

;   LambertConformal projection
      if(in_file@MAP_PROJ .eq. 1)
        map_args@mpProjection               = "LambertConformal"
        map_args@mpLambertParallel1F = get_res_value_keep(map_args, "mpLambertParallel1F",in_file@TRUELAT1)
        map_args@mpLambertParallel2F = get_res_value_keep(map_args, "mpLambertParallel2F",in_file@TRUELAT2)
        if(isatt(in_file,"STAND_LON"))
          map_args@mpLambertMeridianF  = get_res_value_keep(map_args, "mpLambertMeridianF",in_file@STAND_LON)
        else
          if(isatt(in_file,"CEN_LON"))
            map_args@mpLambertMeridianF  = get_res_value_keep(map_args, "mpLambertMeridianF",in_file@CEN_LON)
          else
           print("ERROR: Found neither STAND_LON or CEN_LON in file")
          end if
        end if
      end if
  
;   Stereographic projection
      if(in_file@MAP_PROJ .eq. 2)
        map_args@mpProjection          = "Stereographic"
        map_args@mpCenterLatF   = get_res_value_keep(map_args, "mpCenterLatF", in_file@CEN_LAT)
        if(isatt(in_file,"STAND_LON"))
          map_args@mpCenterLonF  = get_res_value_keep(map_args, "mpCenterLonF",in_file@STAND_LON)
        else
          if(isatt(in_file,"CEN_LON"))
            map_args@mpCenterLonF  = get_res_value_keep(map_args, "mpCenterLonF",in_file@CEN_LON)
          else
           print("ERROR: Found neither STAND_LON or CEN_LON in file")
          end if
        end if
      end if
  
;   Mercator projection
      if(in_file@MAP_PROJ .eq. 3)
        map_args@mpProjection          = "Mercator"
        map_args@mpCenterLatF   = get_res_value_keep(map_args, "mpCenterLatF", 0.0)
        if(isatt(in_file,"STAND_LON"))
          map_args@mpCenterLonF  = get_res_value_keep(map_args, "mpCenterLonF",in_file@STAND_LON)
        else
          if(isatt(in_file,"CEN_LON"))
            map_args@mpCenterLonF  = get_res_value_keep(map_args, "mpCenterLonF",in_file@CEN_LON)
          else
           print("ERROR: Found neither STAND_LON or CEN_LON in file")
          end if
        end if
      end if
  
;    global WRF CylindricalEquidistant
      if(in_file@MAP_PROJ .eq. 6)
        map_args@mpProjection          = "CylindricalEquidistant"
        map_args@mpGridSpacingF = 45
        map_args@mpCenterLonF  = get_res_value_keep(map_args, "mpCenterLonF",in_file@CEN_LON)
        if( isatt(in_file,"POLE_LAT") ) then
          map_args@mpCenterRotF = get_res_value_keep(map_args, "mpCenterRotF", 90.0 - in_file@POLE_LAT) 
          delete(map_args@mpCenterLonF)
          calcen = -190.
          map_args@mpCenterLonF  = get_res_value_keep(map_args, "mpCenterLonF", calcen )
        end if
      end if
  
    else
  
      return(map_args)
  
    end if

    map_args@mpNestTime = get_res_value_keep(map_args, "mpNestTime",0)

      if(isfilevar(in_file,"XLAT"))
        lat = in_file->XLAT(map_args@mpNestTime,:,:)
        lon = in_file->XLONG(map_args@mpNestTime,:,:)
      else
        lat = in_file->XLAT_M(map_args@mpNestTime,:,:)
        lon = in_file->XLONG_M(map_args@mpNestTime,:,:)
      end if
      dims = dimsizes(lat)

      do ii = 0, dims(0)-1
      do jj = 0, dims(1)-1
        if ( lon(ii,jj) .lt. 0.0) then
          lon(ii,jj) = lon(ii,jj) + 360.
        end if
      end do
      end do

      map_args@start_lat = lat(0,0)
      map_args@start_lon = lon(0,0)
      map_args@end_lat   = lat(dims(0)-1,dims(1)-1)
      map_args@end_lon   = lon(dims(0)-1,dims(1)-1)


; Set some resources common to all map projections.
      map_args = set_mp_resources(map_args)

      if ( isatt(map_args,"ZoomIn") .and. map_args@ZoomIn ) then
        y1 = 0
        x1 = 0
        y2 = dims(0)-1
        x2 = dims(1)-1
        if ( isatt(map_args,"Ystart") ) then
          y1 = map_args@Ystart
          delete(map_args@Ystart)
        end if
        if ( isatt(map_args,"Xstart") ) then
          x1 = map_args@Xstart
          delete(map_args@Xstart)
        end if
        if ( isatt(map_args,"Yend") ) then
          if ( map_args@Yend .le. y2 ) then
            y2 = map_args@Yend
          end if
          delete(map_args@Yend)
        end if
        if ( isatt(map_args,"Xend") ) then
          if ( map_args@Xend .le. x2 ) then
            x2 = map_args@Xend
          end if
          delete(map_args@Xend)
        end if

        map_args@mpLeftCornerLatF      = lat(y1,x1)
        map_args@mpLeftCornerLonF      = lon(y1,x1)
        map_args@mpRightCornerLatF     = lat(y2,x2)
        map_args@mpRightCornerLonF     = lon(y2,x2)

        if ( map_args@mpRightCornerLonF .lt. 0.0 ) then
          map_args@mpRightCornerLonF  = map_args@mpRightCornerLonF + 360.0
        end if 

        delete(map_args@ZoomIn)
      end if

      return(map_args)
end

;--------------------------------------------------------------------------------
undef("wrf_map")
function wrf_map(wks[1]:graphic,in_file[1]:file,opt_args[1]:logical)   

begin
;
; This function creates a map plot, and bases the projection on
; the MAP_PROJ attribute in the given file.
;
;   1. Make a copy of the resource list, and call a function to set
;      some resources common to all map projections.
;
;   2. Determine the projection being used, and set resources based
;      on that projection.
;
;   3. Create the map plot, and draw and advance the frame
;      (if requested).

    if(opt_args.and.isatt(opt_args,"gsnDebugWriteFileName")) then
      wrf_debug_file = get_res_value(opt_args,"gsnDebugWriteFileName",  "")    
    end if

    opts = opt_args      ; Make a copy of the resource list
    opts  = True

;---Set some map resources based on parameters and variables in input file.
    opts = wrf_map_resources(in_file,opts)

    if(.not.isatt(opts,"mpProjection")) then
      print("wrf_map: Error: no MAP_PROJ attribute in input file")
      return(new(1,graphic))
    else
      projection = opts@mpProjection
    end if

; The default is not to draw the plot or advance the frame, and
; to maximize the plot in the frame.

  opts@gsnDraw       = get_res_value_keep(opts,"gsnDraw",     False)
  opts@gsnFrame      = get_res_value_keep(opts,"gsnFrame",    False)
  opts@gsnMaximize   = get_res_value_keep(opts,"gsnMaximize", True)

  delete_attrs(opts)                             ; Clean up.
  mp = gsn_map(wks,projection,opts)              ; Create map plot.

  if(isvar("wrf_debug_file")) then
    opts@mpProjection = projection
    write_wrf_debug_info(wks,False,False,wrf_debug_file,opts,"wrf_map")
  end if

  return(mp)                                     ; Return.

end

;--------------------------------------------------------------------------------

undef("wrf_map_overlays")
function wrf_map_overlays(in_file[1]:file, \
                          wks:graphic, \
                          plots[*]:graphic, \
                          opt_arg[1]:logical, \
                          opt_mp[1]:logical) 
 
; This procedure takes an array of plots and overlays them on a
; base plot - map background.
;
; It will advance the plot and cleanup, unless you set the
; PanelPlot resource to True.
;
;  Attributes recognized by this procedure:
;     FramePlot
;     PanelPlot
;     NoTitles                  (don't do any titles) 
;     CommonTitle & PlotTitle is used to overwrite field titles
;        CommonTitle will supercede NoTitles
;     LatLonOverlay
;
; If FramePlot False, then Draw the plot but do not Frame.
; In this case a user want to add to the drawing, and will
; have to advance the Frame manually in the script.
;
; If the "NoTitles" attribute exists and is set True, then
; don't create the top-left titles, and leave the main titles alone.
; This resource can be useful if you are planning to panel
; the plots.
;
; If PanelPlot is set to True, then this flags to wrf_map_overlays
; that these plots are going to be eventually paneled (likely
; by gsn_panel), and hence 1) draw and frame should not be called
; (unless gsnDraw and/or gsnFrame are explicitly set to True),
; and 2) the overlays and titles should not be removed with
; NhlRemoveOverlay and NhlRemoveAnnotation.
;
; If LatLonOverlay is set to True, then this means the user is
; using the 2D lat/lon coordinates to do the overlay, and hence
; tfDoNDCOverlay should not be set to True. (The default is False.)
;
begin

  opts     = opt_arg         ; Make a copy of the resource lists
  opt_mp_2 = opt_mp      

  if(opts.and.isatt(opts,"gsnDebugWriteFileName")) then
    opt_mp_2@gsnDebugWriteFileName = get_res_value(opts, \
                                            "gsnDebugWriteFileName",  "")    
    wrf_debug_file = opt_mp_2@gsnDebugWriteFileName
  end if

  ; Let's make the map first
  base = wrf_map(wks,in_file,opt_mp_2)

  no_titles  = get_res_value(opts,"NoTitles",False)     ; Do we want field titles?
  com_title  = get_res_value(opts,"CommonTitle",False)     ; Do we have a common title?
  if ( com_title ) then
    plot_title = get_res_value(opts,"PlotTitle","  ")
    no_titles = True
  end if
  
  call_draw  = True
  call_frame = get_res_value(opts,"FramePlot",True)     ; Do we want to frame the plot?
  panel_plot = get_res_value(opts,"PanelPlot",False)    ; Are we paneling?
  latlon_overlay = get_res_value(opts,"LatLonOverlay",False) ; Lat/lon Overlay?
  opts@gsnMaximize = get_res_value_keep(opts,"gsnMaximize", True)

  nplots = dimsizes(plots)
;  font_color = "Black"

  do i=0,nplots-1
    if(.not.ismissing(plots(i))) then
;      class_name = NhlClassName(plots(i))
;      print(class_name)
;      if(class_name.eq."contourPlotClass") then
;        getvalues plots(i)
;          "cnFillOn"    : fill_on
;          "cnLineColor" : line_color
;        end getvalues
;        if (.not.fill_on) then
;          font_color = line_color      
;        end if       
;      end if
      if(.not.no_titles) then
        getvalues plots(i)
          "tiMainString" : SubTitle
        end getvalues
        if(i.eq.0) then
          SubTitles = SubTitle
        else
          SubTitles = SubTitles + "~C~" + SubTitle
        end if
      end if
      if(com_title .and. i .eq. nplots-1) then
        getvalues plots(i)
          "tiMainString" : SubTitle
        end getvalues
        SubTitles = plot_title
      end if
      if(.not.latlon_overlay) then
        setvalues plots(i)
          "tfDoNDCOverlay" : True
          "tiMainOn"       : False
        end setvalues
      else
        setvalues plots(i)
          "tiMainOn"       : False
        end setvalues
      end if
      overlay(base,plots(i))
    else
      print("wrf_map_overlays: Warning: overlay plot #" + i + " is not valid.")
    end if
  end do

  if(.not.no_titles .or. com_title) then
    font_height = get_res_value_keep(opts,"FontHeightF",0.01)
    txt = create "map_titles" textItemClass wks
      "txString"      : SubTitles
      "txFontHeightF" : font_height
     ;"txFontColor"   : font_color
    end create
    anno = NhlAddAnnotation(base,txt)
    setvalues anno
      "amZone"           : 3
      "amJust"           : "BottomLeft"
      "amSide"           : "Top"
      "amParallelPosF"   : 0.005
      "amOrthogonalPosF" : 0.03
      "amResizeNotify"   : False
    end setvalues
    base@map_titles = anno
  end if
;
; gsnDraw and gsnFrame default to False if panel plot.
;
  if(panel_plot) then
    call_draw = False
    call_frame= False
  end if


  opts@gsnDraw     = get_res_value_keep(opts,"gsnDraw",     call_draw)
  opts@gsnFrame    = get_res_value_keep(opts,"gsnFrame",    call_frame)

  draw_and_frame(wks,base,opts@gsnDraw,opts@gsnFrame,False, \
                 opts@gsnMaximize)

  if(.not.panel_plot) then
    do i=0,nplots-1
      if(.not.ismissing(plots(i))) then
        NhlRemoveOverlay(base,plots(i),False)
      else
        print("wrf_remove_map_overlays: Warning: overlay plot #" + i + " is not valid.")
        print("                        Nothing to remove.")
      end if
    end do
  end if

  if(isvar("wrf_debug_file")) then
    write_wrf_debug_script(wks,wrf_debug_file,"wrf_map_overlays")
  end if

  if(.not.no_titles.and..not.panel_plot) then
    if(isatt(base,"map_titles")) then
      NhlRemoveAnnotation(base,base@map_titles)
      delete(base@map_titles)
    end if
  end if

return(base)
end

;--------------------------------------------------------------------------------

undef("wrf_overlays")
function wrf_overlays(in_file[1]:file, \
                     wks:graphic, plots[*]:graphic, \
                     opt_arg[1]:logical)
 
; This procedure takes an array of plots and overlays them.
;
; It will advance the plot and cleanup, unless you set the
; PanelPlot resource to True.
; 
;  Attributes recognized by this procedure:
;     FramePlot
;     PanelPlot
;     NoTitles                  (don't do any titles) 
;     CommonTitle & PlotTile is used to overwrite field titles
;        CommonTitle will super-seed NoTitles
;
; If FramePlot False, then Draw the plot but do not Frame.
; In this case a user want to add to the drawing, and will
; have to advance the Frame manually in the script.
;
; If the "NoTitles" attribute exists and is set True, then
; don't create the top-left titles, and leave the main titles alone.
; This resource can be useful if you are planning to panel
; the plots.
;
; If PanelPlot is set to True, then this flags to wrf_overlays
; that these plots are going to be eventually paneled (likely
; by gsn_panel), and hence 1) draw and frame should not be called
; (unless gsnDraw and/or gsnFrame are explicitly set to True),
; and 2) the overlays and titles should not be removed with
; NhlRemoveOverlay and NhlRemoveAnnotation.
;
; If LatLonOverlay is set to True, then this means the user is
; using the 2D lat/lon coordinates to do the overlay, and hence
; tfDoNDCOverlay should not be set to True. (The default is False.)
;
begin
  opts = opt_arg      ; Make a copy of the resource list.

  no_titles  = get_res_value(opts,"NoTitles",False)     ; Do we want field titles?
  com_title  = get_res_value(opts,"CommonTitle",False)     ; Do we have a common title?
  latlon_overlay = get_res_value(opts,"LatLonOverlay",False) ; Lat/lon Overlay?
  if ( com_title ) then
    plot_title = get_res_value(opts,"PlotTitle","  ")
    no_titles = True
  end if

  call_draw  = True
  call_frame = get_res_value(opts,"FramePlot",True)     ; Do we want to frame the plot?
  panel_plot = get_res_value(opts,"PanelPlot",False)    ; Are we paneling?
  opts@gsnMaximize = get_res_value_keep(opts,"gsnMaximize", True)

  nplots = dimsizes(plots)
    
  base = plots(0)
  if(.not.no_titles) then
    getvalues plots(0)
      "tiMainString" : SubTitle
    end getvalues
    SubTitles = SubTitle
    if(.not.latlon_overlay) then
      setvalues plots(0)
        "tfDoNDCOverlay" : True
        "tiMainOn"       : False
      end setvalues
    else
      setvalues plots(0)
        "tiMainOn"       : False
      end setvalues
    end if
  else
    if(.not.latlon_overlay) then
      setvalues plots(0)
        "tfDoNDCOverlay" : True
      end setvalues
    end if
  end if

  if (nplots.eq.1) then 
    blank = create "BlankPlot" logLinPlotClass wks
      ;"cnConstFLabelOn" : False
    end create
    overlay(base,blank)
  end if

  do i=1,nplots-1
    if(.not.ismissing(plots(i))) then
      if(.not.no_titles) then
        getvalues plots(i)
          "tiMainString" : SubTitle
        end getvalues
        if(i.eq.0) then
          SubTitles = SubTitle
        else
          SubTitles = SubTitles + "~C~" + SubTitle
        end if
      end if
      if(com_title .and. i .eq. nplots-1) then
        getvalues plots(i)
          "tiMainString" : SubTitle
        end getvalues
        SubTitles = plot_title
      end if
      if(.not.latlon_overlay) then
        setvalues plots(i)
          "tfDoNDCOverlay" : True
          "tiMainOn"       : False
        end setvalues
      else
        setvalues plots(i)
          "tiMainOn"       : False
        end setvalues
      end if
      overlay(base,plots(i))
    else
      print("wrf_overlays: Warning: overlay plot #" + i + " is not valid.")
    end if
  end do

  if(.not.no_titles .or. com_title) then
    font_height = get_res_value_keep(opts,"FontHeightF",0.01)

    txt = create "map_titles" textItemClass wks
      "txString"      : SubTitles
      "txFontHeightF" : font_height
    end create
    anno = NhlAddAnnotation(base,txt)
    setvalues anno
      "amZone"           : 3
      "amJust"           : "BottomLeft"
      "amSide"           : "Top"
      "amParallelPosF"   : 0.005
      "amOrthogonalPosF" : 0.03
      "amResizeNotify"   : False
    end setvalues
    base@map_titles = anno
  end if

;
; gsnDraw and gsnFrame should default to True if not a panel plot.
;  
  if(panel_plot) then
    call_draw = False
    call_frame= False
  end if

  opts@gsnDraw     = get_res_value_keep(opts,"gsnDraw",     call_draw)
  opts@gsnFrame    = get_res_value_keep(opts,"gsnFrame",    call_frame)
  opts@gsnMaximize = get_res_value_keep(opts,"gsnMaximize", True)

  draw_and_frame(wks,base,opts@gsnDraw,opts@gsnFrame,False, \
                 opts@gsnMaximize)

  if(.not.no_titles.and..not.panel_plot) then
    NhlRemoveAnnotation(base,base@map_titles)
    delete(base@map_titles)
  end if

  if(.not.panel_plot) then
    if ( nplots .ge. 2 ) then
      do i=1,nplots-1
        if(.not.ismissing(plots(i))) then
          NhlRemoveOverlay(base,plots(i),False)
        else
          print("wrf_remove_overlays: Warning: overlay plot #" + i + " is not valid.")
          print("                        Nothing to remove.")
        end if
      end do
    end if
  end if

return(base)
end

;--------------------------------------------------------------------------------

undef("wrf_map_zoom")
function wrf_map_zoom(wks[1]:graphic,in_file[1]:file,opt_args[1]:logical, \
                      y1:integer,y2:integer,x1:integer,x2:integer)

; As of version 5.0.1, this routine is redundant. Use the special "ZoomIn"
; resource in wrf_map to accomplish the same thing. This function is
; being kept for backwards capability. There should be no need for it
; except to run old WRF-NCL codes.  Do not make any changes to it except
; possibly to fix bugs.
;
begin
      print("wrf_map_zoom: Warning: This function is obsolete. Consider using")
      print("                       the 'ZoomIn' resource in wrf_map instead.")
      if(isfilevar(in_file,"XLAT"))
        lat = in_file->XLAT(0,:,:)
        lon = in_file->XLONG(0,:,:)
      else
        lat = in_file->XLAT_M(0,:,:)
        lon = in_file->XLONG_M(0,:,:)
      end if
      opts  = opt_args      ; Make a copy of the resource list
      opts  = True
      opts@mpLeftCornerLatF      = lat(y1,x1)
      opts@mpLeftCornerLonF      = lon(y1,x1)
      opts@mpRightCornerLatF     = lat(y2,x2)
      opts@mpRightCornerLonF     = lon(y2,x2)
      mz = wrf_map(wks,in_file,opts)
      return(mz)
end

;--------------------------------------------------------------------------------

undef("wrf_map_overlay")
procedure wrf_map_overlay(wks:graphic,base[1]:graphic, \
                          plots[*]:graphic, \
                          opt_arg[1]:logical)
 
; As of version 5.0.1, this procedure is obsolete. Use wrf_map_overlays
; instead. It is being kept for backwards capability. Do not make any
; changes to it except possibly to fix bugs.
;
; This procedure takes an array of plots and overlays them on a
; base plot - map background.
;
; It will advance the plot and cleanup, unless you set the
; PanelPlot resource to True.
;
;  Attributes recognized by this procedure:
;     NoTitles                  (don't do any titles) 
;     PanelPlot
;
; If the "NoTitles" attribute exists and is set True, then
; don't create the top-left titles, and leave the main titles alone.
; This resource can be useful if you are planning to panel
; the plots.
;
; If PanelPlot is set to True, then this flags to wrf_map_overlay
; that these plots are going to be eventually paneled (likely
; by gsn_panel), and hence 1) draw and frame should not be called
; (unless gsnDraw and/or gsnFrame are explicitly set to True),
; and 2) the overlays and titles should not be removed with
; NhlRemoveOverlay and NhlRemoveAnnotation.
;
begin
  print("wrf_map_overlay: Warning: This procedure is obsolete. Consider" )
  print("                          using wrf_map_overlays instead.")

  opts = opt_arg      ; Make a copy of the resource list
  opts = True

  if(opts.and.isatt(opts,"NoTitles").and.opts@NoTitles) then
    no_titles = True
  else
    no_titles = False
  end if

  panel_plot = get_res_value(opts,"PanelPlot",False)    ; Are we paneling?
  latlon_overlay = get_res_value(opts,"LatLonOverlay",False) ; Lat/lon Overlay?

  nplots = dimsizes(plots)
;  font_color = "Black"

  do i=0,nplots-1
    if(.not.ismissing(plots(i))) then
;      class_name = NhlClassName(plots(i))
;      print(class_name)
;      if(class_name.eq."contourPlotClass") then
;        getvalues plots(i)
;          "cnFillOn"    : fill_on
;          "cnLineColor" : line_color
;        end getvalues
;        if (.not.fill_on) then
;          font_color = line_color      
;        end if       
;      end if
      if(.not.no_titles) then
        getvalues plots(i)
          "tiMainString" : SubTitle
        end getvalues
        if(i.eq.0) then
          SubTitles = SubTitle
        else
          SubTitles = SubTitles + "~C~" + SubTitle
        end if
        if(.not.latlon_overlay) then
    	  setvalues plots(i)
            "tfDoNDCOverlay" : True
            "tiMainOn"       : False
          end setvalues
        else
    	  setvalues plots(i)
            "tiMainOn"       : False
          end setvalues
        end if
      else
        if(.not.latlon_overlay) then
  	  setvalues plots(i)
            "tfDoNDCOverlay" : True
          end setvalues
        end if
      end if
      overlay(base,plots(i))
    else
      print("wrf_map_overlay: Warning: overlay plot #" + i + " is not valid.")
    end if
  end do

  if(.not.no_titles) then
    font_height = get_res_value_keep(opts,"FontHeightF",0.01)
    txt = create "map_titles" textItemClass wks
      "txString"      : SubTitles
      "txFontHeightF" : font_height
     ;"txFontColor"   : font_color
    end create
    anno = NhlAddAnnotation(base,txt)
    setvalues anno
      "amZone"           : 3
      "amJust"           : "BottomLeft"
      "amSide"           : "Top"
      "amParallelPosF"   : 0.005
      "amOrthogonalPosF" : 0.03
      "amResizeNotify"   : False
    end setvalues
    base@map_titles = anno
  end if
;
; gsnDraw and gsnFrame should default to True if not a panel plot.
; gsnFrame will default to False if opt_arg is False.
;
  if(panel_plot.or..not.opt_arg) then
    call_frame = False
  else
    call_frame = True
  end if
  if(panel_plot) then
    call_draw = False
  else
    call_draw = True
  end if
  opts@gsnDraw     = get_res_value_keep(opts,"gsnDraw",     call_draw)
  opts@gsnFrame    = get_res_value_keep(opts,"gsnFrame",    call_frame)
  opts@gsnMaximize = get_res_value_keep(opts,"gsnMaximize", True)

  draw_and_frame(wks,base,opts@gsnDraw,opts@gsnFrame,False, \
                 opts@gsnMaximize)

  if(.not.panel_plot) then
    do i=0,nplots-1
      if(.not.ismissing(plots(i))) then
        NhlRemoveOverlay(base,plots(i),False)
      else
        print("wrf_remove_map_overlay: Warning: overlay plot #" + i + " is not valid.")
        print("                        Nothing to remove.")
      end if
    end do
  end if

  if(.not.no_titles.and..not.panel_plot) then
    if(isatt(base,"map_titles")) then
      NhlRemoveAnnotation(base,base@map_titles)
      delete(base@map_titles)
    end if
  end if
end

;--------------------------------------------------------------------------------

undef("wrf_overlay")
procedure wrf_overlay(wks:graphic, plots[*]:graphic, \
                          opt_arg[1]:logical)
 
; As of version 5.0.1, this procedure is obsolete. Use wrf_overlays
; instead. It is being kept for backwards capability. Do not make any
; changes to it except possibly to fix bugs.
;
; This procedure takes an array of plots and overlays them.
;
; It will advance the plot and cleanup, unless you set the
; PanelPlot resource to True.
;
;  Attributes recognized by this procedure:
;     NoTitles                  (don't do any titles) 
;     PanelPlot
;
; If the "NoTitles" attribute exists and is set True, then
; don't create the top-left titles, and leave the main titles alone.
; This resource can be useful if you are planning to panel
; the plots.
;
; If PanelPlot is set to True, then this flags to wrf_overlay
; that these plots are going to be eventually paneled (likely
; by gsn_panel), and hence 1) draw and frame should not be called
; (unless gsnDraw and/or gsnFrame are explicitly set to True),
; and 2) the overlays and titles should not be removed with
; NhlRemoveOverlay and NhlRemoveAnnotation.
;
; If LatLonOverlay is set to True, then this means the user is
; using the 2D lat/lon coordinates to do the overlay, and hence
; tfDoNDCOverlay should not be set to True. (The default is False.)
;
begin
  print("wrf_overlay: Warning: This procedure is obsolete. Consider using")
  print("                      wrf_overlays instead.")

  opts = opt_arg      ; Make a copy of the resource list.
  opts = True

  if(opts.and.isatt(opts,"NoTitles").and.opts@NoTitles) then
    no_titles = True
  else
    no_titles = False
  end if

  panel_plot = get_res_value(opts,"PanelPlot",False)    ; Are we paneling?
  latlon_overlay = get_res_value(opts,"LatLonOverlay",False)  ; lat/lon overlay?

  nplots = dimsizes(plots)
    
  base = plots(0)
  if(.not.no_titles) then
    getvalues plots(0)
      "tiMainString" : SubTitle
    end getvalues
    SubTitles = SubTitle
    if(.not.latlon_overlay) then
      setvalues plots(0)
        "tfDoNDCOverlay" : True
        "tiMainOn"       : False
      end setvalues
    else
      setvalues plots(0)
        "tiMainOn"       : False
      end setvalues
    end if
  else
    setvalues plots(0)
      "tfDoNDCOverlay" : True
    end setvalues
  end if

  if (nplots.eq.1) then 
    blank = create "BlankPlot" logLinPlotClass wks
      ;"cnConstFLabelOn" : False
    end create
    overlay(base,blank)
  end if

  do i=1,nplots-1
    if(.not.ismissing(plots(i))) then
      if(.not.no_titles) then
        getvalues plots(i)
          "tiMainString" : SubTitle
        end getvalues
        SubTitles = SubTitles + "~C~" + SubTitle
        if(.not.latlon_overlay) then
          setvalues plots(i)
            "tfDoNDCOverlay" : True
            "tiMainOn"       : False
          end setvalues
        else
          setvalues plots(i)
            "tiMainOn"       : False
          end setvalues
        end if
      else
        if(.not.latlon_overlay) then
          setvalues plots(i)
            "tfDoNDCOverlay" : True
          end setvalues
        end if
      end if
      overlay(base,plots(i))
    else
      print("wrf_overlay: Warning: overlay plot #" + i + " is not valid.")
    end if
  end do

  if(.not.no_titles) then
    font_height = get_res_value_keep(opts,"FontHeightF",0.01)

    txt = create "map_titles" textItemClass wks
      "txString"      : SubTitles
      "txFontHeightF" : font_height
    end create
    anno = NhlAddAnnotation(base,txt)
    setvalues anno
      "amZone"           : 3
      "amJust"           : "BottomLeft"
      "amSide"           : "Top"
      "amParallelPosF"   : 0.005
      "amOrthogonalPosF" : 0.03
      "amResizeNotify"   : False
    end setvalues
    base@map_titles = anno
  end if

;
; gsnDraw and gsnFrame should default to True if not a panel plot.
; gsnFrame will default to False if opt_arg is False.
;
  if(panel_plot.or..not.opt_arg) then
    call_frame = False
  else
    call_frame = True
  end if
  if(panel_plot) then
    call_draw = False
  else
    call_draw = True
  end if
  opts@gsnDraw     = get_res_value_keep(opts,"gsnDraw",     call_draw)
  opts@gsnFrame    = get_res_value_keep(opts,"gsnFrame",    call_frame)
  opts@gsnMaximize = get_res_value_keep(opts,"gsnMaximize", True)

  draw_and_frame(wks,base,opts@gsnDraw,opts@gsnFrame,False, \
                 opts@gsnMaximize)

  if(.not.no_titles.and..not.panel_plot) then
    NhlRemoveAnnotation(base,base@map_titles)
    delete(base@map_titles)
  end if

  if(.not.panel_plot) then
    if ( nplots .ge. 2 ) then
      do i=1,nplots-1
        if(.not.ismissing(plots(i))) then
          NhlRemoveOverlay(base,plots(i),False)
        else
          print("wrf_remove_overlay: Warning: overlay plot #" + i + " is not valid.")
          print("                        Nothing to remove.")
        end if
      end do
    end if
  end if
end

;--------------------------------------------------------------------------------

undef("add_white_space")
function add_white_space(str:string,maxlen:integer)

begin
  cstr = stringtochar(str)
  len  = dimsizes(cstr)-1
  ws   = ""
  if(len.lt.maxlen) then
    do i=1,maxlen-len
      ws = ws + " "
    end do
  end if
  return(ws)

end

;--------------------------------------------------------------------------------

undef("print_opts")
procedure print_opts(opts_name,opts,debug)

begin
  if(.not.debug) then
    return
  end if
  varatts = getvaratts(opts)
;
; Sort attributes alphabetically/
;
  sqsort(varatts)
;
; Get length of longest attribute name.
;
  cvaratts = stringtochar(varatts)
  cmaxlen  = dimsizes(cvaratts(0,:))-1

  print("------------------------------------------------------------")
  print(opts_name + "...")    ; Print name of option variable.
;
; Loop through each attribute in the list. If its value is an array,
; then print out the array with '(/' and '/)' around it.
;
; If the value is a string, then put ticks (') around each string.
;
  do i=0,dimsizes(varatts)-1
    x = opts@$varatts(i)$
;
; Use add_white_space to make sure all the equal signs line up.
;
    tmp_str = "    " + varatts(i) + \
              add_white_space(varatts(i),cmaxlen) + " = "
;
; Check if attribute is an array.
;    
    if(dimsizes(x).gt.1) then
      tmp_str = tmp_str + "(/"
      do j=0,dimsizes(x)-1
        if(typeof(x(j)).eq."string") then
          tmp_str = tmp_str + "'" + x(j) + "'"
        else
          tmp_str = tmp_str + x(j)
        end if
        if(j.lt.dimsizes(x)-1) then
          tmp_str = tmp_str + ","
        else
          tmp_str = tmp_str + "/)"
        end if
      end do
    else      if(typeof(x).eq."string") then
        tmp_str = tmp_str + "'" + x + "'"
      else
        tmp_str = tmp_str + x
      end if
    end if
    print("" + tmp_str)
    delete(x)
  end do

end

;--------------------------------------------------------------------------------

undef("print_header")
procedure print_header(icount:integer,debug)
begin
  icount = icount + 1
  if(.not.debug) then
    return
  end if
  print("END plot #" + icount)
  print("------------------------------------------------------------")

end

;--------------------------------------------------------------------------------