wrf-fire /wrfv2_fire/external/io_grib2/io_grib2.F

Language Fortran 77 Lines 4531
MD5 Hash b4b51a64af2749be95dcb7ea22ea3fb5 Estimated Cost $93,859 (why?)
Repository git://github.com/jbeezley/wrf-fire.git View Raw File View Project SPDX
   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
!*-----------------------------------------------------------------------------
!*
!*  Todd Hutchinson
!*  WSI
!*  400 Minuteman Road
!*  Andover, MA     01810
!*  thutchinson@wsi.com
!*
!*  August, 2005
!*-----------------------------------------------------------------------------

!*
!* This io_grib2 API is designed to read WRF input and write WRF output data
!*   in grib version 2 format.  
!*


#include "wrf_projection.h"

module gr2_data_info

!*
!* This module will hold data internal to this I/O implementation.
!*   The variables will be accessible by all functions (provided they have a
!*   "USE gr2_data_info" line).
!*

  USE grib2tbls_types

  integer                , parameter       :: FATAL            = 1
  integer                , parameter       :: DEBUG            = 100
  integer                , parameter       :: DateStrLen       = 19
  integer                , parameter       :: maxMsgSize       = 300
  integer                , parameter       :: firstFileHandle  = 8
  integer                , parameter       :: maxFileHandles   = 200
  integer                , parameter       :: maxLevels        = 1000
  integer                , parameter       :: maxSoilLevels    = 100
  integer                , parameter       :: maxDomains       = 500
  character(200)                           :: mapfilename = 'grib2map.tbl'

  integer                , parameter       :: JIDSSIZE = 13
  integer                , parameter       :: JPDTSIZE = 15
  integer                , parameter       :: JGDTSIZE = 30

  logical                                  :: grib2map_table_filled = .FALSE.

  logical                                  :: WrfIOnotInitialized = .true.

  integer, dimension(maxDomains)           :: domains
  integer                                  :: max_domain = 0

  character*24                             :: StartDate = ''
  character*24                             :: InputProgramName = ''
  real                                     :: timestep
  integer                                  :: full_xsize, full_ysize
  REAL,          dimension(maxSoilLevels)  :: soil_depth, soil_thickness
  REAL,          dimension(maxLevels)      :: half_eta, full_eta

  integer                                  :: wrf_projection
  integer                                  :: background_proc_id
  integer                                  :: forecast_proc_id
  integer                                  :: production_status
  integer                                  :: compression
  real                                     :: center_lat, center_lon
  real                                     :: dx,dy
  real                                     :: truelat1, truelat2
  real                                     :: proj_central_lon

  TYPE :: HandleVar
     character, dimension(:), pointer      :: fileindex(:)
     integer                               :: CurrentTime
     integer                               :: NumberTimes
     integer                               :: sizeAllocated = 0
     logical                               :: write = .FALSE.
     character (DateStrLen), dimension(:),allocatable  :: Times(:)
     logical                               :: committed, opened, used
     character*128                         :: DataFile
     integer                               :: FileFd
     integer                               :: FileStatus
     integer                               :: recnum
     real                                  :: last_scalar_time_written
  ENDTYPE
  TYPE (HandleVar), dimension(maxFileHandles),SAVE :: fileinfo

  character(len=30000), dimension(maxFileHandles) :: td_output
  character(len=30000), dimension(maxFileHandles) :: ti_output
  character(len=30000), dimension(maxFileHandles) :: scalar_output
  character(len=30000), dimension(maxFileHandles) :: global_input = ''
  character(len=30000), dimension(maxFileHandles) :: scalar_input = ''

  real                                     :: last_fcst_secs
  real                                     :: fcst_secs

  logical                                  :: half_eta_init       = .FALSE.
  logical                                  :: full_eta_init       = .FALSE.
  logical                                  :: soil_thickness_init = .FALSE.
  logical                                  :: soil_depth_init     = .FALSE.

end module gr2_data_info


!*****************************************************************************

subroutine ext_gr2_ioinit(SysDepInfo,Status)

  USE gr2_data_info
  implicit none
#include "wrf_status_codes.h"
#include "wrf_io_flags.h"
  CHARACTER*(*), INTENT(IN) :: SysDepInfo
  integer ,intent(out) :: Status
  integer :: i
  CHARACTER (LEN=300) :: wrf_err_message

  call wrf_debug ( DEBUG , 'Entering ext_gr2_ioinit')

  do i=firstFileHandle, maxFileHandles
        fileinfo(i)%used = .false.
        fileinfo(i)%committed = .false.
        fileinfo(i)%opened = .false.
        td_output(i) = ''
        ti_output(i) = ''
        scalar_output(i) = ''
  enddo
  domains(:) = -1
  last_fcst_secs = -1.0

  fileinfo(1:maxFileHandles)%FileStatus = WRF_FILE_NOT_OPENED
  WrfIOnotInitialized = .false.

  Status = WRF_NO_ERR

  return
end subroutine ext_gr2_ioinit

!*****************************************************************************

subroutine ext_gr2_ioexit(Status)

  USE gr2_data_info
  implicit none
#include "wrf_status_codes.h"
  integer ,intent(out) :: Status

  call wrf_debug ( DEBUG , 'Entering ext_gr2_ioexit')

  Status = WRF_NO_ERR

  if (grib2map_table_filled) then
     call free_grib2map()
     grib2map_table_filled = .FALSE.
  endif

  return
end subroutine ext_gr2_ioexit

!*****************************************************************************

SUBROUTINE ext_gr2_open_for_read_begin ( FileName , Comm_compute, Comm_io, &
     SysDepInfo, DataHandle , Status )

  USE gr2_data_info
  USE grib2tbls_types
  USE grib_mod
  IMPLICIT NONE
#include "wrf_status_codes.h"
#include "wrf_io_flags.h"
  CHARACTER*(*) :: FileName
  INTEGER ,       INTENT(IN)  :: Comm_compute , Comm_io
  CHARACTER*(*) :: SysDepInfo
  INTEGER ,       INTENT(OUT) :: DataHandle
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER (LEN=maxMsgSize) :: msg

  integer :: center, subcenter, MasterTblV, &
       LocalTblV, Disc, Category, ParmNum, DecScl, BinScl

  integer :: fields_to_skip
  integer :: JIDS(JIDSSIZE), JPDTN, JPDT(JPDTSIZE), JGDTN, &
       JGDT(JGDTSIZE)
  logical :: UNPACK
  character*(100) :: VarName
  type(gribfield) :: gfld
  integer         :: idx
  character(len=DateStrLen) :: theTime,refTime
  integer         :: time_range_convert(13)
  integer         :: fcstsecs
  integer         :: endchar
  integer         :: ierr

  INTERFACE
     Subroutine load_grib2map (filename, message, status)
       USE grib2tbls_types
       character*(*), intent(in)                   :: filename
       character*(*), intent(inout)                :: message
       integer      , intent(out)                  :: status
     END subroutine load_grib2map
  END INTERFACE

  call wrf_debug ( DEBUG , &
       'Entering ext_gr2_open_for_read_begin, opening '//trim(FileName))

  CALL gr2_get_new_handle(DataHandle)

  !
  ! Open grib file
  !
  if (DataHandle .GT. 0) then
     
     call baopenr(DataHandle,trim(FileName),status)

     if (status .ne. 0) then
        Status = WRF_ERR_FATAL_BAD_FILE_STATUS
     else
        fileinfo(DataHandle)%opened = .true.
        fileinfo(DataHandle)%DataFile = TRIM(FileName)
        fileinfo(DataHandle)%FileStatus = WRF_FILE_OPENED_NOT_COMMITTED
!        fileinfo(DataHandle)%CurrentTime = 1
     endif
  else
     Status = WRF_WARN_TOO_MANY_FILES
     return
  endif
 
  fileinfo(DataHandle)%recnum = -1

  !
  ! Fill up the grib2tbls structure from data in the grib2map file.
  !
  if (.NOT. grib2map_table_filled) then
     grib2map_table_filled = .TRUE.
     CALL load_grib2map(mapfilename, msg, status)
     if (status .ne. 0) then
        call wrf_message(trim(msg))
        Status = WRF_ERR_FATAL_BAD_FILE_STATUS
        return
     endif
  endif


  !
  ! Get the parameter info for metadata
  !
  VarName = "WRF_GLOBAL"
  CALL get_parminfo(VarName, center, subcenter, MasterTblV, &
       LocalTblV, Disc, Category, ParmNum, DecScl, BinScl, status)
  if (status .ne. 0) then
     write(msg,*) 'Could not find parameter for '//   &
          trim(VarName)//'   Skipping output of '//trim(VarName)
     call wrf_message(trim(msg))
     Status =  WRF_GRIB2_ERR_GRIB2MAP
     return
  endif

  !
  ! Read the metadata
  !
  fields_to_skip = 0
  
  !
  ! First, set all values to the wildcard, then reset values that we wish
  !    to specify.
  !
  call gr2_g2lib_wildcard(JIDS, JPDT, JGDT)
  
  JIDS(1) = center
  JIDS(2) = subcenter
  JIDS(3) = MasterTblV
  JIDS(4) = LocalTblV
  JIDS(5) = 1           ! Indicates that time is "Start of Forecast"
  JIDS(13) = 1          ! Type of processed data (1 for forecast products)
  
  JPDTN = 0             ! Product definition template number
  JPDT(1) = Category
  JPDT(2) = ParmNum
  JPDT(3) = 2           ! Generating process id
  JPDT(9) = 0           ! Forecast time 

  JGDTN    = -1         ! Indicates that any Grid Display Template is a match
  
  UNPACK   = .FALSE.    ! Dont unpack bitmap and data values

  CALL GETGB2(DataHandle, DataHandle, fields_to_skip, -1, Disc, JIDS, JPDTN, &
       JPDT, JGDTN, JGDT, UNPACK, fileinfo(DataHandle)%recnum, gfld, status)
  if (status .ne. 0) then
     if (status .eq. 99) then
        write(msg,*)'Could not find metadata field named '//trim(VarName)
     else
        write(msg,*)'Retrieving grib field '//trim(VarName)//' failed, ',status
     endif
     call wrf_message(trim(msg))
     status = WRF_GRIB2_ERR_GETGB2
     return
  endif

  global_input(DataHandle) = transfer(gfld%local,global_input(DataHandle))
  global_input(DataHandle)(gfld%locallen+1:30000) = ' '

  call gf_free(gfld)

  !
  ! Read and index all scalar data
  !
  VarName = "WRF_SCALAR"
  CALL get_parminfo(VarName, center, subcenter, MasterTblV, &
       LocalTblV, Disc, Category, ParmNum, DecScl, BinScl, status)
  if (status .ne. 0) then
     write(msg,*) 'Could not find parameter for '//   &
          trim(VarName)//'   Skipping reading of '//trim(VarName)
     call wrf_message(trim(msg))
     Status =  WRF_GRIB2_ERR_GRIB2MAP
     return
  endif

  !
  ! Read the metadata
  !
  ! First, set all values to wild, then specify necessary values
  !
  call gr2_g2lib_wildcard(JIDS, JPDT, JGDT)

  JIDS(1) = center
  JIDS(2) = subcenter
  JIDS(3) = MasterTblV
  JIDS(4) = LocalTblV

  JIDS(5) = 1           ! Indicates that time is "Start of Forecast"
  JIDS(13) = 1          ! Type of processed data (1 for forecast products)
  
  JPDTN = 0             ! Product definition template number
  JPDT(1) = Category
  JPDT(2) = ParmNum
  JPDT(3) = 2           ! Generating process id

  JGDTN    = -1         ! Indicates that any Grid Display Template is a match
  
  UNPACK   = .FALSE.    ! Dont unpack bitmap and data values

  fields_to_skip = 0
  do while (status .eq. 0) 
     CALL GETGB2(DataHandle, 0, fields_to_skip, -1, -1, JIDS, JPDTN, &
          JPDT, JGDTN, JGDT, UNPACK, fileinfo(DataHandle)%recnum, &
          gfld, status)
     if (status .eq. 99) then
        exit
     else if (status .ne. 0) then
        write(msg,*)'Finding data field '//trim(VarName)//' failed 1.'
        call wrf_message(trim(msg))
        Status = WRF_GRIB2_ERR_READ
        return
     endif
     
     ! Build times list here
     write(refTime,'(I4,A,I2.2,A,I2.2,A,I2.2,A,I2.2,A,I2.2)')      &
          gfld%idsect(6),'-',gfld%idsect(7),'-',gfld%idsect(8),'_',&
          gfld%idsect(9),':',gfld%idsect(10),':',gfld%idsect(11)

     time_range_convert(:) = -1
     time_range_convert(1) = 60
     time_range_convert(2) = 60*60
     time_range_convert(3) = 24*60*60
     time_range_convert(10) = 3*60*60
     time_range_convert(11) = 6*60*60
     time_range_convert(12) = 12*60*60
     time_range_convert(13) = 1
     
     if (time_range_convert(gfld%ipdtmpl(8)) .gt. 0) then
        fcstsecs = gfld%ipdtmpl(9)*time_range_convert(gfld%ipdtmpl(8))
     else 
        write(msg,*)'Invalid time range in input data: ',gfld%ipdtmpl(8),&
             ' Skipping'
        call wrf_message(trim(msg))
        call gf_free(gfld)
        cycle
     endif
     call advance_wrf_time(refTime,fcstsecs,theTime)

     call gr2_add_time(DataHandle,theTime)

     fields_to_skip = fields_to_skip + fileinfo(DataHandle)%recnum

     scalar_input(DataHandle) = transfer(gfld%local,scalar_input(DataHandle))
     scalar_input(DataHandle)(gfld%locallen+1:30000) = ' '
     
     call gf_free(gfld)
  enddo

  !
  ! Fill up the eta levels variables
  !

  if (.not. full_eta_init) then
     CALL gr2_fill_levels(DataHandle, "ZNW", full_eta, ierr)
     if (ierr .eq. 0) then
        full_eta_init = .TRUE.
     endif
  endif
  if (.not. half_eta_init) then
     CALL gr2_fill_levels(DataHandle, "ZNU", half_eta, ierr)
     if (ierr .eq. 0) then 
        half_eta_init = .TRUE.
     endif
  endif
  !
  ! Fill up the soil levels
  !
  if (.not. soil_depth_init) then
     call gr2_fill_levels(DataHandle,"ZS",soil_depth, ierr)
     if (ierr .eq. 0) then
        soil_depth_init = .TRUE.
     endif
  endif
  if (.not. soil_thickness_init) then
     call gr2_fill_levels(DataHandle,"DZS",soil_thickness, ierr)
     if (ierr .eq. 0) then
        soil_thickness_init = .TRUE.
     endif
  endif

  ! 
  ! Fill up any variables from the global metadata
  !

  CALL gr2_get_metadata_value(global_input(DataHandle), &
       'START_DATE', StartDate, status)
  if (status .ne. 0) then
     write(msg,*)'Could not find metadata value for START_DATE, continuing'
     call wrf_message(trim(msg))
  endif
 
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       'PROGRAM_NAME', InputProgramName, status)
  if (status .ne. 0) then
     write(msg,*)'Could not find metadata value for PROGRAM_NAME, continuing'
     call wrf_message(trim(msg))
  else
     endchar = SCAN(InputProgramName," ")
     InputProgramName = InputProgramName(1:endchar)
  endif


  Status = WRF_NO_ERR

  call wrf_debug ( DEBUG , 'Exiting ext_gr2_open_for_read_begin')

  RETURN
END SUBROUTINE ext_gr2_open_for_read_begin

!*****************************************************************************

SUBROUTINE ext_gr2_open_for_read_commit( DataHandle , Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
#include "wrf_io_flags.h"
  character(len=maxMsgSize) :: msg
  INTEGER ,       INTENT(IN ) :: DataHandle
  INTEGER ,       INTENT(OUT) :: Status

  call wrf_debug ( DEBUG , 'Entering ext_gr2_open_for_read_commit')

  Status = WRF_NO_ERR
  if(WrfIOnotInitialized) then
    Status = WRF_IO_NOT_INITIALIZED
    write(msg,*) 'ext_gr2_ioinit was not called ',__FILE__,', line', __LINE__
    call wrf_debug ( FATAL , msg)
    return
  endif
  fileinfo(DataHandle)%committed = .true.
  fileinfo(DataHandle)%FileStatus = WRF_FILE_OPENED_FOR_READ

  Status = WRF_NO_ERR

  RETURN
END SUBROUTINE ext_gr2_open_for_read_commit

!*****************************************************************************

SUBROUTINE ext_gr2_open_for_read ( FileName , Comm_compute, Comm_io, &
     SysDepInfo, DataHandle , Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  CHARACTER*(*) :: FileName
  INTEGER ,       INTENT(IN)  :: Comm_compute , Comm_io
  CHARACTER*(*) :: SysDepInfo
  INTEGER ,       INTENT(OUT) :: DataHandle
  INTEGER ,       INTENT(OUT) :: Status


  call wrf_debug ( DEBUG , 'Entering ext_gr2_open_for_read')

  DataHandle = 0   ! dummy setting to quiet warning message
  CALL ext_gr2_open_for_read_begin( FileName, Comm_compute, Comm_io, &
       SysDepInfo, DataHandle, Status )
  IF ( Status .EQ. WRF_NO_ERR ) THEN
    CALL ext_gr2_open_for_read_commit( DataHandle, Status )
  ENDIF
  return

  RETURN  
END SUBROUTINE ext_gr2_open_for_read

!*****************************************************************************

SUBROUTINE ext_gr2_open_for_write_begin(FileName, Comm, IOComm, SysDepInfo, &
     DataHandle, Status)
  
  USE gr2_data_info
  implicit none
#include "wrf_status_codes.h"
#include "wrf_io_flags.h"

  character*(*)        ,intent(in)  :: FileName
  integer              ,intent(in)  :: Comm
  integer              ,intent(in)  :: IOComm
  character*(*)        ,intent(in)  :: SysDepInfo
  integer              ,intent(out) :: DataHandle
  integer              ,intent(out) :: Status
  integer :: ierr
  CHARACTER (LEN=maxMsgSize) :: msg

  INTERFACE
     Subroutine load_grib2map (filename, message, status)
       USE grib2tbls_types
       character*(*), intent(in)                   :: filename
       character*(*), intent(inout)                :: message
       integer      , intent(out)                  :: status
     END subroutine load_grib2map
  END INTERFACE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_open_for_write_begin')

  Status = WRF_NO_ERR

  if (.NOT. grib2map_table_filled) then
     grib2map_table_filled = .TRUE.
     CALL load_grib2map(mapfilename, msg, status)
     if (status .ne. 0) then
        call wrf_message(trim(msg))
        Status = WRF_ERR_FATAL_BAD_FILE_STATUS
        return
     endif
  endif

  CALL gr2_get_new_handle(DataHandle)

  if (DataHandle .GT. 0) then

     call baopenw(DataHandle,trim(FileName),ierr)

     if (ierr .ne. 0) then
        Status = WRF_ERR_FATAL_BAD_FILE_STATUS
     else
        fileinfo(DataHandle)%opened = .true.
        fileinfo(DataHandle)%DataFile = TRIM(FileName)
        fileinfo(DataHandle)%FileStatus = WRF_FILE_OPENED_NOT_COMMITTED
     endif
     fileinfo(DataHandle)%last_scalar_time_written = -1
     fileinfo(DataHandle)%committed = .false.
     td_output(DataHandle) = ''
     ti_output(DataHandle) = ''
     scalar_output(DataHandle) = ''
     fileinfo(DataHandle)%write = .true.
  else
     Status = WRF_WARN_TOO_MANY_FILES
  endif

  RETURN  
END SUBROUTINE ext_gr2_open_for_write_begin

!*****************************************************************************

SUBROUTINE ext_gr2_open_for_write_commit( DataHandle , Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
#include "wrf_io_flags.h"
  INTEGER ,       INTENT(IN ) :: DataHandle
  INTEGER ,       INTENT(OUT) :: Status

  call wrf_debug ( DEBUG , 'Entering ext_gr2_open_for_write_commit')

  IF ( fileinfo(DataHandle)%opened ) THEN
    IF ( fileinfo(DataHandle)%used ) THEN
      fileinfo(DataHandle)%committed = .true.
      fileinfo(DataHandle)%FileStatus = WRF_FILE_OPENED_FOR_WRITE
    ENDIF
  ENDIF

  Status = WRF_NO_ERR

  RETURN  
END SUBROUTINE ext_gr2_open_for_write_commit

!*****************************************************************************

subroutine ext_gr2_inquiry (Inquiry, Result, Status)
  use gr2_data_info
  implicit none
#include "wrf_status_codes.h"
  character *(*), INTENT(IN)    :: Inquiry
  character *(*), INTENT(OUT)   :: Result
  integer        ,INTENT(INOUT) :: Status
  SELECT CASE (Inquiry)
  CASE ("RANDOM_WRITE","RANDOM_READ")
     Result='ALLOW'
  CASE ("SEQUENTIAL_WRITE","SEQUENTIAL_READ")
     Result='NO'
  CASE ("OPEN_READ", "OPEN_WRITE", "OPEN_COMMIT_WRITE")
     Result='REQUIRE'
  CASE ("OPEN_COMMIT_READ","PARALLEL_IO")
     Result='NO'
  CASE ("SELF_DESCRIBING","SUPPORT_METADATA","SUPPORT_3D_FIELDS")
     Result='YES'
  CASE ("MEDIUM")
     Result ='FILE'
  CASE DEFAULT
     Result = 'No Result for that inquiry!'
  END SELECT
  Status=WRF_NO_ERR
  return
end subroutine ext_gr2_inquiry

!*****************************************************************************

SUBROUTINE ext_gr2_inquire_opened ( DataHandle, FileName , FileStat, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
#include "wrf_io_flags.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: FileName
  INTEGER ,       INTENT(OUT) :: FileStat
  INTEGER ,       INTENT(OUT) :: Status

  call wrf_debug ( DEBUG , 'Entering ext_gr2_inquire_opened')

  FileStat = WRF_NO_ERR
  if ((DataHandle .ge. firstFileHandle) .and. &
       (DataHandle .le. maxFileHandles)) then
     FileStat = fileinfo(DataHandle)%FileStatus
  else
     FileStat = WRF_FILE_NOT_OPENED
  endif
  
  Status = FileStat

  RETURN
END SUBROUTINE ext_gr2_inquire_opened

!*****************************************************************************

SUBROUTINE ext_gr2_ioclose ( DataHandle, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
#include "wrf_io_flags.h"
  INTEGER DataHandle, Status
  INTEGER istat
  character(len=1000) :: outstring
  character :: lf
  character*(maxMsgSize) :: msg
  integer   :: idx

  lf=char(10)
  call wrf_debug ( DEBUG , 'Entering ext_gr2_ioclose')

  Status = WRF_NO_ERR

  if (fileinfo(DataHandle)%write .eqv. .TRUE.) then
     call gr2_fill_local_use(DataHandle,scalar_output(DataHandle),&
          "WRF_SCALAR",fcst_secs,msg,status)
     if (status .ne. 0) then
        call wrf_message(trim(msg))
        return
     endif
     fileinfo(DataHandle)%last_scalar_time_written = fcst_secs
     scalar_output(DataHandle) = ''
     
     call gr2_fill_local_use(DataHandle,&
          trim(ti_output(DataHandle))//trim(td_output(DataHandle)),&
          "WRF_GLOBAL",0,msg,status)
     if (status .ne. 0) then
        call wrf_message(trim(msg))
        return
     endif
     ti_output(DataHandle) = ''
     td_output(DataHandle) = ''
  endif

  do idx = 1,fileinfo(DataHandle)%NumberTimes 
     if (allocated(fileinfo(DataHandle)%Times)) then
        deallocate(fileinfo(DataHandle)%Times)
     endif
  enddo
  fileinfo(DataHandle)%NumberTimes = 0
  fileinfo(DataHandle)%sizeAllocated = 0
  fileinfo(DataHandle)%CurrentTime = 0
  fileinfo(DataHandle)%write = .FALSE.

  call baclose(DataHandle,status)
  if (status .ne. 0) then
     call wrf_message("Closing file failed, continuing")
  else
     fileinfo(DataHandle)%opened = .true.
     fileinfo(DataHandle)%DataFile = ''
     fileinfo(DataHandle)%FileStatus = WRF_FILE_NOT_OPENED
  endif

  fileinfo(DataHandle)%used = .false.

  RETURN
END SUBROUTINE ext_gr2_ioclose

!*****************************************************************************

SUBROUTINE ext_gr2_write_field( DataHandle , DateStrIn , VarName , &
     Field , FieldType , Comm , IOComm, &
     DomainDesc , MemoryOrder , Stagger , &
     DimNames , &
     DomainStart , DomainEnd , &
     MemoryStart , MemoryEnd , &
     PatchStart , PatchEnd , &
     Status )

  USE gr2_data_info
  USE grib2tbls_types
  IMPLICIT NONE
#include "wrf_status_codes.h"
#include "wrf_io_flags.h"
  integer                       ,intent(in)    :: DataHandle 
  character*(*)                 ,intent(in)    :: DateStrIn
  character*(*)                 ,intent(in)    :: VarName
  integer                       ,intent(in)    :: FieldType
  integer                       ,intent(inout) :: Comm
  integer                       ,intent(inout) :: IOComm
  integer                       ,intent(in)    :: DomainDesc
  character*(*)                 ,intent(in)    :: MemoryOrder
  character*(*)                 ,intent(in)    :: Stagger
  character*(*) , dimension (*) ,intent(in)    :: DimNames
  integer ,dimension(*)         ,intent(in)    :: DomainStart, DomainEnd
  integer ,dimension(*)         ,intent(in)    :: MemoryStart, MemoryEnd
  integer ,dimension(*)         ,intent(in)    :: PatchStart,  PatchEnd
  integer                       ,intent(out)   :: Status

  real                          , intent(in), &
       dimension( 1:1,MemoryStart(1):MemoryEnd(1), &
       MemoryStart(2):MemoryEnd(2), &
       MemoryStart(3):MemoryEnd(3) )           :: Field


  character (120)                              :: DateStr

  character (maxMsgSize)                       :: msg
  integer                                      :: xsize, ysize, zsize
  integer                                      :: x, y, z
  integer                                      :: &
       x_start,x_end,y_start,y_end,z_start,z_end
  integer                                      :: idx
  integer                                      :: proj_center_flag
  logical                                      :: vert_stag = .false.
  real,    dimension(:,:), pointer             :: data
  integer                                      :: istat
  integer                                      :: accum_period
  integer, dimension(maxLevels)                :: level1, level2
  integer, dimension(maxLevels)                :: grib_levels
  logical                                      :: soil_layers, fraction
  integer                                      :: vert_unit1, vert_unit2
  integer                                      :: vert_sclFctr1, vert_sclFctr2
  integer                                      :: this_domain
  logical                                      :: new_domain
  real                                         :: &
       region_center_lat, region_center_lon
  integer                                      :: dom_xsize, dom_ysize;
  integer , parameter                          :: lcgrib = 2000000
  character (lcgrib)                           :: cgrib
  integer                                      :: ierr
  integer                                      :: lengrib

  integer                                     :: center, subcenter, &
       MasterTblV, LocalTblV, Disc, Category, ParmNum, DecScl, BinScl
  CHARACTER(len=100)  :: tmpstr
  integer             :: ndims
  integer             :: dim1size, dim2size, dim3size, dim3
  integer             :: numlevels
  integer             :: ngrdpts
  integer             :: bytes_written
  
  call wrf_debug ( DEBUG , 'Entering ext_gr2_write_field for parameter '//&
       VarName)

  !
  ! If DateStr is all 0s, we reset it to StartDate.  For some reason, 
  !   in idealized simulations, StartDate is 0001-01-01_00:00:00 while
  !   the first DateStr is 0000-00-00_00:00:00.  
  !
  if (DateStrIn .eq. '0000-00-00_00:00:00') then
     DateStr = TRIM(StartDate)
  else
     DateStr = DateStrIn
  endif

  !
  ! Check if this is a domain that we haven t seen yet.  If so, add it to 
  !   the list of domains.
  !
  this_domain = 0
  new_domain = .false.
  do idx = 1, max_domain
     if (DomainDesc .eq. domains(idx)) then
        this_domain = idx
     endif
  enddo
  if (this_domain .eq. 0) then
     max_domain = max_domain + 1
     domains(max_domain) = DomainDesc
     this_domain = max_domain
     new_domain = .true.
  endif

  zsize = 1
  xsize = 1
  ysize = 1
  soil_layers = .false.
  fraction = .false.

  ! First, handle then special cases for the boundary data.

  CALL get_dims(MemoryOrder, PatchStart, PatchEnd, ndims, x_start, x_end, &
       y_start, y_end,z_start,z_end)
  xsize = x_end - x_start + 1
  ysize = y_end - y_start + 1
  zsize = z_end - z_start + 1

  do idx = 1, len(MemoryOrder)
     if ((MemoryOrder(idx:idx) .eq. 'Z') .and. &
          (DimNames(idx) .eq. 'soil_layers_stag')) then
        soil_layers = .true.
     else if ((VarName .eq. 'LANDUSEF') .or. (VarName .eq. 'SOILCBOT') .or. &
          (VarName .eq. 'SOILCTOP')) then
        fraction = .true.
     endif
  enddo

  if (zsize .eq. 0) then 
     zsize = 1
  endif

  !
  ! Fill up the variables that hold the vertical coordinate data
  !

  if (VarName .eq. 'ZNU') then
     do idx = 1, zsize
        half_eta(idx) = Field(1,idx,1,1)
     enddo
     half_eta_init = .TRUE.
  endif

  if (VarName .eq. 'ZNW') then
     do idx = 1, zsize
        full_eta(idx) = Field(1,idx,1,1)
     enddo
     full_eta_init = .TRUE.
  endif
  
  if (VarName .eq. 'ZS') then
     do idx = 1, zsize
        soil_depth(idx) = Field(1,idx,1,1)
     enddo
     soil_depth_init = .TRUE.
  endif

  if (VarName .eq. 'DZS') then
     do idx = 1, zsize
        soil_thickness(idx) = Field(1,idx,1,1)
     enddo
     soil_thickness_init = .TRUE.
  endif

  ! 
  ! Check to assure that dimensions are valid
  !

  if ((xsize .lt. 1) .or. (ysize .lt. 1) .or. (zsize .lt. 1)) then
     write(msg,*) 'Cannot output field with memory order: ', &
          MemoryOrder,Varname
     call wrf_message(trim(msg))
     return
  endif
     

  if (fileinfo(DataHandle)%opened .and. fileinfo(DataHandle)%committed) then

     if (StartDate == '') then
        StartDate = DateStr
     endif
     
     CALL geth_idts(DateStr,StartDate,fcst_secs)

     !
     ! If this is a new forecast time, and we have not written the 
     !   last_fcst_secs scalar output yet, then write it here.
     !

     if ((abs(fcst_secs - 0.0) .gt. 0.01) .and. &
          (last_fcst_secs .ge. 0) .and. &
          (abs(fcst_secs - last_fcst_secs) .gt. 0.01) .and. &
          (abs(last_fcst_secs - fileinfo(DataHandle)%last_scalar_time_written) .gt. 0.01) ) then
        call gr2_fill_local_use(DataHandle,scalar_output(DataHandle),&
             "WRF_SCALAR",last_fcst_secs,msg,status)
        if (status .ne. 0) then
           call wrf_message(trim(msg))
           return
        endif
        fileinfo(DataHandle)%last_scalar_time_written = last_fcst_secs
        scalar_output(DataHandle) = ''
     endif

     call get_vert_stag(VarName,Stagger,vert_stag)
     
     do idx = 1, zsize
        call gr2_get_levels(VarName, idx, zsize, soil_layers, vert_stag, &
             fraction, vert_unit1, vert_unit2, vert_sclFctr1, &
             vert_sclFctr2, level1(idx), level2(idx))
     enddo
     
     ! 
     ! Get the center lat/lon for the area being output.  For some cases (such
     !    as for boundary areas, the center of the area is different from the
     !    center of the model grid.
     !
     if (index(Stagger,'X') .le. 0) then
        dom_xsize = full_xsize - 1
     else
        dom_xsize = full_xsize
     endif
     if (index(Stagger,'Y') .le. 0) then
        dom_ysize = full_ysize - 1
     else
        dom_ysize = full_ysize
     endif
     

     CALL get_region_center(MemoryOrder, wrf_projection, center_lat, &
          center_lon, dom_xsize, dom_ysize, dx, dy, proj_central_lon, &
          proj_center_flag, truelat1, truelat2, xsize, ysize, &
          region_center_lat, region_center_lon)
     

     if (ndims .eq. 0) then        ! Scalar quantity

        ALLOCATE(data(1:1,1:1), STAT=istat)

        call gr2_retrieve_data(MemoryOrder, MemoryStart, MemoryEnd, &
             xsize, ysize, zsize, z, FieldType, Field, data)
        write(tmpstr,'(G17.10)')data(1,1)
        CALL gr2_build_string (scalar_output(DataHandle), &
             trim(adjustl(VarName)), tmpstr, 1, Status)

        DEALLOCATE(data)

     else if (ndims .ge. 1) then   ! Vector (1-D) and 2/3 D quantities

        if (ndims .eq. 1) then     ! Handle Vector (1-D) parameters
           dim1size = zsize
           dim2size = 1
           dim3size = 1
        else                       ! Handle 2/3 D parameters
           dim1size = xsize
           dim2size = ysize
           dim3size = zsize
        endif
        
        ALLOCATE(data(1:dim1size,1:dim2size), STAT=istat)

        CALL get_parminfo(VarName, center, subcenter, MasterTblV, &
             LocalTblV, Disc, Category, ParmNum, DecScl, BinScl, status)
        if (status .ne. 0) then
           write(msg,*) 'Could not find parameter for '//   &
                trim(VarName)//'   Skipping output of '//trim(VarName)
           call wrf_message(trim(msg))
           Status =  WRF_GRIB2_ERR_GRIB2MAP
           return
        endif

        VERTDIM : do dim3 = 1, dim3size

           call gr2_retrieve_data(MemoryOrder, MemoryStart, MemoryEnd, xsize, &
                ysize, zsize, dim3, FieldType, Field, data)
        
           ! 
           ! Here, we do any necessary conversions to the data.
           !
           
           ! Potential temperature is sometimes passed in as perturbation 
           !   potential temperature (i.e., POT-300).  Other times (i.e., from 
           !   WRF SI), it is passed in as full potential temperature.
           ! Here, we convert to full potential temperature by adding 300
           !   only if POT < 200 K.
           !
           if (VarName == 'T') then
              if ((data(1,1) < 200) .and. (data(1,1) .ne. 0)) then
                 data = data + 300
              endif
           endif
           
           ! 
           ! For precip, we setup the accumulation period, and output a precip
           !    rate for time-step precip.
           !
           if ((VarName .eq. 'RAINCV') .or. (VarName .eq. 'RAINNCV')) then
              ! Convert time-step precip to precip rate.
              data = data/timestep
              accum_period = 0
           else
              accum_period = 0
           endif
           
           !
           ! Create indicator and identification sections (sections 0 and 1)
           !
           CALL gr2_create_w(StartDate, cgrib, lcgrib, production_status, &
                Disc, center, subcenter, MasterTblV, LocalTblV, ierr, msg)
           if (ierr .ne. 0) then
              call wrf_message(trim(msg))
              Status = WRF_GRIB2_ERR_GRIBCREATE
              return
           endif

           !
           ! Add the grid definition section (section 3) using a 1x1 grid
           !
           call gr2_addgrid_w(cgrib, lcgrib, center_lat, proj_central_lon,  &
                wrf_projection, truelat1, truelat2, xsize, ysize, dx, dy, &
                region_center_lat, region_center_lon, ierr, msg)
           if (ierr .ne. 0) then
              call wrf_message(trim(msg))
              Status = WRF_GRIB2_ERR_ADDGRIB
              return
           endif

           if (ndims .eq. 1) then
              numlevels = zsize
              grib_levels(:) = level1(:)
              ngrdpts = zsize
           else
              numlevels = 2
              grib_levels(1) = level1(dim3)
              grib_levels(2) = level2(dim3)
              ngrdpts = xsize*ysize
           endif
           
           !
           ! Add the Product Definition, Data representation, bitmap 
           !      and data sections (sections 4-7)
           !
           
           call gr2_addfield_w(cgrib, lcgrib, VarName, Category, ParmNum, &
                DecScl, BinScl, fcst_secs, vert_unit1, vert_unit2, &
                vert_sclFctr1, vert_sclFctr2, numlevels, &
                grib_levels, ngrdpts,  background_proc_id, forecast_proc_id, &
                compression, data, ierr, msg)
           if (ierr .eq. 11) then
              write(msg,'(A,I7,A)') 'WARNING: decimal scale for field '//&
                   trim(VarName)//' at level ',grib_levels(1),&
                   ' was reduced to fit field into 24 bits.  '//&
                   ' Some precision may be lost!'//&
                   '     To prevent this message, reduce decimal scale '//&
                   'factor in '//trim(mapfilename)
              call wrf_message(trim(msg))
           else if (ierr .eq. 12) then
              write(msg,'(A,I7,A)') 'WARNING: binary scale for field '//&
                   trim(VarName)//' at level ',grib_levels(1), &
                   ' was reduced to fit field into 24 bits.  '//&
                   ' Some precision may be lost!'//&
                   '     To prevent this message, reduce binary scale '//&
                   'factor in '//trim(mapfilename)
              call wrf_message(trim(msg))
           else if (ierr .ne. 0) then
              call wrf_message(trim(msg))
              Status = WRF_GRIB2_ERR_ADDFIELD
              return
           endif

           !
           ! Close out the message
           !
           
           call gribend(cgrib,lcgrib,lengrib,ierr)
           if (ierr .ne. 0) then
              write(msg,*) 'gribend failed with ierr: ',ierr     
              call wrf_message(trim(msg))
              Status = WRF_GRIB2_ERR_GRIBEND
              return
           endif

           ! 
           ! Write the data to the file
           !
           
!           call write_file_n(fileinfo(DataHandle)%FileFd, cgrib, lengrib, ierr)
           call bawrite(DataHandle, -1, lengrib, bytes_written, cgrib)
           if (bytes_written .ne. lengrib) then
              write(msg,*) '1 Error writing cgrib to file, wrote: ', &
                   bytes_written, ' bytes.  Tried to write ', lengrib, ' bytes'
              call wrf_message(trim(msg))
              Status = WRF_GRIB2_ERR_WRITE
              return
           endif

        ENDDO VERTDIM
        
        DEALLOCATE(data)

     endif

     last_fcst_secs = fcst_secs

  endif

  deallocate(data, STAT = istat)

  Status = WRF_NO_ERR

  call wrf_debug ( DEBUG , 'Leaving ext_gr2_write_field')

  RETURN
END SUBROUTINE ext_gr2_write_field

!*****************************************************************************

SUBROUTINE ext_gr2_read_field ( DataHandle , DateStr , VarName , Field , &
     FieldType , Comm , IOComm, DomainDesc , MemoryOrder , Stagger ,     &
     DimNames , DomainStart , DomainEnd , MemoryStart , MemoryEnd ,      &
     PatchStart , PatchEnd ,  Status )

  USE gr2_data_info
  USE grib_mod
  IMPLICIT NONE  
#include "wrf_status_codes.h"
#include "wrf_io_flags.h"
  INTEGER                       ,intent(in)       :: DataHandle 
  CHARACTER*(*)                 ,intent(in)       :: DateStr
  CHARACTER*(*)                 ,intent(in)       :: VarName
  integer                       ,intent(inout)    :: FieldType
  integer                       ,intent(inout)    :: Comm
  integer                       ,intent(inout)    :: IOComm
  integer                       ,intent(inout)    :: DomainDesc
  character*(*)                 ,intent(inout)    :: MemoryOrder
  character*(*)                 ,intent(inout)    :: Stagger
  character*(*) , dimension (*) ,intent(inout)    :: DimNames
  integer ,dimension(*)         ,intent(inout)    :: DomainStart, DomainEnd
  integer ,dimension(*)         ,intent(inout)    :: MemoryStart, MemoryEnd
  integer ,dimension(*)         ,intent(inout)    :: PatchStart,  PatchEnd
  integer                       ,intent(out)      :: Status
  INTEGER                       ,intent(out)      :: Field(*)
  integer                       :: xsize,ysize,zsize
  integer                       :: x_start,x_end,y_start,y_end,z_start,z_end
  integer                       :: ndims
  character (len=1000)          :: Value
  character (maxMsgSize)        :: msg
  integer                       :: ierr
  real                          :: Data
  integer                       :: center, subcenter, MasterTblV, &
       LocalTblV, Disc, Category, ParmNum, DecScl, BinScl
  integer                       :: dim1size,dim2size,dim3size,dim3

  integer :: idx
  integer :: fields_to_skip
  integer :: JIDS(JIDSSIZE), JPDTN, JPDT(JPDTSIZE), JGDTN, &
       JGDT(JGDTSIZE)
  logical :: UNPACK
  type(gribfield) :: gfld
  logical                                      :: soil_layers, fraction
  logical                                      :: vert_stag = .false.
  integer                                      :: vert_unit1, vert_unit2
  integer                                      :: vert_sclFctr1, vert_sclFctr2
  integer                                      :: level1, level2
  integer                                      :: di
  real                                         :: tmpreal

  call wrf_debug ( DEBUG , 'Entering ext_gr2_read_field'//fileinfo(DataHandle)%DataFile)
  
  CALL get_dims(MemoryOrder, PatchStart, PatchEnd, ndims, x_start, x_end, &
       y_start, y_end,z_start,z_end)
  xsize = x_end - x_start + 1
  ysize = y_end - y_start + 1
  zsize = z_end - z_start + 1

  ! 
  ! Check to assure that dimensions are valid
  !

  if ((xsize .lt. 1) .or. (ysize .lt. 1) .or. (zsize .lt. 1)) then
     write(msg,*) 'Cannot retrieve field with memory order: ', &
          MemoryOrder,Varname
     Status = WRF_GRIB2_ERR_READ
     call wrf_message(trim(msg))
     return
  endif
     

  if (ndims .eq. 0) then    ! Scalar quantity

     call gr2_get_metadata_value(scalar_input(DataHandle),trim(VarName),&
          Value,ierr)
     if (ierr /= 0) then
        Status = WRF_GRIB2_ERR_READ
        CALL wrf_message ( &
             "gr2_get_metadata_value failed for Scalar variable "//&
             trim(VarName))
        return
     endif

     READ(Value,*,IOSTAT=ierr)Data
     if (ierr .ne. 0) then
        CALL wrf_message("Reading data from "//trim(VarName)//" failed")
        Status = WRF_GRIB2_ERR_READ
        return
     endif

     if (FieldType .eq. WRF_INTEGER) then
        Field(1:1) = data
     else if ((FieldType .eq. WRF_REAL) .or. (FieldType .eq. WRF_DOUBLE)) then
        Field(1:1) = TRANSFER(data,Field(1),1)
     else
        write (msg,*)'Reading of type ',FieldType,'from grib data not supported, not reading ',VarName
        call wrf_message(msg)
     endif

  else if (ndims .ge. 1) then   ! Vector (1-D) and 2/3 D quantities
     
     if (ndims .eq. 1) then     ! Handle Vector (1-D) parameters
        dim1size = zsize
        dim2size = 1
        dim3size = 1
     else                       ! Handle 2/3 D parameters
        dim1size = xsize
        dim2size = ysize
        dim3size = zsize
     endif
     
     CALL get_parminfo(VarName, center, subcenter, MasterTblV, &
          LocalTblV, Disc, Category, ParmNum, DecScl, BinScl, status)
     if (status .ne. 0) then
        write(msg,*) 'Could not find parameter for '//   &
             trim(VarName)//'   Skipping output of '//trim(VarName)
        call wrf_message(trim(msg))
        Status =  WRF_GRIB2_ERR_GRIB2MAP
        return
     endif
     
     CALL get_vert_stag(VarName,Stagger,vert_stag)
     CALL get_soil_layers(VarName,soil_layers)

     VERTDIM : do dim3 = 1, dim3size

        fields_to_skip = 0

        !
        ! First, set all values to wild, then specify necessary values
        !
        call gr2_g2lib_wildcard(JIDS, JPDT, JGDT)

        JIDS(1) = center
        JIDS(2) = subcenter
        JIDS(3) = MasterTblV
        JIDS(4) = LocalTblV
        JIDS(5) = 1           ! Indicates that time is "Start of Forecast"
        
        READ (StartDate,'(I4.4,1X,I2.2,1X,I2.2,1X,I2.2,1X,I2.2,1X,I2.2)') &
             (JIDS(idx),idx=6,11)
        JIDS(13) = 1          ! Type of processed data(1 for forecast products)
        
        JPDT(1) = Category
        JPDT(2) = ParmNum
        JPDT(3) = 2           ! Generating process id

        CALL geth_idts(DateStr,StartDate,tmpreal)  ! Forecast time 
        
        JPDT(9) = NINT(tmpreal)

        if (ndims .eq. 1) then
           jpdtn = 1000       ! Product definition tmplate (1000 for cross-sxn)
        else
           call gr2_get_levels(VarName, dim3, dim3size, soil_layers, &
                vert_stag, .false., vert_unit1, vert_unit2, vert_sclFctr1, &
                vert_sclFctr2, level1, level2)
           
           jpdtn = 0          ! Product definition template (0 for horiz grid)
           JPDT(10) = vert_unit1     ! Type of first surface
           JPDT(11) = vert_sclFctr1  ! Scale factor first surface
           JPDT(12) = level1         ! First surface
           JPDT(13) = vert_unit2     ! Type of second surface
           JPDT(14) = vert_sclFctr2  ! Scale factor second surface
           JPDT(15) = level2         ! Second fixed surface
        endif

        JGDTN    = -1    ! Indicates that any Grid Display Template is a match
        
        UNPACK   = .TRUE.! Unpack bitmap and data values
        
        fields_to_skip = 0
        CALL GETGB2(DataHandle, 0, fields_to_skip, &
             fileinfo(DataHandle)%recnum+1, &
             Disc, JIDS, JPDTN, JPDT, JGDTN, JGDT, UNPACK, &
             fileinfo(DataHandle)%recnum, gfld, status)
        if (status .eq. 99) then
           write(msg,*)'Could not find data for field '//trim(VarName)//&
                ' in file '//trim(fileinfo(DataHandle)%DataFile)
           call wrf_message(trim(msg))
           Status = WRF_GRIB2_ERR_READ
           return
        else if (status .ne. 0) then
           write(msg,*)'Retrieving data field '//trim(VarName)//' failed 2.',status,dim3,DataHandle
           call wrf_message(trim(msg))
           Status = WRF_GRIB2_ERR_READ
           return
        endif

        if(FieldType == WRF_DOUBLE) then
           di = 2
        else 
           di = 1
        endif

        ! 
        ! Here, we do any necessary conversions to the data.
        !
        ! The WRF executable (wrf.exe) expects perturbation potential
        !   temperature.  However, real.exe expects full potential T.
        ! So, if the program is WRF, subtract 300 from Potential Temperature 
        !   to get perturbation potential temperature.
        !
        if (VarName == 'T') then
           if ( &
                (InputProgramName .eq. 'REAL_EM') .or. &
                (InputProgramName .eq. 'IDEAL') .or. &
                (InputProgramName .eq. 'NDOWN_EM')) then
              gfld%fld = gfld%fld - 300
           endif
        endif


        if (ndims .eq. 1) then
           CALL Transpose1D_grib(MemoryOrder, di, FieldType, Field, &
                MemoryStart(1), MemoryEnd(1), MemoryStart(2), MemoryEnd(2), &
                MemoryStart(3), MemoryEnd(3), &
                gfld%fld, zsize)
        else
           CALL Transpose_grib(MemoryOrder, di, FieldType, Field, &
                MemoryStart(1), MemoryEnd(1), MemoryStart(2), MemoryEnd(2), &
                MemoryStart(3), MemoryEnd(3), &
                gfld%fld, dim3, ysize,xsize)
        endif

        call gf_free(gfld)
        
     enddo VERTDIM
  endif

  Status = WRF_NO_ERR


  call wrf_debug ( DEBUG , 'Leaving ext_gr2_read_field')

  RETURN
END SUBROUTINE ext_gr2_read_field

!*****************************************************************************

SUBROUTINE ext_gr2_get_next_var ( DataHandle, VarName, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: VarName
  INTEGER ,       INTENT(OUT) :: Status

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_next_var')

  Status = WRF_WARN_NOOP

  RETURN
END SUBROUTINE ext_gr2_get_next_var

!*****************************************************************************

subroutine ext_gr2_end_of_frame(DataHandle, Status)

  USE gr2_data_info
  implicit none
#include "wrf_status_codes.h"
  integer               ,intent(in)     :: DataHandle
  integer               ,intent(out)    :: Status

  call wrf_debug ( DEBUG , 'Entering ext_gr2_end_of_frame')

  Status = WRF_WARN_NOOP

  return
end subroutine ext_gr2_end_of_frame

!*****************************************************************************

SUBROUTINE ext_gr2_iosync ( DataHandle, Status )

  USE gr2_data_info  
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  INTEGER ,       INTENT(OUT) :: Status
  integer                     :: ierror

  call wrf_debug ( DEBUG , 'Entering ext_gr2_iosync')

  Status = WRF_NO_ERR
  if (DataHandle .GT. 0) then
     CALL flush_file(fileinfo(DataHandle)%FileFd)
  else
     Status = WRF_WARN_TOO_MANY_FILES
  endif

  RETURN
END SUBROUTINE ext_gr2_iosync

!*****************************************************************************

SUBROUTINE ext_gr2_inquire_filename ( DataHandle, FileName , FileStat, &
     Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
#include "wrf_io_flags.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: FileName
  INTEGER ,       INTENT(OUT) :: FileStat
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER *80   SysDepInfo

  call wrf_debug ( DEBUG , 'Entering ext_gr2_inquire_filename')

  FileName = fileinfo(DataHandle)%DataFile 

  if ((DataHandle .ge. firstFileHandle) .and. &
       (DataHandle .le. maxFileHandles)) then
     FileStat = fileinfo(DataHandle)%FileStatus
  else
     FileStat = WRF_FILE_NOT_OPENED
  endif
  Status = WRF_NO_ERR

  RETURN
END SUBROUTINE ext_gr2_inquire_filename

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_info ( DataHandle , VarName , NDim , &
     MemoryOrder , Stagger , DomainStart , DomainEnd , WrfType, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  integer               ,intent(in)     :: DataHandle
  character*(*)         ,intent(in)     :: VarName
  integer               ,intent(out)    :: NDim
  character*(*)         ,intent(out)    :: MemoryOrder
  character*(*)         ,intent(out)    :: Stagger
  integer ,dimension(*) ,intent(out)    :: DomainStart, DomainEnd
  integer               ,intent(out)    :: WrfType
  integer               ,intent(out)    :: Status

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_info')

  MemoryOrder = ""
  Stagger = ""
  DomainStart(1) = 0
  DomainEnd(1) = 0
  WrfType = 0
  NDim = 0

  CALL wrf_message('ext_gr2_get_var_info not supported for grib version2 data')
  Status = WRF_NO_ERR

  RETURN
END SUBROUTINE ext_gr2_get_var_info

!*****************************************************************************

SUBROUTINE ext_gr2_set_time ( DataHandle, DateStr, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: DateStr
  INTEGER ,       INTENT(OUT) :: Status
  integer       :: found_time
  integer       :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_set_time')

  found_time = 0
  do idx = 1,fileinfo(DataHandle)%NumberTimes
     if (fileinfo(DataHandle)%Times(idx) == DateStr) then
        found_time = 1
        fileinfo(DataHandle)%CurrentTime = idx
     endif
  enddo
  if (found_time == 0) then 
     Status = WRF_WARN_TIME_NF
  else
     Status = WRF_NO_ERR
  endif

  RETURN
END SUBROUTINE ext_gr2_set_time

!*****************************************************************************

SUBROUTINE ext_gr2_get_next_time ( DataHandle, DateStr, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) , INTENT(OUT) :: DateStr
  INTEGER ,       INTENT(OUT) :: Status

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_next_time')

  if (fileinfo(DataHandle)%CurrentTime == fileinfo(DataHandle)%NumberTimes) then
     Status = WRF_WARN_TIME_EOF
  else
     fileinfo(DataHandle)%CurrentTime = fileinfo(DataHandle)%CurrentTime + 1
     DateStr = fileinfo(DataHandle)%Times(fileinfo(DataHandle)%CurrentTime)
     Status = WRF_NO_ERR
  endif

  call wrf_debug ( DEBUG , 'Leaving ext_gr2_get_next_time, got time '//DateStr)

  RETURN
END SUBROUTINE ext_gr2_get_next_time

!*****************************************************************************

SUBROUTINE ext_gr2_get_previous_time ( DataHandle, DateStr, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: DateStr
  INTEGER ,       INTENT(OUT) :: Status

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_previous_time')

  if (fileinfo(DataHandle)%CurrentTime <= 0) then
     Status = WRF_WARN_TIME_EOF
  else
     fileinfo(DataHandle)%CurrentTime = fileinfo(DataHandle)%CurrentTime - 1
     DateStr = fileinfo(DataHandle)%Times(fileinfo(DataHandle)%CurrentTime)
     Status = WRF_NO_ERR
  endif

  RETURN
END SUBROUTINE ext_gr2_get_previous_time

!******************************************************************************
!* Start of get_var_ti_* routines
!******************************************************************************

SUBROUTINE ext_gr2_get_var_ti_real ( DataHandle,Element,  Varname, Data, &
     Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)    :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: VarName 
  real ,          INTENT(OUT)   :: Data(*)
  INTEGER ,       INTENT(IN)    :: Count
  INTEGER ,       INTENT(OUT)   :: OutCount
  INTEGER ,       INTENT(OUT)   :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER(len=100)  :: Value

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_ti_real')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx
 
  RETURN
END SUBROUTINE ext_gr2_get_var_ti_real 

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_ti_real8 ( DataHandle,Element,  Varname, Data, &
     Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)      :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: VarName 
  real*8 ,        INTENT(OUT)     :: Data(*)
  INTEGER ,       INTENT(IN)      :: Count
  INTEGER ,       INTENT(OUT)     :: OutCount
  INTEGER ,       INTENT(OUT)     :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(100)  :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_ti_real8')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx
 
  RETURN
END SUBROUTINE ext_gr2_get_var_ti_real8 

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_ti_double ( DataHandle,Element,  Varname, Data, &
     Count, Outcount, Status )
  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) , INTENT(IN)  :: Element
  CHARACTER*(*) , INTENT(IN)  :: VarName
  real*8 ,            INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT)  :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(100)  :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_ti_double')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_var_ti_double

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_ti_integer ( DataHandle,Element,  Varname, Data, &
     Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)       :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: VarName 
  integer ,       INTENT(OUT)      :: Data(*)
  INTEGER ,       INTENT(IN)       :: Count
  INTEGER ,       INTENT(OUT)      :: OutCount
  INTEGER ,       INTENT(OUT)      :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_ti_integer')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_var_ti_integer 

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_ti_logical ( DataHandle,Element,  Varname, Data, &
     Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)       :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: VarName 
  logical ,       INTENT(OUT)      :: Data(*)
  INTEGER ,       INTENT(IN)       :: Count
  INTEGER ,       INTENT(OUT)      :: OutCount
  INTEGER ,       INTENT(OUT)      :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(100) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_ti_logical')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_var_ti_logical 

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_ti_char ( DataHandle,Element,  Varname, Data,  &
     Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: VarName 
  CHARACTER*(*) :: Data
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER       :: stat

  Status = WRF_NO_ERR
  
  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_ti_char')

  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(Element), Data, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  RETURN
END SUBROUTINE ext_gr2_get_var_ti_char 

!******************************************************************************
!* End of get_var_ti_* routines
!******************************************************************************


!******************************************************************************
!* Start of put_var_ti_* routines
!******************************************************************************

SUBROUTINE ext_gr2_put_var_ti_real ( DataHandle,Element,  Varname, Data, &
     Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: VarName 
  real ,          INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_ti_real')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo

     CALL gr2_build_string (ti_output(DataHandle), &
          trim(VarName)//';'//trim(Element), tmpstr, Count, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_var_ti_real 

!*****************************************************************************

SUBROUTINE ext_gr2_put_var_ti_double ( DataHandle,Element,  Varname, Data, &
     Count,  Status )
  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) , INTENT(IN)  :: Element
  CHARACTER*(*) , INTENT(IN)  :: VarName
  real*8 ,            INTENT(IN) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_ti_double')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (ti_output(DataHandle), &
          trim(VarName)//';'//trim(Element), tmpstr, Count, Status)
  endif

  RETURN
END SUBROUTINE ext_gr2_put_var_ti_double

!*****************************************************************************

SUBROUTINE ext_gr2_put_var_ti_real8 ( DataHandle,Element,  Varname, Data, &
     Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: VarName 
  real*8 ,        INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_ti_real8')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (ti_output(DataHandle), &
          trim(VarName)//';'//trim(Element), tmpstr, Count, Status)
  endif

  RETURN
END SUBROUTINE ext_gr2_put_var_ti_real8 

!*****************************************************************************

SUBROUTINE ext_gr2_put_var_ti_integer ( DataHandle,Element,  Varname, Data, &
     Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: VarName 
  integer ,       INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_ti_integer')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (ti_output(DataHandle), &
          trim(VarName)//';'//trim(Element), tmpstr, Count, Status)
  endif

  RETURN
END SUBROUTINE ext_gr2_put_var_ti_integer 

!*****************************************************************************

SUBROUTINE ext_gr2_put_var_ti_logical ( DataHandle,Element,  Varname, Data, &
     Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: VarName 
  logical ,       INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_ti_logical')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (ti_output(DataHandle), &
          trim(Varname)//';'//trim(Element), tmpstr, Count, Status)

  endif

RETURN
END SUBROUTINE ext_gr2_put_var_ti_logical 

!*****************************************************************************

SUBROUTINE ext_gr2_put_var_ti_char ( DataHandle,Element,  Varname, Data,  &
     Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER(len=*) :: Element
  CHARACTER(len=*) :: VarName 
  CHARACTER(len=*) :: Data
  INTEGER ,       INTENT(OUT) :: Status
  REAL dummy
  INTEGER                     :: Count
  CHARACTER(len=1000) :: tmpstr(1)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_ti_char')

  if (fileinfo(DataHandle)%committed) then

     write(tmpstr(1),*)trim(Data)

     CALL gr2_build_string (ti_output(DataHandle), &
          trim(VarName)//';'//trim(Element), tmpstr, 1, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_var_ti_char 

!******************************************************************************
!* End of put_var_ti_* routines
!******************************************************************************

!******************************************************************************
!* Start of get_var_td_* routines
!******************************************************************************

SUBROUTINE ext_gr2_get_var_td_double ( DataHandle,Element,  DateStr, &
     Varname, Data, Count, Outcount, Status )
  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) , INTENT(IN)  :: Element
  CHARACTER*(*) , INTENT(IN)  :: DateStr
  CHARACTER*(*) , INTENT(IN)  :: VarName
  real*8 ,            INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT)  :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_td_double')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(DateStr)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

RETURN
END SUBROUTINE ext_gr2_get_var_td_double

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_td_real ( DataHandle,Element,  DateStr,Varname, &
     Data, Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: VarName 
  real ,          INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_td_real')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(DateStr)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_var_td_real 

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_td_real8 ( DataHandle,Element,  DateStr,Varname, &
     Data, Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: VarName 
  real*8 ,        INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_td_real8')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(DateStr)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_var_td_real8 

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_td_integer ( DataHandle,Element,  DateStr,Varname, &
     Data, Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: VarName 
  integer ,       INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_td_integer')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(DateStr)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_var_td_integer 

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_td_logical ( DataHandle,Element,  DateStr,Varname, &
     Data, Count, Outcount, Status )
  
  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: VarName 
  logical ,       INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_td_logical')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(DateStr)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_var_td_logical 

!*****************************************************************************

SUBROUTINE ext_gr2_get_var_td_char ( DataHandle,Element,  DateStr,Varname, &
     Data,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: VarName 
  CHARACTER*(*) :: Data
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER       :: stat

  Status = WRF_NO_ERR
  
  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_var_td_char')

  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(VarName)//';'//trim(DateStr)//';'//trim(Element), Data, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(VarName)//';'//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  RETURN
END SUBROUTINE ext_gr2_get_var_td_char 

!******************************************************************************
!* End of get_var_td_* routines
!******************************************************************************

!******************************************************************************
!* Start of put_var_td_* routines
!******************************************************************************

SUBROUTINE ext_gr2_put_var_td_double ( DataHandle, Element, DateStr, Varname, &
     Data, Count,  Status )
  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) , INTENT(IN)  :: Element
  CHARACTER*(*) , INTENT(IN)  :: DateStr
  CHARACTER*(*) , INTENT(IN)  :: VarName
  real*8 ,            INTENT(IN) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_td_double')


  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo

     CALL gr2_build_string (td_output(DataHandle), &
          trim(Varname)//';'//trim(DateStr)//';'//trim(Element), &
          tmpstr, Count, Status)

  endif

RETURN
END SUBROUTINE ext_gr2_put_var_td_double

!*****************************************************************************

SUBROUTINE ext_gr2_put_var_td_integer ( DataHandle,Element,  DateStr, &
     Varname, Data, Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: VarName 
  integer ,       INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_td_integer')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (td_output(DataHandle), &
          trim(Varname)//';'//trim(DateStr)//';'//trim(Element), &
          tmpstr, Count, Status)

  endif

RETURN
END SUBROUTINE ext_gr2_put_var_td_integer 

!*****************************************************************************

SUBROUTINE ext_gr2_put_var_td_real ( DataHandle,Element,  DateStr,Varname, &
     Data, Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: VarName 
  real ,          INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_td_real')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (td_output(DataHandle), &
          trim(Varname)//';'//trim(DateStr)//';'//trim(Element), &
          tmpstr, Count, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_var_td_real 

!*****************************************************************************

SUBROUTINE ext_gr2_put_var_td_real8 ( DataHandle,Element,  DateStr,Varname, &
     Data, Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: VarName 
  real*8 ,        INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_td_real8')

  if (fileinfo(DataHandle)%committed) then
     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (td_output(DataHandle), &
          trim(Varname)//';'//trim(DateStr)//';'//trim(Element), &
          tmpstr, Count, Status)
  endif

  RETURN
END SUBROUTINE ext_gr2_put_var_td_real8 

!*****************************************************************************

SUBROUTINE ext_gr2_put_var_td_logical ( DataHandle,Element,  DateStr, &
     Varname, Data, Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: VarName 
  logical ,       INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_td_logical')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo

     CALL gr2_build_string (td_output(DataHandle), &
          trim(Varname)//';'//trim(DateStr)//';'//trim(Element), &
          tmpstr, Count, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_var_td_logical 

!*****************************************************************************

SUBROUTINE ext_gr2_put_var_td_char ( DataHandle,Element,  DateStr,Varname, &
     Data,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: VarName 
  CHARACTER*(*) :: Data
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_var_td_char')

  if (fileinfo(DataHandle)%committed) then

     write(tmpstr(idx),*)Data

     CALL gr2_build_string (td_output(DataHandle), &
          trim(Varname)//';'//trim(DateStr)//';'//trim(Element), &
          tmpstr, 1, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_var_td_char 

!******************************************************************************
!* End of put_var_td_* routines
!******************************************************************************


!******************************************************************************
!* Start of get_dom_ti_* routines
!******************************************************************************

SUBROUTINE ext_gr2_get_dom_ti_real ( DataHandle,Element,   Data, Count, &
     Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  real ,          INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Outcount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_ti_real')

  Status = WRF_NO_ERR

  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_dom_ti_real 

!*****************************************************************************

SUBROUTINE ext_gr2_get_dom_ti_real8 ( DataHandle,Element,   Data, Count, &
     Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  real*8 ,        INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_ti_real8')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx
 
  RETURN
END SUBROUTINE ext_gr2_get_dom_ti_real8 

!*****************************************************************************

SUBROUTINE ext_gr2_get_dom_ti_integer ( DataHandle,Element,   Data, Count, &
     Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  integer ,       INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE
  
  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_ti_integer Element: '//Element)

  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = Count
 
  RETURN
END SUBROUTINE ext_gr2_get_dom_ti_integer 

!*****************************************************************************

SUBROUTINE ext_gr2_get_dom_ti_logical ( DataHandle,Element,   Data, Count, &
     Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  logical ,       INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_ti_logical')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx
 
  RETURN
END SUBROUTINE ext_gr2_get_dom_ti_logical 

!*****************************************************************************

SUBROUTINE ext_gr2_get_dom_ti_char ( DataHandle,Element,   Data,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: Data
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER       :: stat
  INTEGER       :: endchar

  Status = WRF_NO_ERR
  
  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_ti_char')

  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(Element), Data, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  RETURN
END SUBROUTINE ext_gr2_get_dom_ti_char 

!*****************************************************************************

SUBROUTINE ext_gr2_get_dom_ti_double ( DataHandle,Element,   Data, Count, &
     Outcount, Status )
  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) , INTENT(IN)  :: Element
  real*8 ,            INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT)  :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_ti_double')

  Status = WRF_NO_ERR
   
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx
 
RETURN
END SUBROUTINE ext_gr2_get_dom_ti_double

!******************************************************************************
!* End of get_dom_ti_* routines
!******************************************************************************


!******************************************************************************
!* Start of put_dom_ti_* routines
!******************************************************************************

SUBROUTINE ext_gr2_put_dom_ti_real ( DataHandle,Element,   Data, Count,  &
     Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  real ,          INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  REAL dummy
  CHARACTER(len=1000) :: tmpstr(1000)
  character(len=2)    :: lf
  integer             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_ti_real')

  if (Element .eq. 'DX') then
     dx = Data(1)/1000.
  endif
  if (Element .eq. 'DY') then
     dy = Data(1)/1000.
  endif
  if (Element .eq. 'CEN_LAT') then
     center_lat = Data(1)
  endif
  if (Element .eq. 'CEN_LON') then
     center_lon = Data(1)
  endif  
  if (Element .eq. 'TRUELAT1') then
     truelat1 = Data(1)
  endif
  if (Element .eq. 'TRUELAT2') then
     truelat2 = Data(1)
  endif
  if (Element == 'STAND_LON') then
     proj_central_lon = Data(1)
  endif
  if (Element == 'DT') then
     timestep = Data(1)
  endif

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (ti_output(DataHandle), Element, &
          tmpstr, Count, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_dom_ti_real 

!*****************************************************************************

SUBROUTINE ext_gr2_put_dom_ti_real8 ( DataHandle,Element,   Data, Count,  &
     Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  real*8 ,        INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_ti_real8')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (ti_output(DataHandle), Element, &
          tmpstr, Count, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_dom_ti_real8 

!*****************************************************************************

SUBROUTINE ext_gr2_put_dom_ti_integer ( DataHandle,Element,   Data, Count,  &
     Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  INTEGER ,       INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  REAL dummy
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx


  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_ti_integer')

  if (Element == 'WEST-EAST_GRID_DIMENSION') then
     full_xsize = Data(1)
  else if (Element == 'SOUTH-NORTH_GRID_DIMENSION') then
     full_ysize = Data(1)
  else if (Element == 'MAP_PROJ') then
     wrf_projection = Data(1)
  else if (Element == 'BACKGROUND_PROC_ID') then
     background_proc_id = Data(1)
  else if (Element == 'FORECAST_PROC_ID') then
     forecast_proc_id = Data(1)
  else if (Element == 'PRODUCTION_STATUS') then
     production_status = Data(1)
  else if (Element == 'COMPRESSION') then
     compression = Data(1)
  endif

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (ti_output(DataHandle), Element, &
          tmpstr, Count, Status)

  endif

  call wrf_debug ( DEBUG , 'Leaving ext_gr2_put_dom_ti_integer')

  RETURN
END SUBROUTINE ext_gr2_put_dom_ti_integer 

!*****************************************************************************

SUBROUTINE ext_gr2_put_dom_ti_logical ( DataHandle,Element,   Data, Count,  &
     Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  logical ,       INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_ti_logical')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (ti_output(DataHandle), Element, &
          tmpstr, Count, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_dom_ti_logical 

!*****************************************************************************

SUBROUTINE ext_gr2_put_dom_ti_char ( DataHandle,Element,   Data,  &
     Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*),     INTENT(IN)  :: Data
  INTEGER ,       INTENT(OUT) :: Status
  REAL dummy
  CHARACTER(len=1000) :: tmpstr

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_ti_char')

  if (Element .eq. 'START_DATE') then

     !
     ! This is just a hack to fix a problem when outputting restart.  WRF
     !   outputs both the initialization time and the time of the restart 
     !   as the StartDate.  So, we ll just take the earliest.
     !
     if ((StartDate .eq. '') .or. (Data .le. StartDate)) then
        StartDate = Data
     endif

  endif

  if (fileinfo(DataHandle)%committed) then

     write(tmpstr,*)trim(Data)
     
     CALL gr2_build_string (ti_output(DataHandle), Element, &
          tmpstr, 1, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_dom_ti_char

!*****************************************************************************

SUBROUTINE ext_gr2_put_dom_ti_double ( DataHandle,Element, Data, Count, &
     Status )
  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) , INTENT(IN)  :: Element
  real*8 ,            INTENT(IN) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_ti_double')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo

     CALL gr2_build_string (ti_output(DataHandle), Element, &
          tmpstr, Count, Status)

  endif
  
  RETURN
END SUBROUTINE ext_gr2_put_dom_ti_double

!******************************************************************************
!* End of put_dom_ti_* routines
!******************************************************************************


!******************************************************************************
!* Start of get_dom_td_* routines
!******************************************************************************

SUBROUTINE ext_gr2_get_dom_td_real ( DataHandle,Element, DateStr,  Data, &
     Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  real ,          INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_td_real')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(DateStr)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_dom_td_real 

!*****************************************************************************

SUBROUTINE ext_gr2_get_dom_td_real8 ( DataHandle,Element, DateStr,  Data, &
     Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  real*8 ,        INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_td_real8')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(DateStr)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_dom_td_real8 

!*****************************************************************************

SUBROUTINE ext_gr2_get_dom_td_integer ( DataHandle,Element, DateStr,  Data, &
     Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  integer ,       INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_td_integer')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(DateStr)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_dom_td_integer 

!*****************************************************************************

SUBROUTINE ext_gr2_get_dom_td_logical ( DataHandle,Element, DateStr,  Data, &
     Count, Outcount, Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  logical ,       INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_td_logical')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(DateStr)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

  RETURN
END SUBROUTINE ext_gr2_get_dom_td_logical 

!*****************************************************************************

SUBROUTINE ext_gr2_get_dom_td_char ( DataHandle,Element, DateStr,  Data,  &
     Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER*(*) :: Data
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER       :: stat

  Status = WRF_NO_ERR
  
  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_td_char')

  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(DateStr)//';'//trim(Element), Data, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  RETURN
END SUBROUTINE ext_gr2_get_dom_td_char 

!*****************************************************************************

SUBROUTINE ext_gr2_get_dom_td_double ( DataHandle,Element, DateStr,  Data, &
     Count, Outcount, Status )
  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) , INTENT(IN)  :: Element
  CHARACTER*(*) , INTENT(IN)  :: DateStr
  real*8 ,            INTENT(OUT) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT)  :: OutCount
  INTEGER ,       INTENT(OUT) :: Status
  INTEGER          :: idx
  INTEGER          :: stat
  CHARACTER*(1000) :: VALUE

  call wrf_debug ( DEBUG , 'Entering ext_gr2_get_dom_td_double')

  Status = WRF_NO_ERR
  
  CALL gr2_get_metadata_value(global_input(DataHandle), &
       trim(DateStr)//';'//trim(Element), Value, stat)
  if (stat /= 0) then
     CALL wrf_debug ( DEBUG , "gr2_get_metadata_value failed for "//trim(DateStr)//';'//trim(Element))
     Status = WRF_WARN_VAR_NF
     RETURN
  endif

  READ(Value,*,IOSTAT=stat)(Data(idx),idx=1,Count)
  if (stat .ne. 0) then
     CALL wrf_message("Reading data from"//Value//"failed")
     Status = WRF_WARN_COUNT_TOO_LONG
     RETURN
  endif
  Outcount = idx

RETURN
END SUBROUTINE ext_gr2_get_dom_td_double

!******************************************************************************
!* End of get_dom_td_* routines
!******************************************************************************


!******************************************************************************
!* Start of put_dom_td_* routines
!******************************************************************************


SUBROUTINE ext_gr2_put_dom_td_real8 ( DataHandle,Element, DateStr,  Data, &
     Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  real*8 ,        INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_td_real8')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo

     CALL gr2_build_string (td_output(DataHandle), &
          trim(DateStr)//';'//trim(Element), tmpstr, &
          Count, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_dom_td_real8 

!*****************************************************************************

SUBROUTINE ext_gr2_put_dom_td_integer ( DataHandle,Element, DateStr,  Data, &
     Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  integer ,       INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_td_integer')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (td_output(DataHandle), &
          trim(DateStr)//';'//trim(Element), tmpstr, &
          Count, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_dom_td_integer

!*****************************************************************************

SUBROUTINE ext_gr2_put_dom_td_logical ( DataHandle,Element, DateStr,  Data, &
     Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  logical ,       INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_td_logical')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (td_output(DataHandle), &
          trim(DateStr)//';'//trim(Element), tmpstr, &
          Count, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_dom_td_logical

!*****************************************************************************

SUBROUTINE ext_gr2_put_dom_td_char ( DataHandle,Element, DateStr,  Data, &
     Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  CHARACTER(len=*), INTENT(IN)  :: Data
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1)

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_td_char')

  if (fileinfo(DataHandle)%committed) then

     write(tmpstr(1),*)Data

     CALL gr2_build_string (td_output(DataHandle), &
          trim(DateStr)//';'//trim(Element), tmpstr, &
          1, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_dom_td_char 

!*****************************************************************************

SUBROUTINE ext_gr2_put_dom_td_double ( DataHandle,Element, DateStr,  Data, &
     Count,  Status )
  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) , INTENT(IN)  :: Element
  CHARACTER*(*) , INTENT(IN)  :: DateStr
  real*8 ,            INTENT(IN) :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_td_double')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo

     CALL gr2_build_string (td_output(DataHandle), &
          trim(DateStr)//';'//trim(Element), tmpstr, &
          Count, Status)

  endif

RETURN
END SUBROUTINE ext_gr2_put_dom_td_double

!*****************************************************************************

SUBROUTINE ext_gr2_put_dom_td_real ( DataHandle,Element, DateStr,  Data, &
     Count,  Status )

  USE gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"
  INTEGER ,       INTENT(IN)  :: DataHandle
  CHARACTER*(*) :: Element
  CHARACTER*(*) :: DateStr
  real ,          INTENT(IN)  :: Data(*)
  INTEGER ,       INTENT(IN)  :: Count
  INTEGER ,       INTENT(OUT) :: Status
  CHARACTER(len=1000) :: tmpstr(1000)
  INTEGER             :: idx

  call wrf_debug ( DEBUG , 'Entering ext_gr2_put_dom_td_real')

  if (fileinfo(DataHandle)%committed) then

     do idx = 1,Count
        write(tmpstr(idx),'(G17.10)')Data(idx)
     enddo
     
     CALL gr2_build_string (td_output(DataHandle), &
          trim(DateStr)//';'//trim(Element), tmpstr, &
          Count, Status)

  endif

  RETURN
END SUBROUTINE ext_gr2_put_dom_td_real 


!******************************************************************************
!* End of put_dom_td_* routines
!******************************************************************************


SUBROUTINE gr2_get_new_handle(DataHandle)
  USE gr2_data_info
  IMPLICIT NONE
  
  INTEGER ,       INTENT(OUT)  :: DataHandle
  INTEGER :: i

  DataHandle = -1
  do i=firstFileHandle, maxFileHandles
     if (.NOT. fileinfo(i)%used) then
        DataHandle = i
        fileinfo(i)%used = .true.
        exit
     endif
  enddo

  RETURN
END SUBROUTINE gr2_get_new_handle

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


!*****************************************************************************

SUBROUTINE gr2_retrieve_data (MemoryOrder, MemoryStart, MemoryEnd, xsize, ysize, &
     zsize, z, FieldType, Field, data)
  
  IMPLICIT NONE

#include "wrf_io_flags.h"

  character*(*)                 ,intent(in)    :: MemoryOrder
  integer                       ,intent(in)    :: xsize, ysize, zsize
  integer                       ,intent(in)    :: z
  integer,dimension(*)          ,intent(in)    :: MemoryStart, MemoryEnd
  integer                       ,intent(in)    :: FieldType
  real                          ,intent(in),       &
       dimension( 1:1,MemoryStart(1):MemoryEnd(1), &
       MemoryStart(2):MemoryEnd(2), &
       MemoryStart(3):MemoryEnd(3) )           :: Field
  real   ,dimension(1:xsize,1:ysize),intent(inout) :: data

  integer                                      :: x, y, idx
  integer, dimension(:,:),   pointer           :: mold
  integer                                      :: istat
  integer                                      :: dim1
  
  ALLOCATE(mold(1:xsize,1:ysize), STAT=istat)
  if (istat .ne. 0) then
     print *,'Could not allocate space for mold, returning'
     return
  endif

  !
  ! Set the size of the first dimension of the data array (dim1) to xsize.  
  !    If the MemoryOrder is Z or z, dim1 is overridden below.
  !
  dim1 = xsize

  SELECT CASE (MemoryOrder)
  CASE ('XYZ')
     data = Field(1,1:xsize,1:ysize,z)
  CASE ('C')
     data = Field(1,1:xsize,1:ysize,z)
  CASE ('XZY')
     data = Field(1,1:xsize,z,1:ysize)
  CASE ('YXZ')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,y,x,z)
        enddo
     enddo
  CASE ('YZX')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,y,z,x)
        enddo
     enddo
  CASE ('ZXY')
     data = Field(1,z,1:xsize,1:ysize)
  CASE ('ZYX')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,z,y,x)
        enddo
     enddo
  CASE ('XY')
     data = Field(1,1:xsize,1:ysize,1)
  CASE ('YX')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,y,x,1)
        enddo
     enddo
     
  CASE ('XSZ')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,y,z,x)
        enddo
     enddo
  CASE ('XEZ')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,y,z,x)
        enddo
     enddo
  CASE ('YSZ')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,x,z,y)
        enddo
     enddo
  CASE ('YEZ')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,x,z,y)
        enddo
     enddo
     
  CASE ('XS')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,y,x,1)
        enddo
     enddo
  CASE ('XE')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,y,x,1)
        enddo
     enddo
  CASE ('YS')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,x,y,1)
        enddo
     enddo
  CASE ('YE')
     do x = 1,xsize
        do y = 1,ysize
           data(x,y) = Field(1,x,y,1)
        enddo
     enddo
  CASE ('Z')
     data(1:zsize,1) = Field(1,1:zsize,1,1)
     dim1 = zsize
  CASE ('z')
     data(1:zsize,1) = Field(1,zsize:1,1,1)
     dim1 = zsize
  CASE ('0')
     data(1,1) = Field(1,1,1,1)
  END SELECT
  
  ! 
  ! Here, we convert any integer fields to real
  !
  if (FieldType == WRF_INTEGER) then
     mold = 0
     do idx=1,dim1
        !
        ! The parentheses around data(idx,:) are needed in order
        !   to fix a bug with transfer with the xlf compiler on NCARs
        !   IBM (bluesky).
        !
        data(idx,:)=transfer((data(idx,:)),mold)
     enddo
  endif

  deallocate(mold)
  
  return

end subroutine gr2_retrieve_data

!*****************************************************************************

SUBROUTINE gr2_get_levels(VarName, zidx, zsize, soil_layers, vert_stag, &
     fraction, vert_unit1, vert_unit2, vert_sclFctr1, vert_sclFctr2, &
     level1, level2)

  use gr2_data_info
  IMPLICIT NONE

  integer :: zidx
  integer :: zsize
  logical :: soil_layers
  logical :: vert_stag
  logical :: fraction
  integer :: vert_unit1, vert_unit2
  integer :: vert_sclFctr1, vert_sclFctr2
  integer :: level1
  integer :: level2
  character (LEN=*) :: VarName

  ! Setup vert_unit, and vertical levels in grib units

  if ((VarName .eq. 'LANDUSEF') .or. (VarName .eq. 'SOILCTOP') &
       .or. (VarName .eq. 'SOILCBOT')) then
     vert_unit1 = 105;
     vert_unit2 = 255;
     vert_sclFctr1 = 0
     vert_sclFctr2 = 0
     level1 = zidx
     level2 = 0
  else if ((zsize .gt. 1) .and. (.not. soil_layers) .and. (.not. fraction)) &
       then
     vert_unit1 = 111;
     vert_unit2 = 255;
     vert_sclFctr1 = 4
     vert_sclFctr2 = 4
     if (vert_stag) then
        level1 = (10000*full_eta(zidx)+0.5)
     else
        level1 = (10000*half_eta(zidx)+0.5)
     endif
     level2 = 0
  else
     ! Set the vertical coordinate and level for soil and 2D fields
     if (fraction) then
        vert_unit1 = 105
        vert_unit2 = 255
        level1 = zidx
        level2 = 0
        vert_sclFctr1 = 0
        vert_sclFctr2 = 0
     else if (soil_layers) then
        vert_unit1 = 106
        vert_unit2 = 106
        level1 = 100*(soil_depth(zidx) - 0.5*soil_thickness(zidx))+0.5
        level2 = 100*(soil_depth(zidx) + 0.5*soil_thickness(zidx))+0.5
        vert_sclFctr1 = 2
        vert_sclFctr2 = 2
     else if (VarName .eq. 'mu') then
        vert_unit1 = 105
        vert_unit2 = 255
        level1 = 0
        level2 = 0
        vert_sclFctr1 = 0
        vert_sclFctr2 = 0
     else if ((VarName .eq. 'Q2') .or. (VarName .eq. 'TH2') .or. &
        (VarName .eq. 'T2')) then
        vert_unit1 = 103
        vert_unit2 = 255
        level1 = 2
        level2 = 0
        vert_sclFctr1 = 0
        vert_sclFctr2 = 0
     else if ((VarName .eq. 'Q10') .or. (VarName .eq. 'TH10') .or. &
          (VarName .eq. 'U10') .or. (VarName .eq. 'V10')) then
        vert_unit1 = 103
        vert_unit2 = 255
        level1 = 10
        level2 = 0
        vert_sclFctr1 = 0
        vert_sclFctr2 = 0
     else 
        vert_unit1 = 1
        vert_unit2 = 255
        level1 = 0
        level2 = 0
        vert_sclFctr1 = 0
        vert_sclFctr2 = 0
     endif
  endif

end SUBROUTINE gr2_get_levels

!*****************************************************************************

subroutine gr2_create_w(StartDate, cgrib, lcgrib, production_status, Disc, &
     center, subcenter, MasterTblV, LocalTblV, ierr, msg)

  implicit none

  character*24 ,intent(in)     :: StartDate
  character*(*),intent(inout)  :: cgrib
  integer      ,intent(in)     :: lcgrib
  integer      ,intent(in)     :: production_status
  integer      ,intent(out)    :: ierr
  character*(*),intent(out)    :: msg
  integer , dimension(13)      :: listsec1
  integer , dimension(2)       :: listsec0
  integer                      :: slen
  integer , intent(in)         :: Disc, center, subcenter, MasterTblV, LocalTblV

  ! 
  ! Create the grib message
  !
  listsec0(1) = Disc       ! Discipline (Table 0.0)
  listsec0(2) = 2          ! Grib edition number

  listsec1(1) = center     ! Id of Originating Center (255 for missing)
  listsec1(2) = subcenter  ! Id of originating sub-center (255 for missing)
  listsec1(3) = MasterTblV ! Master Table Version #
  listsec1(4) = LocalTblV  ! Local table version #
  listsec1(5) = 1          ! Significance of reference time, 1 indicates start of forecast

  READ(StartDate(1:4),  '(I4)') listsec1(6) ! Year of reference

  READ(StartDate(6:7),  '(I2)') listsec1(7) ! Month of reference

  READ(StartDate(9:10), '(I2)') listsec1(8) ! Day of reference

  slen = LEN(StartDate)

  if (slen.GE.13) then
     read(StartDate(12:13),'(I2)') listsec1(9)
  else
     listsec1(9) = 0
  endif

  if (slen.GE.16) then
     read(StartDate(15:16),'(I2)') listsec1(10)
  else
     listsec1(10) = 0
  endif

  if (slen.GE.19) then
     read(StartDate(18:19),'(I2)') listsec1(11)
  else
     listsec1(11) = 0
  end if

  listsec1(12) = production_status  ! Production status of data
  listsec1(13) = 1     ! Type of data (1 indicates forecast products)

  call gribcreate(cgrib,lcgrib,listsec0,listsec1,ierr)

  if (ierr .ne. 0) then
     write(msg,*) 'gribcreate failed with ierr: ',ierr
  else
     msg = ''
  endif
  
end SUBROUTINE gr2_create_w


!*****************************************************************************
subroutine gr2_addgrid_w(cgrib, lcgrib, central_lat, central_lon, wrf_projection, &
     latin1, latin2, nx, ny, dx, dy, center_lat, center_lon, ierr,msg)
  
  implicit none

  character*(*)            ,intent(inout)   :: cgrib
  integer                  ,intent(in)      :: lcgrib
  real                     ,intent(in)      :: central_lat
  real                     ,intent(in)      :: central_lon
  integer                  ,intent(in)      :: wrf_projection
  real                     ,intent(in)      :: latin1
  real                     ,intent(in)      :: latin2
  integer                  ,intent(in)      :: nx
  integer                  ,intent(in)      :: ny
  real                     ,intent(in)      :: dx
  real                     ,intent(in)      :: dy
  real                     ,intent(in)      :: center_lat
  real                     ,intent(in)      :: center_lon
  integer                  ,intent(out)     :: ierr
  character*(*)            ,intent(out)     :: msg
  integer, dimension(5)                     :: igds
  integer, parameter                        :: igdstmplen = 25
  integer, dimension(igdstmplen)            :: igdstmpl
  integer, parameter                        :: idefnum = 0
  integer, dimension(idefnum)               :: ideflist
  real                                      :: LLLa, LLLo, URLa, URLo
  real                                      :: incrx, incry
  real, parameter                           :: deg_to_microdeg = 1e6
  real, parameter                           :: km_to_mm = 1e6
  real, parameter                           :: km_to_m = 1e3
  real, parameter                           :: DEG_TO_RAD = PI/180
  real, parameter                           :: RAD_TO_DEG = 180/PI
  real, parameter                           :: ERADIUS = 6370.0

  igds(1) = 0      ! Source of grid definition
  igds(2) = nx*ny  ! Number of points in grid
  igds(3) = 0      ! 
  igds(4) = 0

  ! Here, setup the parameters that are common to all WRF projections

  igdstmpl(1) = 1       ! Shape of earth (1 for spherical with specified radius)
  igdstmpl(2) = 0       ! Scale factor for earth radius
  igdstmpl(3) = ERADIUS*km_to_m ! Radius of earth
  igdstmpl(4) = 0       ! Scale factor for major axis
  igdstmpl(5) = 0       ! Major axis
  igdstmpl(6) = 0       ! Scale factor for minor axis
  igdstmpl(7) = 0       ! Minor axis
  igdstmpl(8) = nx      ! Number of points along x axis
  igdstmpl(9) = ny      ! Number of points along y axis
  
  !
  ! Setup increments in "x" and "y" direction.  For LATLON projection
  !   increments need to be in degrees.  For all other projections, 
  !   increments are in km.
  !
  if ((wrf_projection .eq. WRF_LATLON) &
       .or. (wrf_projection .eq. WRF_CASSINI)) then
     incrx = (dx/ERADIUS) * RAD_TO_DEG
     incry = (dy/ERADIUS) * RAD_TO_DEG
  else
     incrx = dx
     incry = dy
  endif

  ! Latitude and longitude of first (i.e., lower left) grid point
  call get_ll_latlon(central_lat, central_lon, wrf_projection, &
       latin1, latin2, nx, ny, incrx, incry, center_lat, center_lon, &
       LLLa, LLLo, URLa, URLo, ierr);

  select case (wrf_projection)

  case(WRF_LATLON,WRF_CASSINI)
     igds(5) = 0
     igdstmpl(10) = 0    ! Basic Angle of init projection (not important to us)
     igdstmpl(11) = 0    ! Subdivision of basic angle
     igdstmpl(12) = LLLa*deg_to_microdeg
     igdstmpl(13) = LLLo*deg_to_microdeg
     call gr2_convert_lon(igdstmpl(13))
     igdstmpl(14) = 128  ! Resolution and component flags
     igdstmpl(15) = URLa*deg_to_microdeg
     igdstmpl(16) = URLo*deg_to_microdeg
     call gr2_convert_lon(igdstmpl(16))

     ! Warning, the following assumes that dx and dy are valid at the equator.
     !    It is not clear in WRF where dx and dy are valid for latlon projections
     igdstmpl(17) = incrx*deg_to_microdeg ! i-direction increment in micro degs
     igdstmpl(18) = incry*deg_to_microdeg ! j-direction increment in micro degs

     igdstmpl(19) = 64   ! Scanning mode
  case(WRF_MERCATOR)
     igds(5) = 10
     igdstmpl(10) = LLLa*deg_to_microdeg
     igdstmpl(11) = LLLo*deg_to_microdeg
     call gr2_convert_lon(igdstmpl(11))
     igdstmpl(12) = 128  ! Resolution and component flags
     igdstmpl(13) = latin1*deg_to_microdeg  ! "True" latitude
     igdstmpl(14) = URLa*deg_to_microdeg
     igdstmpl(15) = URLo*deg_to_microdeg
     call gr2_convert_lon(igdstmpl(15))
     igdstmpl(16) = 64   ! Scanning mode
     igdstmpl(17) = 0    ! Orientation of grid between i-direction and equator
     igdstmpl(18) = dx*km_to_mm   ! i-direction increment
     igdstmpl(19) = dy*km_to_mm   ! j-direction increment
  case(WRF_LAMBERT)
     igds(5) = 30
     
     igdstmpl(10) = LLLa*deg_to_microdeg
     igdstmpl(11) = LLLo*deg_to_microdeg
     call gr2_convert_lon(igdstmpl(11))
     igdstmpl(12) = 128 ! Resolution and component flag
     igdstmpl(13) = latin1*deg_to_microdeg ! Latitude where Dx and Dy are specified
     igdstmpl(14) = central_lon*deg_to_microdeg
     call gr2_convert_lon(igdstmpl(14))
     igdstmpl(15) = dx*km_to_mm  ! x-dimension grid-spacing  in units of m^-3
     igdstmpl(16) = dy*km_to_mm
     if (center_lat .lt. 0) then
        igdstmpl(17) = 1
     else
        igdstmpl(17) = 0
     endif
     igdstmpl(18) = 64   ! Scanning mode
     igdstmpl(19) = latin1*deg_to_microdeg
     igdstmpl(20) = latin2*deg_to_microdeg
     igdstmpl(21) = -90*deg_to_microdeg
     igdstmpl(22) = central_lon*deg_to_microdeg
     call gr2_convert_lon(igdstmpl(22))

  case(WRF_POLAR_STEREO)
     igds(5) = 20
     igdstmpl(10) = LLLa*deg_to_microdeg
     igdstmpl(11) = LLLo*deg_to_microdeg
     call gr2_convert_lon(igdstmpl(11))
     igdstmpl(12) = 128 ! Resolution and component flag
     igdstmpl(13) = latin1*deg_to_microdeg ! Latitude where Dx and Dy are specified
     igdstmpl(14) = central_lon*deg_to_microdeg
     call gr2_convert_lon(igdstmpl(14))
     igdstmpl(15) = dx*km_to_mm  ! x-dimension grid-spacing  in units of m^-3
     igdstmpl(16) = dy*km_to_mm
     if (center_lat .lt. 0) then
        igdstmpl(17) = 1
     else
        igdstmpl(17) = 0
     endif
     igdstmpl(18) = 64   ! Scanning mode

  case default
     write(msg,*) 'invalid WRF projection: ',wrf_projection
     ierr = -1
     return
  end select


  call addgrid(cgrib,lcgrib,igds,igdstmpl,igdstmplen,ideflist,idefnum,ierr)
  if (ierr .ne. 0) then
     write(msg,*) 'addgrid failed with ierr: ',ierr
  else
     msg = ''
  endif

end subroutine gr2_addgrid_w

!*****************************************************************************

subroutine gr2_addfield_w(cgrib, lcgrib, VarName, parmcat, parmnum, DecScl, &
     BinScl, fcst_secs, vert_unit1, vert_unit2, vert_sclFctr1, vert_sclFctr2, &
     numlevels, levels, ngrdpts, background_proc_id, forecast_proc_id, &
     compression, fld, ierr, msg)
  
  implicit none

  character*(*)            ,intent(inout)   :: cgrib
  integer                  ,intent(in)      :: lcgrib
  character (LEN=*)        ,intent(in)      :: VarName
  integer                  ,intent(in)      :: parmcat,parmnum,DecScl,BinScl
  real                     ,intent(in)      :: fcst_secs
  integer                  ,intent(in)      :: vert_unit1, vert_unit2
  integer                  ,intent(in)      :: vert_sclFctr1, vert_sclFctr2
  integer                  ,intent(in)      :: numlevels
  integer, dimension(*)    ,intent(in)      :: levels
  integer                  ,intent(in)      :: ngrdpts
  real                     ,intent(in)      :: fld(ngrdpts)
  integer                  ,intent(in)      :: background_proc_id
  integer                  ,intent(in)      :: forecast_proc_id
  integer                  ,intent(in)      :: compression
  integer                  ,intent(out)     :: ierr
  character*(*)            ,intent(out)     :: msg
  integer                                   :: ipdsnum
  integer, parameter                        :: ipdstmplen = 15
  integer, dimension(ipdstmplen)            :: ipdstmpl
  integer                                   :: numcoord
  integer, dimension(numlevels)             :: coordlist
  integer                                   :: idrsnum
  integer, parameter                        :: idrstmplen = 7
  integer, dimension(idrstmplen)            :: idrstmpl
  integer                                   :: ibmap
  integer, dimension(1)                     :: bmap

  if (numlevels .gt. 2) then
     ipdsnum = 1000           ! Product definition tmplate (1000 for cross-sxn)
  else
     ipdsnum = 0              ! Product definition template (0 for horiz grid)
  endif

  ipdstmpl(1) = parmcat    ! Parameter category
  ipdstmpl(2) = parmnum    ! Parameter number
  ipdstmpl(3) = 2          ! Type of generating process (2 for forecast)
  ipdstmpl(4) = background_proc_id ! Background generating process id
  ipdstmpl(5) = forecast_proc_id   ! Analysis or forecast generating process id
  ipdstmpl(6) = 0          ! Data cutoff period (Hours)
  ipdstmpl(7) = 0          ! Data cutoff period (minutes)
  ipdstmpl(8) = 13         ! Time range indicator (13 for seconds)
  ipdstmpl(9) = NINT(fcst_secs) ! Forecast time

  if (ipdsnum .eq. 1000) then
     numcoord = numlevels
     coordlist = levels(1:numlevels)

     !
     ! Set Data Representation templ (Use 0 for vertical cross sections,
     !    since there seems to be a bug in g2lib for JPEG2000 and PNG)
     !
     idrsnum = 0

  else if (ipdsnum .eq. 0) then
     ipdstmpl(10) = vert_unit1    ! Type of first surface (111 for Eta level)
     ipdstmpl(11) = vert_sclFctr1 ! Scale factor for 1st surface
     ipdstmpl(12) = levels(1)     ! First fixed surface
     ipdstmpl(13) = vert_unit2    ! Type of second fixed surface
     ipdstmpl(14) = vert_sclFctr2 ! Scale factor for 2nd surface
     if (numlevels .eq. 2) then 
        ipdstmpl(15) = levels(2)
     else
        ipdstmpl(15) = 0
     endif
     numcoord = 0
     coordlist(1) = 0

     ! Set Data Representation templ (40 for JPEG2000, 41 for PNG)  
     idrsnum = compression

  endif


  if (idrsnum == 40) then    ! JPEG 2000

     idrstmpl(1) = 255       ! Reference value - ignored on input
     idrstmpl(2) = BinScl    ! Binary scale factor
     idrstmpl(3) = DecScl    ! Decimal scale factor 
     idrstmpl(4) = 0         ! number of bits for each data value - ignored on input
     idrstmpl(5) = 0         ! Original field type - ignored on input
     idrstmpl(6) = 0         ! 0 for lossless compression
     idrstmpl(7) = 255       ! Desired compression ratio if idrstmpl(6) != 0

  else if (idrsnum == 41) then ! PNG

     idrstmpl(1) = 255       ! Reference value - ignored on input
     idrstmpl(2) = BinScl    ! Binary scale factor
     idrstmpl(3) = DecScl    ! Decimal scale factor 
     idrstmpl(4) = 0         ! number of bits for each data value - ignored on input
     idrstmpl(5) = 0         ! Original field type - ignored on input

  else if (idrsnum == 0) then! Simple packing 

     idrstmpl(1) = 255       ! Reference value - ignored on input
     idrstmpl(2) = BinScl    ! Binary scale factor
     idrstmpl(3) = DecScl    ! Decimal scale factor 
     idrstmpl(4) = 0         ! number of bits for each data value - ignored on input
     idrstmpl(5) = 0         ! Original field type - ignored on input
     
  else
     
     write (msg,*) 'addfield failed because Data Representation template',&
          idrsnum,' is invalid'
     ierr = 1
     return

  endif

  ibmap = 255                ! Flag for bitmap
  
  call addfield(cgrib, lcgrib, ipdsnum, ipdstmpl, ipdstmplen, coordlist,      &
       numcoord, idrsnum, idrstmpl, idrstmplen, fld, ngrdpts, ibmap,          &
       bmap, ierr)

  if (ierr .ne. 0) then
     write(msg,*) 'addfield failed with ierr: ',ierr
  else
     msg = ''
  endif

end subroutine gr2_addfield_w

!*****************************************************************************

subroutine gr2_fill_local_use(DataHandle,string,VarName,fcsts,msg,status)

  use gr2_data_info
  IMPLICIT NONE
#include "wrf_status_codes.h"

  integer,         intent(in)    :: DataHandle
  character*(*)   ,intent(inout) :: string
  character*(*)   ,intent(in)    :: VarName
  integer                        :: center, subcenter, MasterTblV, LocalTblV, &
       Disc, Category, ParmNum, DecScl, BinScl
  integer         ,intent(out)   :: status
  character*(*)   ,intent(out)   :: msg
  integer , parameter            :: lcgrib = 1000000
  character (lcgrib)             :: cgrib
  real, dimension(1,1)           :: data
  integer                        :: lengrib
  integer                        :: lcsec2
  integer                        :: fcsts
  integer                        :: bytes_written
  
  ! 
  ! Set data to a default dummy value.
  !
  data = 1.0

  !
  ! This statement prevents problems when calling addlocal in the grib2
  !   library.  Basically, if addlocal is called with an empty string, it
  !   will be encoded correctly by the grib2 routine, but the grib2 routines
  !   that read the data (i.e., getgb2) will segfault.  This prevents that 
  !   segfault.
  !

  if (string .eq. '') string = 'none'

  CALL get_parminfo(VarName, center, subcenter, MasterTblV, &
       LocalTblV, Disc, Category, ParmNum, DecScl, BinScl, status)
  if (status .ne. 0) then
     write(msg,*) 'Could not find parameter for '//   &
          trim(VarName)//'   Skipping output of '//trim(VarName)
     call wrf_message(trim(msg))
     Status =  WRF_GRIB2_ERR_GRIB2MAP
     return
  endif

  !
  ! Create the indicator and identification sections (sections 0 and 1)
  !
  CALL gr2_create_w(StartDate, cgrib, lcgrib, production_status, Disc, &
             center, subcenter, MasterTblV, LocalTblV, status, msg)
  if (status .ne. 0) then
     call wrf_message(trim(msg))
     Status = WRF_GRIB2_ERR_GRIBCREATE
     return
  endif

  ! 
  ! Add the local use section
  !
  lcsec2 = len_trim(string)
  call addlocal(cgrib,lcgrib,string,lcsec2,status)
  if (status .ne. 0) then
     call wrf_message(trim(msg))
     Status = WRF_GRIB2_ERR_ADDLOCAL
     return
  endif

  !
  ! Add the grid definition section (section 3) using a 1x1 grid
  !
  call gr2_addgrid_w(cgrib, lcgrib, center_lat, proj_central_lon,  &
       wrf_projection, truelat1, truelat2, 1, 1, dx, dy,       &
       center_lat, center_lon, status, msg)
  if (status .ne. 0) then
     call wrf_message(trim(msg))
     Status = WRF_GRIB2_ERR_ADDGRIB
     return
  endif

  !
  ! Add the Product Definition, Data representation, bitmap 
  !      and data sections (sections 4-7)
  !
  call gr2_addfield_w(cgrib, lcgrib, VarName, Category, ParmNum, DecScl, &
       BinScl, fcsts, 1, 255, 0, 0, 1, 0, 1, &
       background_proc_id, forecast_proc_id, compression, data, status, msg)
  if (status .ne. 0) then
     call wrf_message(trim(msg))
     Status = WRF_GRIB2_ERR_ADDFIELD
     return
  endif

  !
  ! Close out the message
  !
  
  call gribend(cgrib,lcgrib,lengrib,status)
  if (status .ne. 0) then
     write(msg,*) 'gribend failed with status: ',status     
     call wrf_message(trim(msg))
     Status = WRF_GRIB2_ERR_GRIBEND
     return
  endif

  ! 
  ! Write the data to the file
  !
  
  call bawrite(DataHandle, -1, lengrib, bytes_written, cgrib)
!!  call write_file_n(fileinfo(DataHandle)%FileFd, cgrib, lengrib, status)
  if (bytes_written .ne. lengrib) then
     write(msg,*) '2 Error writing cgrib to file, wrote: ', &
          bytes_written, ' bytes.  Tried to write ', lengrib, ' bytes'
     call wrf_message(trim(msg))
     Status = WRF_GRIB2_ERR_WRITE
     return
  endif

  ! Set string back to the original blank value
  if (string .eq. '') string = ''

  return

end subroutine gr2_fill_local_use

!*****************************************************************************
!
! Set longitude to be in the range of 0-360 degrees.
!
!*****************************************************************************

subroutine gr2_convert_lon(value)

  IMPLICIT NONE

  integer, intent(inout) :: value
  real, parameter                           :: deg_to_microdeg = 1e6

  do while (value .lt. 0) 
     value = value + 360*deg_to_microdeg
  enddo

  do while (value .gt. 360*deg_to_microdeg) 
     value = value - 360*deg_to_microdeg
  enddo

end subroutine gr2_convert_lon


!*****************************************************************************
!
! Add a time to the list of times
!
!*****************************************************************************

subroutine gr2_add_time(DataHandle,addTime)

  USE gr2_data_info
  IMPLICIT NONE

  integer           :: DataHandle
  character (len=*) :: addTime
  integer           :: idx
  logical           :: already_have = .false.
  logical           :: swap
  character (len=len(addTime)) :: tmp
  character (DateStrLen), dimension(:),pointer  :: tmpTimes(:)
  integer,parameter :: allsize = 50
  integer           :: ierr
  
  already_have = .false.
  do idx = 1,fileinfo(DataHandle)%NumberTimes 
     if (addTime .eq. fileinfo(DataHandle)%Times(idx)) then
        already_have = .true.
     endif
  enddo
  
  if (.not. already_have) then
     fileinfo(DataHandle)%NumberTimes = fileinfo(DataHandle)%NumberTimes + 1

     if (fileinfo(DataHandle)%NumberTimes .gt. &
          fileinfo(DataHandle)%sizeAllocated) then

        if (fileinfo(DataHandle)%NumberTimes .eq. 1) then

           if (allocated(fileinfo(DataHandle)%Times)) &
                deallocate(fileinfo(DataHandle)%Times)

           allocate(fileinfo(DataHandle)%Times(allsize), stat = ierr)
           if (ierr .ne. 0) then
              call wrf_message('Could not allocate space for Times 1, exiting')
              stop
           endif

           fileinfo(DataHandle)%sizeAllocated = allsize

        else

           allocate(tmpTimes(fileinfo(DataHandle)%NumberTimes), stat=ierr)

           tmpTimes = &
                fileinfo(DataHandle)%Times(1:fileinfo(DataHandle)%NumberTimes)

           deallocate(fileinfo(DataHandle)%Times)

           allocate(&
                fileinfo(DataHandle)%Times(fileinfo(DataHandle)%sizeAllocated+allsize), stat=ierr)

           if (ierr .ne. 0) then
              call wrf_message('Could not allocate space for Times 2, exiting')
              stop
           endif

           fileinfo(DataHandle)%Times(1:fileinfo(DataHandle)%NumberTimes) = &
                tmpTimes

           deallocate(tmpTimes)
           
        endif
        
     endif

     fileinfo(DataHandle)%Times(fileinfo(DataHandle)%NumberTimes) = addTime
  
     ! Sort the Times array

     swap = .true.
     do while (swap)
        swap = .false.
        do idx = 1,fileinfo(DataHandle)%NumberTimes - 1
           if (fileinfo(DataHandle)%Times(idx) .gt. fileinfo(DataHandle)%Times(idx+1)) then
              tmp = fileinfo(DataHandle)%Times(idx)
              fileinfo(DataHandle)%Times(idx) = fileinfo(DataHandle)%Times(idx+1)
              fileinfo(DataHandle)%Times(idx+1) = tmp
              swap = .true.
           endif
        enddo
     enddo

  endif

  return

end subroutine gr2_add_time


!*****************************************************************************
!
! Fill an array of levels
!
!*****************************************************************************

subroutine gr2_fill_levels(DataHandle,VarName,levels,ierr)

  USE gr2_data_info
  USE grib_mod
  IMPLICIT NONE

#include "wrf_status_codes.h"


  integer            :: DataHandle
  character (len=*)  :: VarName
  REAL,DIMENSION(*)  :: levels
  integer            :: ierr
  integer :: JIDS(JIDSSIZE), JPDTN, JPDT(JPDTSIZE), JGDTN, &
       JGDT(JGDTSIZE)
  type(gribfield)    :: gfld
  integer            :: status, fields_to_skip
  logical            :: unpack
  integer            :: center, subcenter, MasterTblV, LocalTblV, &
       Disc, Category, ParmNum, DecScl, BinScl
  CHARACTER (LEN=maxMsgSize) :: msg


  CALL get_parminfo(VarName, center, subcenter, MasterTblV, &
       LocalTblV, Disc, Category, ParmNum, DecScl, BinScl, status)
  if (status .ne. 0) then
     write(msg,*) 'Could not find parameter for '//   &
          trim(VarName)//'   Skipping output of '//trim(VarName)
     call wrf_message(trim(msg))
     ierr = -1
     return
  endif


  !
  ! First, set all values to wild, then specify necessary values
  !
  call gr2_g2lib_wildcard(JIDS, JPDT, JGDT)

  JIDS(1) = center
  JIDS(2) = subcenter
  JIDS(3) = MasterTblV
  JIDS(4) = LocalTblV
  JIDS(5) = 1           ! Indicates that time is "Start of Forecast"
  JIDS(13) = 1          ! Type of processed data (1 for forecast products)
  
  JPDTN = 1000          ! Product definition template number
  JPDT(1) = Category
  JPDT(2) = ParmNum
  JPDT(3) = 2           ! Generating process id

  JGDTN    = -1         ! Indicates that any Grid Display Template is a match
  
  UNPACK   = .TRUE.     ! Unpack bitmap and data values


  fields_to_skip = 0

  CALL GETGB2(DataHandle, 0, fields_to_skip, -1, Disc, JIDS, JPDTN, &
       JPDT, JGDTN, JGDT, UNPACK, fileinfo(DataHandle)%recnum, &
       gfld, status)
  if (status .eq. 99) then
     write(msg,*)'Could not find field '//trim(VarName)//&
          ' continuing.'
     call wrf_message(trim(msg))
     ierr = -1
     return
  else if (status .ne. 0) then
     write(msg,*)'Retrieving scalar data field '//trim(VarName)//&
          ' failed, continuing.'
     call wrf_message(trim(msg))
     ierr = -1
     return
  endif
  
  levels(1:gfld%ndpts) = gfld%fld(1:gfld%ndpts)
  ierr = 0
  
end subroutine gr2_fill_levels


!*****************************************************************************
!
! Set values for search array arguments for getgb2 to missing.
!
!*****************************************************************************

subroutine gr2_g2lib_wildcard(JIDS, JPDT, JGDT)

  USE gr2_data_info
  integer :: JIDS(*), JPDT(*), JGDT(*)

  do idx = 1,JIDSSIZE
     JIDS(idx) = -9999
  enddo
  
  do idx=1,JPDTSIZE
     JPDT(idx) = -9999
  enddo
  
  do idx = 1,JGDTSIZE
     JGDT(idx) = -9999
  enddo

  return

end subroutine gr2_g2lib_wildcard
!*****************************************************************************
!
! Retrieve a metadata value from the input string
!
!*****************************************************************************

subroutine gr2_get_metadata_value(instring, Key, Value, stat)
  character(len=*),intent(in)  :: instring
  character(len=*),intent(in)  :: Key
  character(len=*),intent(out) :: Value
  integer         ,intent(out) :: stat
  integer :: Key_pos, equals_pos, line_end
  character :: lf

  lf=char(10)

  Value = 'abc'

  !
  ! Find Starting position of Key
  !
  Key_pos = index(instring, lf//' '//Key//' =')
  if (Key_pos .eq. 0) then
     stat = -1
     return
  endif

  !
  ! Find position of the "=" after the Key
  !
  equals_pos = index(instring(Key_pos:len(instring)), "=") + Key_pos
  if (equals_pos .eq. Key_pos) then
     stat = -1
     return
  endif

  !
  ! Find end of line
  !
  line_end = index(instring(equals_pos:len(instring)), lf) + equals_pos

  !
  ! Handle the case for the last line in the string
  !
  if (line_end .eq. equals_pos) then
     line_end = len(trim(instring))
  endif

  !
  ! Set value
  !
  if ( (equals_pos + 1) .le. (line_end - 2) ) then
     Value = trim(adjustl(instring(equals_pos+1:line_end-2)))
  else
     Value = ""
  endif
  
  stat = 0
  

end subroutine gr2_get_metadata_value

!*****************************************************************************
!
! Build onto a metadata string with the input value
!
!*****************************************************************************

SUBROUTINE gr2_build_string (string, Element, Value, Count, Status)

  IMPLICIT NONE
#include "wrf_status_codes.h"

  CHARACTER (LEN=*) , INTENT(INOUT) :: string
  CHARACTER (LEN=*) , INTENT(IN)    :: Element
  CHARACTER (LEN=*) , INTENT(IN)    :: Value(*)
  INTEGER ,           INTENT(IN)    :: Count
  INTEGER ,           INTENT(OUT)   :: Status

  CHARACTER (LEN=2)                 :: lf
  INTEGER                           :: IDX

  lf=char(10)//' '

  if (index(string,lf//Element//' =') .gt. 0) then
     ! We do nothing, since we dont want to add the same variable twice.
  else 
     if (len_trim(string) == 0) then
        string = lf//Element//' = '
     else
        string = trim(string)//lf//Element//' = '
     endif
     do idx = 1,Count
        if (idx > 1) then
           string = trim(string)//','
        endif
        string = trim(string)//' '//trim(adjustl(Value(idx)))
     enddo
  endif

  Status = WRF_NO_ERR

END SUBROUTINE gr2_build_string
Back to Top