Source

enzo-dev-problem-types / src / enzo / Grid.h

Full commit
   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
/***********************************************************************
/
/  GRID CLASS
/
/  written by: Greg Bryan
/  date:       November, 1994
/  modified:   Many times by AK, DC, RH, JB, DR...
/
/  PURPOSE:
/
************************************************************************/

#ifndef GRID_DEFINED__
#define GRID_DEFINED__
#include "ProtoSubgrid.h"
#include "ListOfParticles.h"
#include "region.h"
#include "FastSiblingLocator.h"
#include "StarParticleData.h"
#include "AMRH5writer.h"
#include "Star.h"
#include "FOF_allvars.h"
#include "MemoryPool.h"

#ifdef FLUX_FIX
#include "TopGridData.h"
#endif

struct HierarchyEntry;

#include "EnzoArray.h"

//#ifdef ANALYSIS_TOOLS
#include "../anyl/AnalyzeClusters.h"
//#endif

#ifdef TRANSFER
#include "PhotonPackage.h"
#include "ListOfPhotonsToMove.h"
#endif /* TRANSFER */

#ifdef NEW_PROBLEM_TYPES
#include "ProblemType.h"
#endif

//extern int CommunicationDirection;

//struct ParticleEntry {
//  FLOAT Position[3];
//  float Mass;
//  float Velocity[3];
//  float Attribute[MAX_NUMBER_OF_PARTICLE_ATTRIBUTES];
//  int Number;
// int Type;
//};

extern int CommunicationDirection;
int FindField(int f, int farray[], int n);
struct LevelHierarchyEntry;

class grid
{
#ifdef NEW_PROBLEM_TYPES
 protected:
#else
 private:
#endif
//
//  General grid class data
//
  int GridRank;                        // number of dimensions
  int GridDimension[MAX_DIMENSION];    // total dimensions of all grids
  int GridStartIndex[MAX_DIMENSION];   // starting index of the active region
                                       //   (zero based)
  int GridEndIndex[MAX_DIMENSION];     // stoping index of the active region
                                       //   (zero based)
  FLOAT GridLeftEdge[MAX_DIMENSION];   // starting pos (active problem space)
  FLOAT GridRightEdge[MAX_DIMENSION];  // ending pos (active problem space)
  float dtFixed;                       // current (fixed) timestep
  FLOAT Time;                          // current problem time
  FLOAT OldTime;                       // time corresponding to OldBaryonField
  int   SubgridsAreStatic;             // 
  int   ID;                            // Grid ID Number
//
//  Baryon grid data
//
  int    NumberOfBaryonFields;                        // active baryon fields
  float *BaryonField[MAX_NUMBER_OF_BARYON_FIELDS];    // pointers to arrays
  float *OldBaryonField[MAX_NUMBER_OF_BARYON_FIELDS]; // pointers to old arrays
  float *InterpolatedField[MAX_NUMBER_OF_BARYON_FIELDS]; // For RT and movies
  float *RandomForcingField[MAX_DIMENSION];           // pointers to arrays //AK
  int    FieldType[MAX_NUMBER_OF_BARYON_FIELDS];
  FLOAT *CellLeftEdge[MAX_DIMENSION];
  FLOAT *CellWidth[MAX_DIMENSION];
  fluxes *BoundaryFluxes;
  float *YT_TemperatureField;                         // place to store temperature field
                                                      // for call to yt.

  // For restart dumps

  int NumberOfSubgrids;
  fluxes **SubgridFluxStorage;

  // MHD data
  float *divB;
  float *gradPhi[MAX_DIMENSION];

  float  CourantSafetyNumber;                       // Hydro parameter
  int    PPMFlatteningParameter;                    // PPM parameter
  int    PPMDiffusionParameter;                     // PPM parameter
  int    PPMSteepeningParameter;                    // PPM parameter
//
//  Particle data
//
  int    NumberOfParticles;
  FLOAT *ParticlePosition[MAX_DIMENSION];  // pointers to position arrays
  float *ParticleVelocity[MAX_DIMENSION];  // pointers to velocity arrays
  float *ParticleAcceleration[MAX_DIMENSION+1];  // 
  float *ParticleMass;                     // pointer to mass array
  PINT  *ParticleNumber;                   // unique identifier
  int   *ParticleType;                     // type of particle
  float *ParticleAttribute[MAX_NUMBER_OF_PARTICLE_ATTRIBUTES];
//
//  Star particle data
//
  int NumberOfStars;
  Star *Stars;
//
//  Gravity data
// 
  float *PotentialField;
  float *AccelerationField[MAX_DIMENSION]; // cell cntr acceleration at n+1/2
  float *GravitatingMassField;
  FLOAT  GravitatingMassFieldLeftEdge[MAX_DIMENSION];
  int    GravitatingMassFieldDimension[MAX_DIMENSION];
  FLOAT  GravitatingMassFieldCellSize;     // all dimensions must be the same
  float *GravitatingMassFieldParticles;     // for particles only
  FLOAT  GravitatingMassFieldParticlesLeftEdge[MAX_DIMENSION];
  FLOAT  GravitatingMassFieldParticlesCellSize;
  int    GravitatingMassFieldParticlesDimension[MAX_DIMENSION];
  gravity_boundary_type GravityBoundaryType;
  float  PotentialSum;
//
//  Top grid parallelism (for implicit solvers)
//
  int ProcLayout[MAX_DIMENSION];
  int ProcLocation[MAX_DIMENSION];
  int ProcNeighbors[MAX_DIMENSION][2];
//
//  Radiation data
//
#ifdef TRANSFER
  float MaxRadiationDt;
#endif
//
//  Rebuild Hierarchy Temporaries
//
  int   *FlaggingField;             // Boolean flagging field (for refinement)
  float *MassFlaggingField;         // Used by mass flagging criteria
  float *ParticleMassFlaggingField; // Used by particle mass flagging criteria
//
//  Parallel Information
//
  int ProcessorNumber;
//
// Movie Data Format
//
  int TimestepsSinceCreation; 	// Not really since creation anymore... 
  				// resets everytime the grid outputs


//
// Friends
//
  friend int ExternalBoundary::Prepare(grid *TopGrid);
  friend int ProtoSubgrid::CopyFlaggedZonesFromGrid(grid *Grid);
  friend class Star;
#ifdef NEW_PROBLEM_TYPES
  friend class EnzoProblemType;
#endif

#ifdef TRANSFER
#include "PhotonGrid_Variables.h"
#endif

 public:

// -------------------------------------------------------------------------
//  Main hydro/AMR functions
//

/* Grid constructor (Set all data to null/default state). */

   grid();

/* Grid deconstructor (free up memory usage) */

   ~grid();

/* Read grid data from a file (returns: success/failure) */

   int ReadGrid(FILE *main_file_pointer, int GridID, char DataFilename[], 
		int ReadText = TRUE, int ReadData = TRUE);

/* Read grid data from a group file (returns: success/failure) */

#ifndef NEW_GRID_IO
   int Group_ReadGrid(FILE *fptr, int GridID, HDF5_hid_t file_id, 
		      char DataFilename[],
		      int ReadText, int ReadData, bool ReadParticlesOnly=false);
#else
   int Group_ReadGrid(FILE *main_file_pointer, int GridID, HDF5_hid_t file_id, 
		      char DataFilename[],
		      int ReadText = TRUE, int ReadData = TRUE, 
		      bool ReadParticlesOnly=false, int ReadEverything = FALSE);
#endif
   
/* Get field or particle data based on name or integer 
   defined in typedefs.h. Details are in Grid_CreateFieldArray.C. */

   EnzoArrayBool *CreateFieldArrayBool(field_type field);
   EnzoArrayBool *CreateFieldArrayBool(char *field_name);

   EnzoArrayInt *CreateFieldArrayInt(field_type field);
   EnzoArrayInt *CreateFieldArrayInt(char *field_name);
  
   EnzoArrayFloat *CreateFieldArrayFloat(field_type field);
   EnzoArrayFloat *CreateFieldArrayFloat(char *field_name);
  
   EnzoArrayFLOAT *CreateFieldArrayFLOAT(field_type field);
   EnzoArrayFLOAT *CreateFieldArrayFLOAT(char *field_name);

   EnzoArrayPINT *CreateFieldArrayPINT(field_type field);
   EnzoArrayPINT *CreateFieldArrayPINT(char *field_name);

/* Write unigrid cubes to a file (returns: success/failure) */

   int WriteCube(char *base_name, int grid_id, int TGdims[]);

/* Write grid data to a file (returns: success/failure) */

   int WriteGrid(FILE *main_file_pointer, char *base_name, int grid_id);

/* Write grid data to a group file (returns: success/failure) */

#ifndef NEW_GRID_IO
   int Group_WriteGrid(FILE *fptr, char *base_name, int grid_id, HDF5_hid_t file_id);
#else
   int Group_WriteGrid(FILE *main_file_pointer, char *base_name, int grid_id, HDF5_hid_t file_id, int WriteEverything = FALSE);
#endif

   int WriteAllFluxes(hid_t grid_node);
   int WriteFluxGroup(hid_t top_group, fluxes *fluxgroup);

   int ReadAllFluxes(hid_t grid_node);
   int ReadFluxGroup(hid_t top_group, fluxes *fluxgroup);

   int FillFluxesFromStorage(int *ThisNumberOfSubgrids,
        fluxes ***fluxgroup) {
        *ThisNumberOfSubgrids = this->NumberOfSubgrids;
        *fluxgroup = this->SubgridFluxStorage;
        this->SubgridFluxStorage = NULL;
        if(ProcessorNumber != MyProcessorNumber) return -1;
        return 0;
    }
   
/* Routines for writing/reading grid hierarchy information to/from
   HDF5 hierarchy file */
   int WriteHierarchyInformationHDF5(char *base_name, hid_t level_group_id, int level, int ParentGridIDs[], int NumberOfDaughterGrids, int DaughterGridIDs[], int NextGridThisLevelID, int NextGridNextLevelID, FILE *log_fptr);
   
   int ReadHierarchyInformationHDF5(hid_t Hfile_id, int GridID, int &Task, int &NextGridThisLevelID, int &NextGridNextLevelID, char DataFilename[], FILE *log_fptr);


/* Write grid data to separate files (returns: success/failure) */

   int WriteGridX(FILE *main_file_pointer, char *base_name, int grid_id);

/* Write task memory map */

   int WriteMemoryMap(FILE *file_pointer, char *base_name, int grid_id);

/* Write grid-to-task map */

   int WriteTaskMap(FILE *file_pointer, char *base_name, int grid_id);

/* Write grid hierarchy only */

   int WriteStuff(FILE *main_file_pointer, char *base_name, int grid_id);

/* Interpolate to specified time and write unigrid cube data to a file
   (returns: success/failure). */

   int WriteCubeInterpolate(FLOAT WriteTime, char *base_name, int grid_id, int TGdims[]);

/* Interpolate to specified time and write grid data to a file
   (returns: success/failure). */

   int WriteGridInterpolate(FLOAT WriteTime, FILE *main_file_pointer, 
			    char *base_name, int grid_id);

/* Interpolate to specified time and write grid data to a group file
   (returns: success/failure). */

   int Group_WriteGridInterpolate(FLOAT WriteTime, FILE *main_file_pointer,
                            char *base_name, int grid_id, HDF5_hid_t file_id);

   int ComputeVectorAnalysisFields(field_type fx, field_type fy, field_type fz,
                                   float* &curl_x, float* &curl_y, float* &curl_z,
                                   float* &div);

private:
   int write_dataset(int ndims, hsize_t *dims, const char *name, hid_t group, 
       hid_t data_type, void *data, int active_only = TRUE,
       float *temp=NULL);
   int read_dataset(int ndims, hsize_t *dims, const char *name, hid_t group,
       hid_t data_type, void *read_to, int copy_back_active=FALSE,
       float *copy_to=NULL, int *active_dims=NULL);
   int ReadExtraFields(hid_t group_id);
public:

/* Compute the timestep constraint for this grid
    (for steps #3 and #4) */

   float ComputeTimeStep();

/* Set the timestep in this grid to the timestep in the argument
    (for step #3) */

   void SetTimeStep(float dt) {dtFixed = dt;};

/* Check timestep (dtFixed) against argument (return fail if dtFixed > dt).
    (for step #4) */

   int CheckTimeStep(float dt) {return ((dtFixed > dt) ? FAIL : SUCCESS);};

/* Return time, timestep */

   FLOAT ReturnTime() {return Time;};
   FLOAT ReturnOldTime() {return OldTime;};
   float ReturnTimeStep() {return dtFixed;};

  /* Return, set grid ID */

  void SetGridID(int id) { ID = id; };
  int GetGridID(void) { return ID; };
   
  /* Baryons: return field types. */

  int ReturnFieldType(int type[]) 
  {
    for (int i = 0; i < NumberOfBaryonFields; i++) type[i] = FieldType[i];
    return SUCCESS;
  };

/* Baryons: Interpolate (parental) grid in argument to current grid.
            (returns success or fail).
    (for step #16) */

   int InterpolateBoundaryFromParent(grid *ParentGrid);

/* Member functions for dealing with thermal conduction */
   int ComputeHeat(float dedt[]);	     /* Compute Heat */
   int ConductHeat();			     /* Conduct Heat */
   int ComputeConductionTimeStep(float &dt); /* Estimate conduction time-step */

/* Baryons: Copy current solution to Old solution (returns success/fail)
    (for step #16) */

   int CopyBaryonFieldToOldBaryonField();
   int CopyOldBaryonFieldToBaryonField();


/* Copy potential field to baryon potential for output purposes. */

   int CopyPotentialToBaryonField();

/* Baryons: Update boundary according to the external boundary values
    (for step #16) */

   int SetExternalBoundaryValues(ExternalBoundary *Exterior);

/* Baryons: solve hydro equations in this grid (returns: the fluxes of the
           subgrids in the argument).  Returns SUCCESS or FAIL.
    (for step #16) */

   int SolveHydroEquations(int CycleNumber, int NumberOfSubgrids, 
			   fluxes *SubgridFluxes[], int level);

/* Baryons: return pointer to the BoundaryFluxes of this grid */

   int ReturnFluxDims(fluxes &f, int RefinementFactors[]);

/* Baryons: prepare and clear the accumulated boundary fluxes for this grid.
    (for step #16) */

   void PrepareBoundaryFluxes();
   void ClearBoundaryFluxes();

/* Baryons: projected solution in current grid to the grid in the 
           argument which must have a lower resolution (i.e. downsample 
           the current grid to the appropriate level).
    (for step #18) */

   int ProjectSolutionToParentGrid(grid &ParentGrid);

/* Baryons: return boundary fluxes from this grid.  Downsample them to
           the refinement factors specified in the argument.
	   Returns FAIL or SUCCESS.
    (for step #19) */

   int GetProjectedBoundaryFluxes(grid *ParentGrid, fluxes &ProjectedFluxes);

/* Return the refinement factors as compared to the grid in the argument
   (integer version) (for step #19) */

   void ComputeRefinementFactors(grid *SubGrid, int RefinementFactors[]) {
     int dim;
     for (dim = 0; dim < GridRank; dim++) RefinementFactors[dim] = 
	 int( CellWidth[dim][0] / SubGrid->CellWidth[dim][0] + 0.5);
     for (dim = GridRank; dim < MAX_DIMENSION; dim++)
       RefinementFactors[dim] = 1;
   };

/* Return the refinement factors as compared to the grid in the argument
   (float version) (for step #19) */

   void ComputeRefinementFactorsFloat(grid *SubGrid, float Factors[]) {
     int dim;
     for (dim = 0; dim < GridRank; dim++) Factors[dim] = 
       (*CellWidth[dim]) / (*(SubGrid->CellWidth[dim]));;
     for (dim = GridRank; dim < MAX_DIMENSION; dim++)
       Factors[dim] = 1.0;
   };

/* Baryons: Search for redundant overlap between two sets of fluxes (other
            and refined).  If found, set the refined fluxes equal to the
	    initial fluxes so there will be no double corrections.(step #19) */

   void CorrectRedundantFluxes(fluxes *OtherFluxes, fluxes *InitialFluxes, 
                               fluxes *RefinedFluxes);

/* Baryons: correct for better flux estimates produced by subgrids
           (i.e given the initial flux estimates and the subgrid flux 
	   estimates, correct the grid to account for the subgrid 
	   flux estimates).  Returns SUCCESS or FAIL.
    (for step #19) */

#ifdef FLUX_FIX
   int CorrectForRefinedFluxes(fluxes *InitialFluxes, fluxes *RefinedFluxes,
			       fluxes *BoundaryFluxesThisTimeStep,
			       int SUBlingGrid,
			       TopGridData *MetaData);
#else
   int CorrectForRefinedFluxes(fluxes *InitialFluxes, fluxes *RefinedFluxes,
			       fluxes *BoundaryFluxesThisTimeStep);
#endif

/* Baryons: add the fluxes pointed to by the argument to the boundary fluxes
            of this grid (sort of for step #16).  Note that the two fluxes
	    must have the same size. */

   int AddToBoundaryFluxes(fluxes *BoundaryFluxesToBeAdded);

/* set new time (time += dt)
    (step #21) */

   void SetTimeNextTimestep() {Time += dtFixed;};
   void SetTimePreviousTimestep() {Time -= dtFixed;};

/* set time of this grid (used in setup) */

   void SetTime(FLOAT NewTime) {Time = NewTime;};

/* set hydro parameters (used in setup) */

   void SetHydroParameters(float co, int p1, int p2, int p3) 
     {
       CourantSafetyNumber    = co;
       PPMFlatteningParameter = p1;
       PPMDiffusionParameter  = p2;
       PPMSteepeningParameter = p3;
     }

/* Baryons: compute the pressure at the requested time. */

   int ComputePressure(FLOAT time, float *pressure);

/* Baryons: compute the pressure at the requested time using the dual energy
            formalism. */

   int ComputePressureDualEnergyFormalism(FLOAT time, float *pressure);

/* Baryons: compute the temperature. */

   int ComputeTemperatureField(float *temperature);

/* Baryons: compute the temperature at the requested time using
   Gadget equilibrium cooling. */

   int GadgetComputeTemperature(FLOAT time, float *temperature);

/* Baryons: compute the temperatre at the requested time using the dual energy
   formalism when using Gadget equilibrium cooling. */

   int GadgetComputeTemperatureDEF(FLOAT time, float *temperature);

/* Baryons: compute the dust temperature. */

   int ComputeDustTemperatureField(float *temperature, float *dust_temperature);

/* Baryons: compute X-ray emissivity in specified band. */

   int ComputeXrayEmissivity(float *temperature,
			     float *xray_emissivity, float keV1, float keV2,
			     char *XrayFileName);

/* Baryons: compute number density of ionized elements (just O7 and O8). */

   int ComputeElementalDensity(float *temperature, float *elemental_density,
			       int Type);

/* Baryons: compute the ratio of specific heats. */

   int ComputeGammaField(float *GammaField);

/* Baryons: compute the cooling time. */

   int ComputeCoolingTime(float *cooling_time);

/* Baryons & DualEnergyFormalism: Restore consistency between total and
                                  internal energy fields. */

   int RestoreEnergyConsistency(int Region);

/* Returns some grid info. */

   int ReturnGridInfo(int *Rank, int Dims[], FLOAT Left[], FLOAT Right[]);

/* Subtracts kinetic component from total energy. */

   int ConvertTotalEnergyToGasEnergy();

/* Sets the energy to provide Jean's level support (Zeus: returns coeff). */
   
   int SetMinimumSupport(float &MinimumSupportEnergyCoefficient);

/* Debugging support. */

   int DebugCheck(char *message = "Debug");

#ifdef EMISSIVITY
   /* define function prototype as a grid member function */
   int ClearEmissivity();
   int CheckEmissivity();
#endif

// -------------------------------------------------------------------------
// Functions used for analysis
//

/* Calculate the angular momentum of a grid (given center). */

   int CalculateAngularMomentum(FLOAT Center[], float AngularMomentum[],
				float MeanVelocity[], float DMVelocity[],
				FLOAT CenterOfMass[], FLOAT DMCofM[]);

/* Find and track density peaks. */

   int AnalyzeTrackPeaks(int level, int ReportLevel);

/* Project some of the fields to a plane. */

   int ProjectToPlane(FLOAT ProjectedFieldLeftEdge[], 
		      FLOAT ProjectedFieldRightEdge[],
		      int ProjectedFieldDims[], float *ProjectedField[], 
		      int ProjectionDimension, int ProjectionSmooth,
                      int NumberOfProjectedFields, int level,
		      int XrayUseLookupTable, float XrayLowerCutoffkeV,
		      float XrayUpperCutoffkeV, char *XrayFileName);

   int ProjectToPlane2(FLOAT ProjectedFieldLeftEdge[], 
		       FLOAT ProjectedFieldRightEdge[],
		       int ProjectedFieldDims[], float *ProjectedField[], 
		       int ProjectionDimension, int ProjectionSmooth,
		       int NumberOfProjectedFields, int level,
		       int MetalLinesUseLookupTable, char *MetalLinesFilename);

/* Set the fields to zero under the active region of the specified subgrid. */

   int ZeroSolutionUnderSubgrid(grid *Subgrid, int FieldsToZero, 
                                float Value = 1.0, int AllProcessors = FALSE,
				int IncludeGhostZones = FALSE);

/* Convert the grid data to particle data for output. */

   int OutputAsParticleData(FLOAT RegionLeftEdge[], FLOAT RegionRightEdge[],
                           ListOfParticles *ParticleList[NUM_PARTICLE_TYPES],
                           float BaseRadius);

/* Output star particles to a binary file */

   int OutputStarParticleInformation(FILE *StarFile);

/* Return some information about the grid. */

   int CollectGridInformation(int &GridMemory, float &GridVolume, 
                              int &NumberOfCells, float &AxialRatio,
                              int &CellsTotal, int &Particles);

/* Output grid information (for movie generation). */

   int OutputGridMovieData(FILE *Gridfptr, FILE *DMfptr, FILE *Starfptr,
			   FLOAT RegionLeftEdge[], FLOAT RegionRightEdge[],
			   FLOAT WriteOutTime, int NumberOfPoints[3],
			   int NumberOfValuesPerPoint[3],
			   char *PointValueNames[3][20], float BaseRadius);

/* Output movie data (sequential format) */

   int WriteNewMovieData(FLOAT RegionLeftEdge[], FLOAT RegionRightEdge[], 
			 int RootResolution, FLOAT StopTime, 
			 AMRHDF5Writer &AmiraGrid,
			 int lastMovieStep, int TopGridCycle, 
			 int WriteMe, int MovieTimestepCounter, int open, 
			 FLOAT WriteTime,
			 int alreadyopened[][MAX_DEPTH_OF_HIERARCHY] = NULL, 
			 int NumberOfStarParticlesOnProcOnLvl[][MAX_DEPTH_OF_HIERARCHY] = NULL);

   int WriteNewMovieDataSeparateParticles(FLOAT RegionLeftEdge[], FLOAT RegionRightEdge[], 
					  FLOAT StopTime, AMRHDF5Writer &AmiraGrid,
					  int lastMovieStep, int WriteMe, 
					  FLOAT WriteTime, int alreadyopened[],
					  int NumberOfStarParticlesOnProc[]);

   int ReturnMovieTimestep() { return TimestepsSinceCreation; };

/* Output tracer particle information (interpolated from baryon grid). */

   int TracerParticleOutputData(FILE *ptr, FLOAT WriteOutTime);

// -------------------------------------------------------------------------
// Functions for radiative cooling and multi-species rate equations
//

/* Handle the selection of cooling and chemistry modules */

   int MultiSpeciesHandler();

/* Handle the selection of shock finding algorithm */

   int ShocksHandler();

/* Solve the radiative cooling/heating equations  */

   int SolveRadiativeCooling();

/* Solve the rate equations. */

   int SolveRateEquations();

/* Solve the joint rate and radiative cooling/heating equations  */

   int SolveRateAndCoolEquations(int RTCoupledSolverIntermediateStep);

/* Solve the joint rate and radiative cooling/heating equations using MTurk's Solver */

   int SolveHighDensityPrimordialChemistry();
#ifdef USE_CVODE
   int SolvePrimordialChemistryCVODE();
#endif

/* Compute densities of various species for RadiationFieldUpdate. */

   int RadiationComputeDensities(int level);

// -------------------------------------------------------------------------
// Functions for Gadget cooling

/* Driving routine for Gadget equilibrium cooling */

   int GadgetCalculateCooling(float *d, float *e, float *ge,
			      float *u, float *v, float *w,
			      int *in, int *jn, int *kn,
			      int *iexpand, hydro_method *imethod, 
			      int *idual, int *idim,
			      int *is, int *js, int *ks, int *ie, int *je,
			      int *ke, float *dt, float *aye,
			      float *fh, float *utem, float *uxyz,
			      float *uaye, float *urho, float *utim,
			      float *gamma);

/* Computes cooling time using gadget equilibrium cooling */

   int GadgetCoolingTime(float *d, float *e, float *ge,
			 float *u, float *v, float *w,
			 float *cooltime,
			 int *in, int *jn, int *kn,
			 int *iexpand, hydro_method *imethod, int *idual, int *idim,
			 int *is, int *js, int *ks, int *ie, int *je,
			 int *ke, float *dt, float *aye,
			 float *fh, float *utem, float *uxyz,
			 float *uaye, float *urho, float *utim,
			 float *gamma);


/* calculates abundances and rates using Gadget equilibrium cooling */

   void Gadgetfind_abundances_and_rates(float logT, float rho, float *ne_guess);

/* calculates temperature using Gadget equilibrium cooling */

   float Gadgetconvert_u_to_temp(float u, float rho, float *ne_guess);

/* calculates cooling rates (not cooling time) using Gadget equilibrium cooling 
   and gas temperature */

   float GadgetCoolingRate(float logT, float rho, float *nelec, float redshift);

/* wrapper for GadgetCoolingRate */

   float Gadget_EquilibriumCooling(float u_old, float rho, float dt,
				   float *ne_guess, float *utem, float *uxyz, 
				   float *uaye, float *urho,
				   float *utim, float redshift);

/* calculates cooling rate (not cooling time) using energy instead of temperature 
   for Gadget equil. cooling */

   float GadgetCoolingRateFromU(float u, float rho, float *ne_guess, 
				float redshift);

// Functions for shock finding
//
   int FindShocks();
   int FindTempSplitShocks();
   int FindVelShocks();
   int FindVelSplitShocks();

// -------------------------------------------------------------------------
// Functions for grid (re)generation.
//

/* Remove un-needed arrays before rebuilding. */

   void CleanUp();

/* Delete all the fields, but leave other grid data. */

   void DeleteAllFields();

/* Delete all the fields except for the particle data */

   void DeleteAllButParticles();

/* Delete all the baryon fields */

   void DeleteBaryonFields();

/* Sum particle mass flagging fields into ProcessorNumber if particles
   aren't local. */

   int SetParticleMassFlaggingField(int StartProc=0, int EndProc=0, int level=-1, 
				    int ParticleMassMethod=-1, int *SendProcs=NULL, 
				    int NumberOfSends=0);
   int CollectParticleMassFlaggingField(void);
   void ClearParticleMassFlaggingField(void);

/* Clear mass flagging field (gg #1) */

   void ClearMassFlaggingField();

/* Clear boolean flagging field (gg #0) */

   void ClearFlaggingField();

/* Set boolean flagging field */

   int SetFlaggingField(int &NumberOfFlaggedCells, int level);

/* Set flagging field from static regions */

   int SetFlaggingFieldStaticRegions(int level, int &NumberOfFlaggedCells);

/* Delete flagging field */

   void DeleteFlaggingField();

/* Particles: deposit particles living in this grid into the Mass Flagging
             field (gg #2) */

   void DepositParticlesToMassFlaggingField() {};

/* Particles: deposit particles to particle mass flagging field. */

   int DepositMustRefineParticles(int pmethod, int level);

/* baryons: add baryon density to mass flaggin field (so the mass flagging
            field contains the mass in the cell (not the density) 
            (gg #3) */

   int AddFieldMassToMassFlaggingField();

/* Flag all points where we are forbidding refinement from a color field */

   int FlagCellsToAvoidRefinement();

/* Flag all points in a region where refinement is not needed */

   int FlagCellsToAvoidRefinementRegion(int level);

/* Flag all points that require refining  (and delete Mass Flagging Field).
     Returns the number of flagged cells.  Returns the number of flagged cells
     (gg #4) */

   int FlagCellsToBeRefinedByMass(int level, int method);

/* Flag all points that require refining by their slope.
     Returns the number of flagged cells.  Returns the number of flagged cells
     (gg #4) */

   int FlagCellsToBeRefinedBySlope();

/* Flag all points that require refinging by the presence of shocks.
     Returns the number of flagged cells.  Returns the number of flagged cells
     (gg #4) */

   int FlagCellsToBeRefinedByShocks();

/* Flag all points based on the Mach number of the shock. */

   int FlagCellsToBeRefinedByShockwaves(int level);

/* Flag all points that require refining by the Jean's length criterion. */

   int FlagCellsToBeRefinedByJeansLength();

/* Flag all points that require refining by the total Jean's length criterion. (Tom Abel 10/2010) */

   int FlagCellsToBeRefinedByTotalJeansLength();

/* Flag all points that require refining by the Resistive Scale length criterion. 
   abs(B)/abs(curl(B)) should be larger than cell size*/

   int FlagCellsToBeRefinedByResistiveLength();

/* Flag all points that require refining by Shear. */

   int FlagCellsToBeRefinedByShear();

/* Flag all cells for which tcool < dx/sound_speed. */

   int FlagCellsToBeRefinedByCoolingTime();

/* Flag all cells which are near a must-refine particle. */

   int FlagCellsToBeRefinedByMustRefineParticles();

/* Flag all cells which are within a user-specified refinement region. */

   int FlagCellsToBeRefinedByMustRefineRegion(int level);

/* Flag all cells which are above a user-specified metallicity. */

   int FlagCellsToBeRefinedByMetallicity(int level);


/* Flagging all cell adjacent to a previous flagged cell.  Also, remove all
   Flagged cells in the boundary zones and within one zone of the boundary. */

   int FlagBufferZones();

/* Identify new subgrids for this grid (and prove Fermat's last theorem too)
   (gg #5) */

   void IdentifyNewSubgrids(GridList &list);

/* Identify new subgrids for this grid (1x1x1 subgrids).
   (gg #5) */

   void IdentifyNewSubgridsSmall(GridList &list);

/* Coalesce neighbouring subgrids */

   // void CoalesceSubgrids(GridList &list);

/* Inherit properties (rank, baryon field types, etc.) from ParentGrid
   (gg # 5,6) */

   void InheritProperties(grid *ParentGrid);

/* set the grid dimensions, left, right edges and cell quantities based
   on arguments (gg #5,6) */

   void PrepareGrid(int Rank, int Dimensions[], 
		    FLOAT LeftEdge[], FLOAT RightEdge[], int NumParticles);

/* Allocates space for grids (dims and NumberOfBaryonFields must be set). */

   void AllocateGrids();

/* set the grid derived quantites (CellLeftEdge, CellWidth & BoundaryFluxes) */

   void PrepareGridDerivedQuantities();

/* baryons: interpolate field values from the Parent Grid (gg #6).
            Returns SUCCESS or FAIL. */

   int InterpolateFieldValues(grid *ParentGrid);

/* Interpolate one radiation field.  Based on InterpolateFieldValues
   but removed all of the conservative stuff. */   

   int InterpolateRadiationFromParent(grid *ParentGrid, int Field);

/* baryons: check for coincident zones between grids & copy if found.
            (correctly includes periodic boundary conditions). */

   int CheckForOverlap(grid *OtherGrid,
		       boundary_type LeftFaceBoundaryCondition[],
		       boundary_type RightFaceBoundaryCondition[],
		       int (grid::*CopyFunction)(grid *OtherGrid,
						 FLOAT EdgeOffset[]));

 



/* baryons: check for subgrids adjacent to external boundary with reflecting BCs. */

   int CheckForExternalReflections(
				   boundary_type LeftFaceBoundaryCondition[],
				   boundary_type RightFaceBoundaryCondition[]);

/* David Collins flux correction - July 2005 */
#ifdef FLUX_FIX
   int CheckForSharedFace(grid *OtherGrid,
			       boundary_type LeftFaceBoundaryCondition[],
			       boundary_type RightFaceBoundaryCondition[]);

   int CheckForSharedFaceHelper(grid *OtherGrid,
				     FLOAT EdgeOffset[MAX_DIMENSION]);
#endif

/* baryons: check for overlap between grids & return TRUE if it exists
            (correctly includes periodic boundary conditions). */

   int CheckForPossibleOverlap(grid *OtherGrid,
                       boundary_type LeftFaceBoundaryCondition[],
                       boundary_type RightFaceBoundaryCondition[]);
   int CheckForPossibleOverlapHelper(grid *OtherGrid,
                                        FLOAT EdgeOffset[MAX_DIMENSION]);

/* baryons: copy coincident zone from the (old) grid in the argument
            (gg #7).  Return SUCCESS or FAIL. */

   int CopyZonesFromGrid(grid *GridOnSameLevel, 
			 FLOAT EdgeOffset[MAX_DIMENSION]);

/* gravity: copy coincident potential field zones from grid in the argument
            (gg #7).  Return SUCCESS or FAIL. */

   int CopyPotentialField(grid *GridOnSameLevel, 
			  FLOAT EdgeOffset[MAX_DIMENSION]);

/* baryons: check for coincident zone from the (old) grid in the argument
            (gg #7).  Return SUCCESS or FAIL. */

   int CopyZonesFromGridCountOnly(grid *GridOnSameLevel, int &Overlap);

/* Returns whether or not the subgrids of this grid are static. */

   int AreSubgridsStatic() {return SubgridsAreStatic;};

/* Check the energy conservation. */

   int ComputeEnergy(float EnergySum[]);

/* These two routines add grids to the chaining mesh used in the
   FastSiblingLocator method and use the chaining mesh to find
   possible siblings. */

   int FastSiblingLocatorAddGrid(ChainingMeshStructure *mesh);

   int FastSiblingLocatorFindSiblings(ChainingMeshStructure *mesh,
                          SiblingGridList *list,
                          boundary_type LeftBoundaryCondition[],
                          boundary_type RightBoundaryCondition[]);

   /* hack: add density squared field to grid (used in ExtractSection). */

   void CreateDensitySquaredField() {
     int size = GridDimension[0]*GridDimension[1]*GridDimension[2];
     BaryonField[NumberOfBaryonFields] = new float[size];
     for (int i = 0; i < size; i++)
       BaryonField[NumberOfBaryonFields][i] = 
	 BaryonField[0][i]*BaryonField[0][i];
     FieldType[NumberOfBaryonFields++] = Density;
   };

   void PrintBaryonFieldValues(int field, int index)
     {fprintf(stdout, "Baryonfield[field = %"ISYM"][index = %"ISYM"] = %g\n", 
	      field, index, BaryonField[field][index]);};

// -------------------------------------------------------------------------
// Functions for use with gravity.
//

/* Set the gravity boundary type of a grid. */

   void SetGravityParameters(gravity_boundary_type Boundary) {
     GravityBoundaryType = Boundary;};
   gravity_boundary_type ReturnGravityBoundaryType() 
     {return GravityBoundaryType;};

/* Gravity: Initialize, the gravitating Mass Field
    (for steps #5, #6). */

   int InitializeGravitatingMassField(int RefinementFactor);

/* Gravity: Initialize, the particle component of the mass field. */

   int InitializeGravitatingMassFieldParticles(int RefinementFactor);

/* Gravity: allocate & clear the GravitatingMassField. */

   int ClearGravitatingMassField();

/* Gravity & baryons: Copy the parent density field to the extra boundary
      region of GravitatingMassField (if any). */

   int CopyParentToGravitatingFieldBoundary(grid *ParentGrid);

/* Gravity & Particles: allocate & clear the GravitatingMassFieldParticles. */

   int ClearGravitatingMassFieldParticles();

/* Baryons: add the baryon mass to the GravitatingMassField. */

   int AddBaryonsToGravitatingMassField();

/* Generic deposit particles/grids to grid (either GravitatingMassField or
   GravitatingMassFieldParticles depending on the value of DepositField). */

   int DepositPositions(FLOAT *Positions[], float *Mass, int Number, 
			int DepositField);

/* deposit particles/grids to grid (if they are on the grid). */

/* int DepositPositionsEdgeOff(float *Positions[], float *Mass, int Number);*/

/* Gravity: Difference potential to get acceleration field. */

   int ComputeAccelerationField(int DifferenceType, int level);

/* Gravity: Interpolate accelerations from other grid. */

   int InterpolateAccelerations(grid *FromGrid);

/* Gravity: Compute particle and grid accelerations. */

   int ComputeAccelerations(int level);

/* Particles: add overlapping ParticleMassField to Target's 
   GravitatingMassField. */

   int CopyOverlappingMassField(grid *TargetGrid, 
				FLOAT EdgeOffset[MAX_DIMENSION]);

/* Gravity: Allocate and make initial guess for PotentialField. */

   int PreparePotentialField(grid *ParentGrid);

/* Gravity: Allocate and make initial guess for PotentialField. */

   int SolveForPotential(int level, FLOAT PotentialTime = -1);

/* Gravity: Prepare the Greens Function. */

   int PrepareGreensFunction();
   int PreparePeriodicGreensFunction(region *GreensRegion);

/* Gravity: Copy potential/density into/out of FFT regions. */

   int PrepareFFT(region *InitialRegion, int Field, int DomainDim[]);
   int FinishFFT(region *InitialRegion, int Field, int DomainDim[]);

/* Gravity: set the potential boundary for isolated BC's */

   int SetIsolatedPotentialBoundary();

/* Gravity: Set the external acceleration fields. */

   int ComputeAccelerationFieldExternal();

/* Gravity: Set the external acceleration fields from external potential. */

   int ComputeAccelerationsFromExternalPotential(int DifferenceType,
                                                 float *ExternalPotential,
                                                 float *Field[]);

/* Gravity: Add fixed, external potential to baryons & particles. */

   int AddExternalPotentialField(float *field);
   

/* Particles + Gravity: Clear ParticleAccleration. */

   int ClearParticleAccelerations();

/* Baryons + Gravity: Interpolate the AccelerationField in FromGrid to
             AccelerationFieldForCells at the GridPositions in this grid. */

   int InterpolateGridPositions(grid *FromGrid);

/* Particles + Gravity: Interpolate the AccelerationField in FromGrid to
             ParticleAcceleration at the ParticlePositions in this grid. */

   int InterpolateParticlePositions(grid *FromGrid, int DifferenceType);

/* Generic routine for interpolating particles/grid. */

   int InterpolatePositions(FLOAT *Positions[], int dim, float *Field, 
			    int Number);

/* Gravity: Delete GravitatingMassField. */

   void DeleteGravitatingMassField() {
     delete [] GravitatingMassField; 
     GravitatingMassField = NULL;
   };

/* Gravity: Delete AccelerationField. */

   void DeleteAccelerationField() {
     if (!((SelfGravity || UniformGravity || PointSourceGravity || ExternalGravity))) return;
     for (int dim = 0; dim < GridRank; dim++) {
       delete [] AccelerationField[dim];
       AccelerationField[dim] = NULL;
     }
   };

/* Gravity: Add fixed, external acceleration to baryons & particles. */

   int AddExternalAcceleration();

/* Gravity: deposit baryons into target GravitatingMassField. */

   int DepositBaryons(grid *TargetGrid, FLOAT DepositTime);

// -------------------------------------------------------------------------
// Functions for accessing various grid-based information
//
   int GetGridRank() {return GridRank;}
   int GetGridDimension(int Dimension) {return GridDimension[Dimension];}
   int GetGridStartIndex(int Dimension) {return GridStartIndex[Dimension];}
   int GetGridEndIndex(int Dimension) {return GridEndIndex[Dimension];}
   int GetActiveSize() {
     int dim, size;
     for (dim = 0, size = 1; dim < GridRank; dim++) {
       size *= GridEndIndex[dim] - GridStartIndex[dim] + 1;
     }
     return size;
   }
   int GetGridSize() {
     int dim, size;
     for (dim = 0, size = 1; dim < GridRank; dim++)
       size *= GridDimension[dim];
     return size;
   }
   FLOAT GetGridLeftEdge(int Dimension) {return GridLeftEdge[Dimension];}
   FLOAT GetGridRightEdge(int Dimension) {return GridRightEdge[Dimension];}


#ifdef TRANSFER
// -------------------------------------------------------------------------
// Functions for use with coupled radiation-hydrodynamics solver.
//
   void SetMaxRadiationDt(float MaxRadDt) {MaxRadiationDt = MaxRadDt;}
#endif


// -------------------------------------------------------------------------
// Functions for accessing specific baryon fields 
// (all sources combined in the file Grid_AccessBaryonFields.C)
//
   float* AccessDensity();
   float* AccessTotalEnergy();
   float* AccessGasEnergy();
   float* AccessVelocity1();
   float* AccessVelocity2();
   float* AccessVelocity3();
   float* AccessElectronDensity();
   float* AccessHIDensity();
   float* AccessHIIDensity();
   float* AccessHeIDensity();
   float* AccessHeIIDensity();
   float* AccessHeIIIDensity();
   float* AccessHMDensity();
   float* AccessH2IDensity();
   float* AccessH2IIDensity();
   float* AccessDIDensity();
   float* AccessDIIDensity();
   float* AccessHDIDensity();
   float* AccessSNColour();
   float* AccessMetallicity();
   float* AccessExtraType0();
   float* AccessExtraType1();
   float* AccessKPhHI();
   float* AccessPhotoGamma();
   float* AccessKPhHeI();
   float* AccessGammaHeI();
   float* AccessKPhHeII();
   float* AccessGammaHeII();
   float* AccessKDissH2I();
   float* AccessGravPotential();
   float* AccessAcceleration0();
   float* AccessAcceleration1();
   float* AccessAcceleration2();
   float* AccessRadPressure0();
   float* AccessRadPressure1();
   float* AccessRadPressure2();
   float* AccessEmissivity0();
   float* AccessRadiationFrequency0();
   float* AccessRadiationFrequency1();
   float* AccessRadiationFrequency2();
   float* AccessRadiationFrequency3();
   float* AccessRadiationFrequency4();
   float* AccessRadiationFrequency5();
   float* AccessRadiationFrequency6();
   float* AccessRadiationFrequency7();
   float* AccessRadiationFrequency8();
   float* AccessRadiationFrequency9();


// -------------------------------------------------------------------------
// Functions for accessing top-grid parallelism information
// (note: information only available/valid for this level)
//

/* Processor layout: get and set the number of procs in each 
   dim within the cartesian processor grid
   (1-based, i.e. {1 1 1} defines a single-processor layout) */ 
   int GetProcessorLayout(int Dimension) {return ProcLayout[Dimension];}
   void SetProcessorLayout(int Dimension, int procs) {
     if (Dimension < 0 || Dimension > MAX_DIMENSION)
       fprintf(stderr,"SetProcessorLayout: invalid Dimension.\n");
     else
       if (procs > 0)  ProcLayout[Dimension] = procs; 
       else fprintf(stderr,"SetProcessorLayout: invalid procs value.\n");
   }

/* Processor location: get and set the location of this grid's proc
   within the cartesian processor grid defined in ProcLayout
   (0-based, i.e. {0 0 0} defines the 1st proc in each dimension) */
   int GetProcessorLocation(int Dimension) {return ProcLocation[Dimension];}
   void SetProcessorLocation(int Dimension, int location) {
     if (Dimension < 0 || Dimension > MAX_DIMENSION)
       fprintf(stderr,"SetProcessorLocation: invalid Dimension.\n");
     else
       if (location >= 0)  ProcLocation[Dimension] = location; 
       else fprintf(stderr,"SetProcessorLocation: invalid location.\n");     
   }

/* Processor neighbors: get and set the grid IDs (not MPI process IDs) of this
   grid's neighbors within the cartesian processor grid defined in ProcLayout. 
     Get... returns the {left=0,right=1} neighbor grid ID in a given dim
     Set... provides access to set neighbor information into the grid */
   int GetProcessorNeighbors(int Dimension, int LR) {
     return ProcNeighbors[Dimension][LR];}
   void SetProcessorNeighbors(int Dimension, int LR, int NBid) { 
     if (Dimension < 0 || Dimension > MAX_DIMENSION)
       fprintf(stderr,"SetProcessorNeighbors: invalid Dimension.\n");
     else
       if (LR < 0 || LR > 1) 
	 fprintf(stderr,"SetProcessorNeighbors: invalid neighbor.\n");    
       else
	 if (NBid >= 0)  ProcNeighbors[Dimension][LR] = NBid; 
	 else fprintf(stderr,"SetProcessorNeighbors: invalid grid ID.\n");    
   }


// -------------------------------------------------------------------------
// Functions for use with particles.
//

/* Particles: Deposit particles in the specified field (DepositField) of the
              TargetGrid at the given time. */

   int DepositParticlePositions(grid *TargetGrid, FLOAT DepositTime, 
				int DepositField);

   int DepositParticlePositionsLocal(FLOAT DepositTime, int DepositField);

/* Particles: add overlapping ParticleMassField to Target's 
   GravitatingMassField. */

   int AddOverlappingParticleMassField(grid *TargetGrid, 
				       FLOAT EdgeOffset[MAX_DIMENSION]);

/* Particles: Apply particle acceleration to velocity for particles in this 
              grid
    (for step #9) */

   int UpdateParticleVelocity(float TimeStep);

/* Particles: Update particle positions (push)
    (for step #13) */

   int UpdateParticlePosition(float TimeStep, int OffProcessorUpdate = FALSE);

/* Particles: Move particles from TargetGrid to this grid. */

   int MoveAllParticles(int NumberOfGrids, grid* TargetGrids[]);

   int MoveAllParticlesOld(int NumberOfGrids, grid* TargetGrids[]);

/* Particles: Move particles that lie within this grid from the TargetGrid
              to this grid. */

//   int MoveSubgridParticles(grid *TargetGrid);


   int MoveSubgridParticles(grid *TargetGrid,
                            int *Counter,
                            PINT *Number,
                            int *Type,
                            float *Mass,
                            FLOAT *Position[],
                            float *Velocity[],
                            float *Attribute[]);


/* Particles: same as above, but a version that is much more efficient. */

   int MoveSubgridParticlesFast(int NumberOfSubgrids, grid *ToGrids[],
				int AllLocal);

/* Particles: Clean up moved particles (from MoveSubgridParticles). */

   int CleanUpMovedParticles();

/* Particles: delete accleration fields. */

   void DeleteParticleAcceleration() {
     if (!((SelfGravity || UniformGravity || PointSourceGravity))) return;
     for (int dim = 0; dim < GridRank+ComputePotential; dim++) {
       delete [] ParticleAcceleration[dim];
       ParticleAcceleration[dim] = NULL;
     }
   };

/* Particles & Gravity: Delete GravitatingMassField. */

   void DeleteGravitatingMassFieldParticles() {
     delete [] GravitatingMassFieldParticles; 
     GravitatingMassFieldParticles = NULL;
     GravitatingMassFieldParticlesCellSize = FLOAT_UNDEFINED;
   };

/* Particles: return number of particles. */

   int ReturnNumberOfParticles() {return NumberOfParticles;};

   int ReturnNumberOfStarParticles(void);

/* Particles: set number of particles. */

   void SetNumberOfParticles(int num) {NumberOfParticles = num;};

/* Particles: delete particle fields and set null. */

   void DeleteParticles() {
     if (ParticleMass != NULL) delete [] ParticleMass;
     if (ParticleNumber != NULL) delete [] ParticleNumber;
     if (ParticleType != NULL) delete [] ParticleType;
     ParticleMass = NULL;
     ParticleNumber = NULL;
     ParticleType = NULL;
     for (int dim = 0; dim < GridRank; dim++) {
       if (ParticlePosition[dim] != NULL) delete [] ParticlePosition[dim];
       if (ParticleVelocity[dim] != NULL) delete [] ParticleVelocity[dim];
       ParticlePosition[dim] = NULL;
       ParticleVelocity[dim] = NULL;
     }
     for (int i = 0; i < NumberOfParticleAttributes; i++) {
       if (ParticleAttribute[i] != NULL) delete [] ParticleAttribute[i];
       ParticleAttribute[i] = NULL;
     }   
   };

/* Particles: allocate new particle fields. */

   void AllocateNewParticles(int NumberOfNewParticles) {
     ParticleMass = new float[NumberOfNewParticles];
     ParticleNumber = new PINT[NumberOfNewParticles];
     ParticleType = new int[NumberOfNewParticles];
     for (int dim = 0; dim < GridRank; dim++) {
       ParticlePosition[dim] = new FLOAT[NumberOfNewParticles];
       ParticleVelocity[dim] = new float[NumberOfNewParticles];
     }
     for (int i = 0; i < NumberOfParticleAttributes; i++)
       ParticleAttribute[i] = new float[NumberOfNewParticles];
   };

/* Particles: Copy pointers passed into into grid. */

   void SetParticlePointers(float *Mass, PINT *Number, int *Type,
                            FLOAT *Position[], 
			    float *Velocity[], float *Attribute[]) {
    ParticleMass   = Mass;
    ParticleNumber = Number;
    ParticleType   = Type;
    for (int dim = 0; dim < GridRank; dim++) {
      ParticlePosition[dim] = Position[dim];
      ParticleVelocity[dim] = Velocity[dim];
    }
    for (int i = 0; i < NumberOfParticleAttributes; i++)
      ParticleAttribute[i] = Attribute[i];
   };

/* Particles: Set new star particle index. */

   void SetNewParticleIndex(int &NumberCount1, PINT &NumberCount2);

/* Particles: Set new star particle index. - Old version */

   void SetNewParticleIndexOld(int &NumberCount, int BaseNumber) {
     for (int n = 0; n < NumberOfParticles; n++) 
      if (ParticleNumber[n] == INT_UNDEFINED)
	ParticleNumber[n] = BaseNumber + NumberCount++;
   };

/* Particles: Add given number to particle index. */

   void AddToParticleNumber(PINT *Count) {
     if (MyProcessorNumber == ProcessorNumber)
       for (int n = 0; n < NumberOfParticles; n++)
	 ParticleNumber[n] += *Count;
     *Count += NumberOfParticles;
   }

  float ReturnTotalSinkMass() {
    float total = 0;
    double dx3 = CellWidth[0][0] * CellWidth[0][0] * CellWidth[0][0];
    if (MyProcessorNumber == ProcessorNumber)
      for (int n = 0; n < NumberOfParticles; n++)
	if (ParticleType[n] == PARTICLE_TYPE_MUST_REFINE)
	  total += ParticleMass[n] * dx3;
    return total;
  };

/* Particles: return particle type (1 - dm, 2 - star).   Note that this
   has now been superceded by a real particle type field. */

   int ReturnParticleType(int index) {
     if (NumberOfParticleAttributes > 0 && StarParticleCreation > 0)
       if (ParticleAttribute[0][index] > 0)
         return PARTICLE_TYPE_STAR;
     return PARTICLE_TYPE_DARK_MATTER;
   }

/* Particles: return particle information in structure array */

   int ReturnParticleEntry(ParticleEntry *ParticleList);

/* Particles: set mass of merged particles to be -1 */

   void RemoveMergedParticles(ParticleEntry *List, const int &Size, int *Flag);

/* Particles: append particles belonging to this grid from a list */

   int AddParticlesFromList(ParticleEntry *List, const int &Size, int *AddedNewParticleNumber);
   int CheckGridBoundaries(FLOAT *Position);

/* Particles: sort particle data in ascending order by number (id) or type. */

void SortParticlesByNumber();
void SortParticlesByType();

int CreateParticleTypeGrouping(hid_t ptype_dset,
                               hid_t ptype_dspace,
                               hid_t parent_group,
                               hid_t file_id);

 int ChangeParticleTypeBeforeSN(int _type, int level, 
				int *ParticleBufferSize=NULL);

// -------------------------------------------------------------------------
// Communication functions
//

/* Set grid's processor number. */

  void SetProcessorNumber(int Proc) {
    ProcessorNumber = Proc;
  };

/* Return grid's processor number. */

  int ReturnProcessorNumber() {
    return ProcessorNumber;
  }

/* Send a region from a real grid to a 'fake' grid on another processor. */

  int CommunicationSendRegion(grid *ToGrid, int ToProcessor, int SendField, 
			     int NewOrOld, int RegionStart[], int RegionDim[]);

/* Send a region from a 'fake' grid to a real grid on another processor. */

  int CommunicationReceiveRegion(grid *ToGrid, int ToProcessor, 
				 int SendField, int NewOrOld, 
				 int RegionStart[], int RegionDim[],
				 int IncludeBoundary);

/* Move a grid from one processor to another. */

  int CommunicationMoveGrid(int ToProcessor, int MoveParticles = TRUE,
			    int DeleteAllFields = TRUE);

/* Send particles from one grid to another. */

  int CommunicationSendParticles(grid *ToGrid, int ToProcessor, 
				int FromStart, int FromNumber, int ToStart);

/* Transfer particle amount level 0 grids. */

  int CommunicationTransferParticles(grid* Grids[], int NumberOfGrids,
				     int ThisGridNum, int TopGridDims[],
				     int *&NumberToMove, 
				     int StartIndex, int EndIndex, 
				     particle_data *&List,
				     int *Layout, int *GStartIndex[],
				     int *GridMap, int CopyDirection);
  int CommunicationTransferStars(grid* Grids[], int NumberOfGrids,
				 int ThisGridNum, int TopGridDims[],
				 int *&NumberToMove, 
				 int StartIndex, int EndIndex, 
				 star_data *&List, int *Layout, 
				 int *GStartIndex[], int *GridMap, 
				 int CopyDirection);

  int CollectParticles(int GridNum, int* &NumberToMove, 
		       int &StartIndex, int &EndIndex, 
		       particle_data* &List, int CopyDirection);

  int CollectStars(int GridNum, int* &NumberToMove, 
		   int &StartIndex, int &EndIndex, 
		   star_data* &List, int CopyDirection);

  // Only used for static hierarchies
  int MoveSubgridStars(int NumberOfSubgrids, grid* ToGrids[],
		       int AllLocal);

  int TransferSubgridParticles(grid* Subgrids[], int NumberOfSubgrids, 
			       int* &NumberToMove, int StartIndex, 
			       int EndIndex, particle_data* &List, 
			       bool KeepLocal, bool ParticlesAreLocal,
			       int CopyDirection,
			       int IncludeGhostZones = FALSE,
			       int CountOnly = FALSE);

  int TransferSubgridStars(grid* Subgrids[], int NumberOfSubgrids, 
			   int* &NumberToMove, int StartIndex, 
			   int EndIndex, star_data* &List, 
			   bool KeepLocal, bool ParticlesAreLocal,
			   int CopyDirection,
			   int IncludeGhostZones = FALSE);

// -------------------------------------------------------------------------
// Helper functions (should be made private)
//

  /* This is a simple helper function which determines if the method
     should return immediately because of communication-mode reasons.
     Assumes that info is being sent from the "other-grid" processor to
     the "this-grid" processor (i.e. the one that holds this object). */

  int CommunicationMethodShouldExit(grid *OtherGrid) {

    /* Return if neither grid lives on this processor. */
    //    if (NumberOfProcessors == 1) return SUCCESS;

    if (MyProcessorNumber != ProcessorNumber && 
        MyProcessorNumber != OtherGrid->ProcessorNumber)
      return SUCCESS;

    /* If the two grids are on the same processor then return if
       either in post-receive or receive modes to avoid duplicating method
       (i.e. action is only carried out if in send mode (or send-receive)). */

    if (ProcessorNumber == OtherGrid->ProcessorNumber)
      if (CommunicationDirection == COMMUNICATION_POST_RECEIVE ||
	  CommunicationDirection == COMMUNICATION_RECEIVE)
        return SUCCESS;

    /* If in send mode then exit if the send grid is not on this processor. */

    if (CommunicationDirection == COMMUNICATION_SEND &&
        MyProcessorNumber != OtherGrid->ProcessorNumber)
      return SUCCESS;

    /* If in either receive phase then exit if receive grid is not on this 
       processor. */

    if ((CommunicationDirection == COMMUNICATION_RECEIVE ||
         CommunicationDirection == COMMUNICATION_POST_RECEIVE) &&
        MyProcessorNumber != ProcessorNumber)
      return SUCCESS;

    return FAIL; /* i.e. method should not exit immediately. */
  }

/* Baryons: find certain commonly used variables from the list of fields. */

  int IdentifyPhysicalQuantities(int &DensNum, int &GENum,   int &Vel1Num, 
				 int &Vel2Num, int &Vel3Num, int &TENum);

  int IdentifyPhysicalQuantities(int &DensNum, int &GENum, int &Vel1Num, 
				 int &Vel2Num, int &Vel3Num, int &TENum,
				 int &B1Num, int &B2Num, int &B3Num);

  int IdentifyPhysicalQuantities(int &DensNum, int &GENum, int &Vel1Num, 
				 int &Vel2Num, int &Vel3Num, int &TENum,
				 int &B1Num, int &B2Num, int &B3Num, int &PhiNum);

  /* Identify driving fields */

  int IdentifyDrivingFields(int &Drive1Num, int &Drive2Num, int &Drive3Num);

  /* Identify potential field */

  int IdentifyPotentialField(int &PotenNum, int &Acce1Num, int &Acce2Num, int &Acce3Num);

  /* Identify colour field */

  int IdentifyColourFields(int &SNColourNum, int &MetalNum, 
			   int &MetalIaNum, int &MBHColourNum,
			   int &Galaxy1ColourNum, int &Galaxy2ColourNum);

  /* Identify Multi-species fields. */

  int IdentifySpeciesFields(int &DeNum, int &HINum, int &HIINum, 
			    int &HeINum, int &HeIINum, int &HeIIINum,
			    int &HMNum, int &H2INum, int &H2IINum,
                            int &DINum, int &DIINum, int &HDINum);

  /* Identify shock fields. */
  int IdentifyShockSpeciesFields(int &MachNum,int &PSTempNum, int &PSDenNum);

  // Identify Simon Glover Species Fields
  int IdentifyGloverSpeciesFields(int &HIINum,int &HINum,int &H2INum,
				  int &DINum,int &DIINum,int &HDINum,
				  int &HeINum,int &HeIINum,int &HeIIINum,
				  int &CINum,int &CIINum,int &OINum,
				  int &OIINum,int &SiINum,int &SiIINum,
				  int &SiIIINum,int &CHINum,int &CH2INum,
				  int &CH3IINum,int &C2INum,int &COINum,
				  int &HCOIINum,int &OHINum,int &H2OINum,
				  int &O2INum);

/* Zeus Solver. */

  int ZeusSolver(float *gamma, int igamfield, int nhy, 
		 float dx[], float dy[], float dz[], 
		 int gravity, int NumberOfSubgrids, long_int GridGlobalStart[],
		 fluxes *SubgridFluxes[],
		 int NumberOfColours, int colnum[], int bottom,
		 float minsupecoef);

/* PPM Direct Euler Solver. */

int SolvePPM_DE(int CycleNumber, int NumberOfSubgrids, 
		fluxes *SubgridFluxes[], float *CellWidthTemp[], 
		Elong_int GridGlobalStart[], int GravityOn, 
		int NumberOfColours, int colnum[]);

int xEulerSweep(int k, int NumberOfSubgrids, fluxes *SubgridFluxes[], 
		Elong_int GridGlobalStart[], float *CellWidthTemp[], 
		int GravityOn, int NumberOfColours, int colnum[], float *pressure);

int yEulerSweep(int i, int NumberOfSubgrids, fluxes *SubgridFluxes[], 
		Elong_int GridGlobalStart[], float *CellWidthTemp[], 
		int GravityOn, int NumberOfColours, int colnum[], float *pressure);

int zEulerSweep(int j, int NumberOfSubgrids, fluxes *SubgridFluxes[], 
		Elong_int GridGlobalStart[], float *CellWidthTemp[], 
		int GravityOn, int NumberOfColours, int colnum[], float *pressure);

// AccelerationHack

  int AccelerationHack;

#ifdef SAB
  //These should be moved later.
  //Used for boundary condition set of AccelerationField.
  int ActualNumberOfBaryonFields;
  int AttachAcceleration();
  int DetachAcceleration();

  int    ActualFieldType[MAX_NUMBER_OF_BARYON_FIELDS];
  float *ActualBaryonField[MAX_NUMBER_OF_BARYON_FIELDS];
  float *ActualOldBaryonField[MAX_NUMBER_OF_BARYON_FIELDS];
  float *OldAccelerationField[3];
#endif

// -------------------------------------------------------------------------
// Functions for Specific problems (usually problem generator functions).
//

/* Generalized Extra Field Grid Initializer (returns NumberOfBaryonFields) */
  int InitializeTestProblemGrid(int field_counter);

/* Protostellar Collapse problem: initialize grid (returns SUCCESS or FAIL) */
  int ProtostellarCollapseInitializeGrid(float CoreDensity,
					 float CoreEnergy,
					 float CoreRadius,
					 float AngularVelocity);

/* HydroShockTubes problems: initialize grid (returns SUCCESS or FAIL) */

  int HydroShockTubesInitializeGrid(float InitialDiscontinuity,
				    float LeftDensity, float RightDensity,
				    float LeftVelocityX, float RightVelocityX,
				    float LeftVelocityY, float RightVelocityY,
				    float LeftVelocityZ, float RightVelocityZ,
				    float LeftPressure, float RightPressure);
  int HydroShockTubesInitializeGrid(float InitialDiscontinuity,
				    float SecondDiscontinuity,
				    float LeftDensity, float RightDensity,
				    float CenterDensity,
				    float LeftVelocityX, float RightVelocityX,
				    float CenterVelocityX,
				    float LeftVelocityY, float RightVelocityY,
				    float CenterVelocityY,
				    float LeftVelocityZ, float RightVelocityZ,
				    float CenterVelocityZ,
				    float LeftPressure, float RightPressure,
				    float CenterPressure);

/* Initialize for a uniform grid (returns SUCCESS or FAIL) */

  int InitializeUniformGrid(float UniformDensity, float UniformTotalEnergy,
			    float UniformGasEnergy, float UniformVelocity[], 
			    float UniformBField[]);


/* Initialize a grid for the Double Mach reflection problem. */

  int DoubleMachInitializeGrid(float d0, float e0, float u0,float v0,float w0);


/* Initialize a grid for Implosion test problem */

  int ImplosionInitializeGrid(float ImplosionDiamondDensity,
			      float ImplosionDiamondTotalEnergy);


/* Initialize a grid for Sedov Explosion */

  int SedovBlastInitializeGrid(float SedovBlastInitialRadius,
                               float SedovBlastInnerTotalEnergy);

  int SedovBlastInitializeGrid3D(char * fname);

  int SedovBlastInitializeGrid3DFixedR(float dr);


/* Initialize a grid for RadiatingShock (Sedov+Cooling) Explosion */

  int RadiatingShockInitializeGrid(FLOAT RadiatingShockInitialRadius,
				   float RadiatingShockInnerDensity,
				   float RadiatingShockInnerTotalEnergy,
				   int RadiatingShockUseDensityFluctuations,
				   int RadiatingShockRandomSeed,
				   float RadiatingShockDensityFluctuationLevel,
				   int RadiatingShockInitializeWithKE,
				   int RadiatingShockUseSedovProfile,
				   FLOAT RadiatingShockSedovBlastRadius,
				   float RadiatingShockEnergy,
				   float RadiatingShockPressure,
				   float RadiatingShockKineticEnergyFraction,
				   float RadiatingShockRhoZero,
				   float RadiatingShockVelocityZero,
				   int RadiatingShockRandomSeedInitialize,
				   FLOAT RadiatingShockCenterPosition[MAX_DIMENSION]);

  /* Initialize a grid for a rotating cylinder collapse */
  int RotatingCylinderInitializeGrid(FLOAT RotatingCylinderRadius,
				     FLOAT RotatingCylinderCenterPosition[MAX_DIMENSION],
				     float RotatingCylinderLambda,
				     float RotatingCylinderOverdensity);

  int RotatingSphereInitializeGrid(FLOAT RotatingSphereRadius,
				     FLOAT RotatingSphereCenterPosition[MAX_DIMENSION],
				     float RotatingSphereLambda,
				     float RotatingSphereOverdensity);

  /* Initialize a grid for the KH instability problem. */

  int KHInitializeGrid(float KHInnerDensity,
                       float KHInnerInternalEnergy,
                       float KHOuterInternalEnergy,
                       float KHPerturbationAmplitude,
                       float KHInnerVx, float KHOuterVx);

  /* Initialize a grid and set boundary for the 2D/3D Noh problem. */

  int NohInitializeGrid(float d0, float p0, float u0);
  int ComputeExternalNohBoundary();

/* Zeldovich Pancake: initial grid (returns SUCCESS or FAIL). */

  int ZeldovichPancakeInitializeGrid(int   ZeldovichPancakeDirection,
				     float ZeldovichPancakeCentralOffset,
				     float ZeldovichPancakeOmegaBaryonNow,
				     float ZeldovichPancakeOmegaCDMNow,
				     float ZeldovichPancakeCollapseRedshift,
				     float ZeldovichPancakeInitialTemperature,
				     float ZeldovichPancakeInitialUniformBField[]);

/* 1D Pressureless Collapse: initialize grid. */

  int PressurelessCollapseInitializeGrid(int PressurelessCollapseDirection,
				    float PressurelessCollapseInitialDensity,
				      int PressurelessCollapseNumberOfCells);

/* Gravity Test: particles in isolated boundaries */
  int TestOrbitInitializeGrid(int NumberOfTestParticles,
			      FLOAT TestRadius,
			      float CentralMass,
			      float TestMass,
			      int UseBaryons);

/* Gravity Test: initialize grid. */

  int TestGravityInitializeGrid(float CentralDensity, 
				int NumberOfNewParticles, int UseBaryons);

/* Gravity Test: check results. */

  int TestGravityCheckResults(FILE *fptr, grid *TopGrid);

/* Gravity Test Motion: initialize grid. */

  int TestGravityMotionInitializeGrid(float InitialVelocity);

/* Gravity Test (Sphere): initialize grid. */

  int TestGravitySphereInitializeGrid(float InteriorDensity, 
				      float ExteriorDensity,
				      float SphereRadius, 
				      int SphereType, int UseBaryons,
				      FLOAT SphereCenter[]);

/* Gravity Test (Sphere): check results. */

  int TestGravitySphereCheckResults(FILE *fptr);

/* Conduction Test: initialize grid. */

  int ConductionTestInitialize(float PulseHeight, FLOAT PulseWidth, int PulseType, FLOAT PulseCenter[MAX_DIMENSION], int FieldGeometry, float Bfield);

/* Conduction Cloud: initialize grid. */

  int ConductionCloudInitialize(float CloudOverdensity, FLOAT CloudWidth, int CloudType);

/* Conducting Bubble Test: initialize grid. */

  int ConductionBubbleInitialize(FLOAT BubbleRadius, int PulseType, float DeltaEntropy, 
				 float MidpointEntropy, float EntropyGradient,
				 float MidpointTemperature, FLOAT BubbleCenter[MAX_DIMENSION]);

/* Exploding Stratified Medium Test: initialize grid. */

  int StratifiedMediumExplosionInitialize(FLOAT BubbleRadius, int PulseType,
					  float ExplosionEnergy, FLOAT BubbleCenter[MAX_DIMENSION]);

/* Spherical Infall Test: initialize grid. */

  int SphericalInfallInitializeGrid(float InitialPerturbation, int UseBaryons,
				    float SphericalInfallOmegaBaryonNow,
				    float SphericalInfallOmegaCDMNow,
				    int SubgridIsStatic);


/* Spherical Infall Test: get the profile from the center. */

  int SphericalInfallGetProfile(int level, int ReportLevel);

/* GravityEquilibriumTest: initialize grid. */

  int GravityEquilibriumTestInitializeGrid(float ScaleHeight);

/* CollapseTest: initialize grid. */

#define MAX_SPHERES 10

  int CollapseTestInitializeGrid(int NumberOfSpheres,
			     FLOAT SphereRadius[MAX_SPHERES],
			     FLOAT SphereCoreRadius[MAX_SPHERES],
			     float SphereDensity[MAX_SPHERES],
			     float SphereTemperature[MAX_SPHERES],
			     float SphereMetallicity[MAX_SPHERES],
			     FLOAT SpherePosition[MAX_SPHERES][MAX_DIMENSION],
			     float SphereVelocity[MAX_SPHERES][MAX_DIMENSION],
			     float SphereFracKeplarianRot[MAX_SPHERES],
			     float SphereTurbulence[MAX_SPHERES],
			     float SphereDispersion[MAX_SPHERES],
			     float SphereCutOff[MAX_SPHERES],
			     float SphereAng1[MAX_SPHERES],
			     float SphereAng2[MAX_SPHERES],
			     int   SphereNumShells[MAX_SPHERES],
			     int   SphereType[MAX_SPHERES],
			     int   SphereUseParticles,
			     float ParticleMeanDensity,
			     float UniformVelocity[MAX_DIMENSION],
			     int   SphereUseColour,
			     int   SphereUseMetals,
			     float InitialTemperature, 
			     float InitialDensity, int level);

  /* CosmologySimulation: initialize grid. */
  int CosmologySimulationInitializeGrid(
			  int   InitialGridNumber,
			  float CosmologySimulationOmegaBaryonNow,
			  float CosmologySimulationOmegaCDMNow,
			  float CosmologySimulationInitialTemperature,
			  char *CosmologySimulationDensityName,
			  char *CosmologySimulationTotalEnergyName,
			  char *CosmologySimulationGasEnergyName,
			  char *CosmologySimulationVelocityNames[],
			  char *CosmologySimulationParticlePositionName,
			  char *CosmologySimulationParticleVelocityName,
 			  char *CosmologySimulationParticleDisplacementName,
			  char *CosmologySimulationParticleMassName,
			  char *CosmologySimulationParticleTypeName,
			  char *CosmologySimulationParticlePositionNames[],
			  char *CosmologySimulationParticleVelocityNames[],
 			  char *CosmologySimulationParticleDisplacementNames[],
			  int   CosmologySimulationSubgridsAreStatic,
			  int   TotalRefinement,
			  float CosmologySimulationInitialFractionHII,
			  float CosmologySimulationInitialFractionHeII,
			  float CosmologySimulationInitialFractionHeIII,
			  float CosmologySimulationInitialFractionHM,
			  float CosmologySimulationInitialFractionH2I,
			  float CosmologySimulationInitialFractionH2II,
			  float CosmologySimulationInitialFractionMetal,
			  float CosmologySimulationInitialFractionMetalIa,
#ifdef TRANSFER
			  float RadHydroInitialRadiationEnergy,
#endif
			  int   CosmologySimulationUseMetallicityField,
			  PINT &CurrentNumberOfParticles,
			  int CosmologySimulationManuallySetParticleMassRatio,
			  float CosmologySimulationManualParticleMassRatio,
			  int CosmologySimulationCalculatePositions,
			  float CosmologySimulationInitialUniformBField[]);

  int CosmologyReadParticles3D(
		   char *CosmologySimulationParticleVelocityName,
		   char *CosmologySimulationParticleMassName,
		   char *CosmologySimulationParticleTypeName,
		   char *CosmologySimulationParticleParticleNames[],
		   char *CosmologySimulationParticleVelocityNames[],
		   float CosmologySimulationOmegaBaryonNow,
		   int *Offset, int level);

  int CosmologyInitializeParticles(
		   char *CosmologySimulationParticleVelocityName,
 		   char *CosmologySimulationParticleDisplacementName,
		   char *CosmologySimulationParticleMassName,
		   char *CosmologySimulationParticleTypeName,
		   char *CosmologySimulationParticleVelocityNames[],
 		   char *CosmologySimulationParticleDisplacementNames[],
		   float CosmologySimulationOmegaBaryonNow,
		   int *Offset, int level);

  /* CosmologySimulation: initialize partitioned nested grids. */
  int NestedCosmologySimulationInitializeGrid(
			  int   InitialGridNumber,
			  float CosmologySimulationOmegaBaryonNow,
			  float CosmologySimulationOmegaCDMNow,
			  float CosmologySimulationInitialTemperature,
			  char *CosmologySimulationDensityName,
			  char *CosmologySimulationTotalEnergyName,
			  char *CosmologySimulationGasEnergyName,
			  char *CosmologySimulationVelocityNames[],
			  char *CosmologySimulationParticlePositionName,
			  char *CosmologySimulationParticleDisplacementName,
			  char *CosmologySimulationParticleVelocityName,
			  char *CosmologySimulationParticleMassName,
			  char *CosmologySimulationParticleTypeName,
			  char *CosmologySimulationParticleVelocityNames[],
			  char *CosmologySimulationParticleDisplacementNames[],
			  int   CosmologySimulationSubgridsAreStatic,
			  int   TotalRefinement,
			  float CosmologySimulationInitialFractionHII,
			  float CosmologySimulationInitialFractionHeII,
			  float CosmologySimulationInitialFractionHeIII,
			  float CosmologySimulationInitialFractionHM,
			  float CosmologySimulationInitialFractionH2I,
			  float CosmologySimulationInitialFractionH2II,
			  float CosmologySimulationInitialFractionMetal,
			  float CosmologySimulationInitialFractionMetalIa,
			  int   CosmologySimulationUseMetallicityField,
			  PINT &CurrentNumberOfParticles,
			  int CosmologySimulationManuallySetParticleMassRatio,
			  float CosmologySimulationManualParticleMassRatio,
			  int CosmologySimulationCalculatePositions,
			  FLOAT SubDomainLeftEdge[],
			  FLOAT SubDomainRightEdge[],
			  float CosmologySimulationInitialUniformBField[]);


  /* Initialization for isolated galaxy sims */
  int GalaxySimulationInitializeGrid(
				     FLOAT DiskRadius,
				     float GalaxyMass,
				     float GasMass,
				     FLOAT DiskPosition[MAX_DIMENSION], 
				     FLOAT ScaleHeightz,
				     FLOAT ScaleHeightR, 
				     float DMConcentration,
				     float DiskTemperature,
				     float InitialTemperature,
				     float AngularMomentum[MAX_DIMENSION],
				     float UniformVelocity[MAX_DIMENSION], 
				     int UseMetallicityField, 
				     float GalaxySimulationInflowTime,
				     float GalaxySimulationInflowDensity,
				     int level);

  /* Free expansion test */
  int FreeExpansionInitializeGrid(int FreeExpansionFullBox,
				  float FreeExpansionDensity,
				  double FreeExpansionEnergy,
				  float FreeExpansionMaxVelocity,
				  float FreeExpansionMass,
				  float FreeExpansionRadius,
				  float DensityUnits, float VelocityUnits,
				  float LengthUnits, float TimeUnits);

  /* Supernova restart initialize grid. */
  int SupernovaRestartInitialize(float EjectaDensity, float EjectaRadius,
				 float EjectaThermalEnergy, 
				 FLOAT EjectaCenter[3], int ColourField,
				 int *NumberOfCellsSet);

  /* Put Sink restart initialize grid. */
  int PutSinkRestartInitialize(int level ,int *NumberOfCellsSet);

  /* PhotonTest restart initialize grid. */
  int PhotonTestRestartInitialize(int level ,int *NumberOfCellsSet);

  /* Free-streaming radiation test problem: initialize grid (SUCCESS or FAIL) */
  int FSMultiSourceInitializeGrid(float DensityConst, float V0Const, 
				  float V1Const, float V2Const, float TEConst, 
				  float RadConst, int local);

  /* FLD Radiation test problem: initialize grid (SUCCESS or FAIL) */
  int RadHydroConstTestInitializeGrid(int NumChem, float DensityConst, 
				      float V0Const, float V1Const, 
				      float V2Const, float IEConst, 
				      float EgConst, float HMassFrac, 
				      float InitFracHII, float InitFracHeII, 
				      float InitFracHeIII, int local);

  /* FLD Radiation ionization test problem: initialize grid (SUCCESS or FAIL) */
  int RHIonizationTestInitializeGrid(int NumChem, float DensityConst, 
				     float V0Const, float V1Const, 
				     float V2Const, float IEConst, 
				     float EgConst, float HMassFrac, 
				     float InitFracHII, float InitFracHeII, 
				     float InitFracHeIII, int local);

  /* FLD Radiation clump ionization problem: initialize grid (SUCCESS or FAIL) */
  int RHIonizationClumpInitializeGrid(int NumChem, float NumDensityIn, 
				      float NumDensityOut, float V0Const,
				      float V1Const, float V2Const,
				      float IEConstIn, float IEConstOut, 
				      float EgConst, float HMassFrac, 
				      float InitFracHII, float ClumpCenterX0, 
				      float ClumpCenterX1, float ClumpCenterX2, 
				      float ClumpRadius, int local);

  /* FLD Rad r^{-2} density ionization problem: initialize grid (SUCCESS or FAIL) */
  int RHIonizationSteepInitializeGrid(int NumChem, float NumDensity, 
				      float DensityRadius, float DensityCenter0, 
				      float DensityCenter1, float DensityCenter2, 
				      float V0Const, float V1Const, 
				      float V2Const, float IEConst, 
				      float EgConst, float InitFracHII, int local);

  /* FLD Radiation test problem: cosmological HII ioniztion (SUCCESS or FAIL) */
  int CosmoIonizationInitializeGrid(int NumChem, float VxConst, float VyConst, 
				    float VzConst, float IEConst, 
				    float EgConst, float InitFracHII, 
				    float OmegaBaryonNow, int local);

  /* FLD Radiation test problem: stream test (SUCCESS or FAIL) */
  int RadHydroStreamTestInitializeGrid(float DensityConst, float EgConst,
				       int RadStreamDim, int RadStreamDir,
				       int local);

  /* FLD Radiation test problem: pulse test (SUCCESS or FAIL) */
  int RadHydroPulseTestInitializeGrid(float DensityConst, float EgConst,
				      int RadPulseDim, int local);

  /* FLD Radiation test problem: grey Marshak wave test (SUCCESS or FAIL) */
  int RadHydroGreyMarshakWaveInitializeGrid(float DensityConst, float IEConst, 
			      	            float EgConst, int GreyMarshDir,
					    int local);

  /* FLD Radiation test problem: radiating shock test (SUCCESS or FAIL) */
  int RadHydroRadShockInitializeGrid(float DensityConst, float TEConst, 
			      	     float REConst, float VelocityConst,
                                     int ShockDir, int local);

  /* Cooling test initialization */
  int CoolingTestInitializeGrid();

  /* Reset internal energy to initial values for cooling test. */
  int CoolingTestResetEnergies();

  /* One-zone free-fall test initialization */
  int OneZoneFreefallTestInitializeGrid(float InitialDensity,
					float MinimumTemperature,
					float MaximumTemperature,
					float MinimumMetallicity,
					float MaximumMetallicity);

  /* Solve free-fall analytical solution. */
  int SolveOneZoneFreefall();

/* Tricks for Random Forcing. */

  int ReturnNumberOfBaryonFields(){return NumberOfBaryonFields;};
  int SetNumberOfBaryonFields(int &number)
    {NumberOfBaryonFields = number; return 0;};
  int AppendForcingToBaryonFields();
  int DetachForcingFromBaryonFields();
  int RemoveForcingFromBaryonFields();
  int AddRandomForcing(float * norm, float dtTopGrid);
  int PrepareRandomForcingNormalization(float * GlobVal, int GlobNum);
  int ReadRandomForcingFields(FILE *main_file_pointer, char DataFilename[]);

  int AddFields(int TypesToAdd[], int NumberOfFields);
  int DeleteObsoleteFields(int *ObsoleteFields, 
			   int NumberOfObsoleteFields);
 
  inline bool isLocal () {return MyProcessorNumber == ProcessorNumber; };

 private:
//  int ReadRandomForcingFields(FILE *main_file_pointer);
 public:

/* TurbulenceSimulation: initialize grid. */

#define TURBULENCE_INIT_PARAMETERS_DECL \
     float TurbulenceSimulationInitialDensity, \
     float TurbulenceSimulationInitialDensityPerturbationAmplitude, \
     float TurbulenceSimulationInitialTemperature, \
     float TurbulenceSimulationInitialPressure, \
     float TurbulenceSimulationInitialMagneticField[], \
     char *TurbulenceSimulationMagneticNames[], \
     char *TurbulenceSimulationDensityName, \
     char *TurbulenceSimulationTotalEnergyName, \
     char *TurbulenceSimulationGasPressureName, \
     char *TurbulenceSimulationGasEnergyName, \
     char *TurbulenceSimulationVelocityNames[], \
     char *TurbulenceSimulationRandomForcingNames[], \
     int   TurbulenceSimulationSubgridsAreStatic, \
     int   TotalRefinement


#define TURBULENCE_INIT_PARAMETERS \
     TurbulenceSimulationInitialDensity, \
     TurbulenceSimulationInitialDensityPerturbationAmplitude, \
     TurbulenceSimulationInitialTemperature, \
     TurbulenceSimulationInitialPressure, \
     TurbulenceSimulationInitialMagneticField, \
     TurbulenceSimulationMagneticNames, \
     TurbulenceSimulationDensityName, \
     TurbulenceSimulationTotalEnergyName, \
     TurbulenceSimulationGasPressureName, \
     TurbulenceSimulationGasEnergyName, \
     TurbulenceSimulationVelocityNames, \
     TurbulenceSimulationRandomForcingNames, \
     TurbulenceSimulationSubgridsAreStatic, \
     TotalRefinement


 int TurbulenceSimulationInitializeGrid(TURBULENCE_INIT_PARAMETERS_DECL);
 int ComputeRandomForcingFields(int mode);
 int ExtraFunction(char * message); //for debugging.

  // The following are private since they should only be called by
  // TurbulenceSimulationInitializeGrid()

 private:
//  int TurbulenceSimulationInitializeGrid(TURBULENCE_INIT_PARAMETERS_DECL);
 public:


/* Comoving coordinate expansion terms. */

  int ComovingExpansionTerms();

/* Adjust the gravity source terms for comoving coordinates. */

  int ComovingGravitySourceTerm();

/* Star Particle handler routine. */

  int StarParticleHandler(HierarchyEntry* SubgridPointer, int level,
			  float dtLevelAbove);

/* Particle splitter routine. */

  int ParticleSplitter(int level);

/* Magnetic field resetting routine. */

  int MagneticFieldResetter(int level);

/* Apply a time-action to a grid. */

  int ApplyTimeAction(int Type, float Parameter);

/* Routine to set the tracer particle velocities from the grid velocity. */

  int TracerParticleSetVelocity();

/* Creates tracer particles in this grid. */

  int TracerParticleCreateParticles(FLOAT LeftEdge[], FLOAT RightEdge[],
                                    FLOAT Spacing, PINT &TotalParticleCount);


/* ShearingBox: initialize grid. */

  int ShearingBoxInitializeGrid(float ThermalMagneticRatio, float fraction, 
				float ShearingGeometry, 
				int InitialMagneticFieldConfiguration);

  int ShearingBox2DInitializeGrid(float ThermalMagneticRatio, float fraction, 
				float ShearingGeometry, 
			       int InitialMagneticFieldConfiguration);

  int ShearingBoxStratifiedInitializeGrid(float ThermalMagneticRatio, float fraction, 
				float ShearingGeometry, 
				int InitialMagneticFieldConfiguration);
// -------------------------------------------------------------------------
// Analysis functions for AnalysisBaseClass and it's derivatives.
//

  // Flag cells that overlap a subgrid (used for analysis).
  int FlagRefinedCells(grid *Subgrid);
  
  inline int IsInVolume( Eflt32 *LeftEdge, Eflt32 *RightEdge ){
    for( int i = 0; i < GridRank; i++ ){
      if( (GridLeftEdge[i] >= RightEdge[i]) ||
	  (GridRightEdge[i] <= LeftEdge[i]) ){
	return FALSE;
      }
    }
     return TRUE;
  }
  inline int IsInVolume( Eflt64 *LeftEdge, Eflt64 *RightEdge ){
    for( int i = 0; i < GridRank; i++ ){
      if( (GridLeftEdge[i] >= RightEdge[i]) ||
	  (GridRightEdge[i] <= LeftEdge[i]) ){
	return FALSE;
      }
    }
     return TRUE;
  }
  inline int IsInVolume( Eflt128 *LeftEdge, Eflt128 *RightEdge ){
    for( int i = 0; i < GridRank; i++ ){
      if( (GridLeftEdge[i] >= RightEdge[i]) ||
	  (GridRightEdge[i] <= LeftEdge[i]) ){
	return FALSE;
      }
    }
     return TRUE;
  }



  // Check to see if a FLOAT point is in the grid.
  inline int PointInGrid( Eflt32 *point ){
    for( int i = 0; i < GridRank; i++ ){
      if( ((point[i] >= GridLeftEdge[i]) &&
	  (point[i] < GridRightEdge[i])) == FALSE )
	return FALSE;
    }
    return TRUE;
  }
  inline int PointInGrid( Eflt64 *point ){
    for( int i = 0; i < GridRank; i++ ){
      if( ((point[i] >= GridLeftEdge[i]) &&
	  (point[i] < GridRightEdge[i])) == FALSE )
	return FALSE;
    }
    return TRUE;
  }
  inline int PointInGrid( Eflt128 *point ){
    for( int i = 0; i < GridRank; i++ ){
      if( ((point[i] >= GridLeftEdge[i]) &&
	  (point[i] < GridRightEdge[i])) == FALSE )
	return FALSE;
    }
    return TRUE;
  }

  // Check to see if a FLOAT point is in the grid (excluding boundaries)
  inline int PointInGridNB( Eflt32 *point ){
    for( int i = 0; i < GridRank; i++ ){
      if( ((point[i] > GridLeftEdge[i]) &&
	  (point[i] < GridRightEdge[i])) == FALSE )
	return FALSE;
    }
    return TRUE;
  }
  inline int PointInGridNB( Eflt64 *point ){
    for( int i = 0; i < GridRank; i++ ){
      if( ((point[i] > GridLeftEdge[i]) &&
	  (point[i] < GridRightEdge[i])) == FALSE )
	return FALSE;
    }
    return TRUE;
  }
  inline int PointInGridNB( Eflt128 *point ){
    for( int i = 0; i < GridRank; i++ ){
      if( ((point[i] > GridLeftEdge[i]) &&
	  (point[i] < GridRightEdge[i])) == FALSE )
	return FALSE;
    }
    return TRUE;
  }

  // Flags a 3D array where the grid overlaps.
  // Very similar to the FastSib stuff. (I think.)
  void FlagGridArray( HierarchyEntry ***GridArray, int *dx,
		      float *cell_width, HierarchyEntry *my_HE );

  /* Includes for analysis tools */

//#ifdef ANALYSIS_TOOLS
#include "../anyl/Grid_AnalyzeClusters.h"
//#endif

#ifdef USE_PYTHON
    void ConvertToNumpy(int GridID, PyArrayObject *container[],
                        int ParentID, int level, FLOAT WriteTime);
#endif
//------------------------------------------------------------------------
// Methods for star formation
//------------------------------------------------------------------------

  Star *ReturnStarPointer(void) { return Stars; };
  int ReturnNumberOfStars(void) { return NumberOfStars; };
  void SetNumberOfStars(int value) { NumberOfStars = value; };

  /* Calculate enclosed mass within a radius */

  int GetEnclosedMass(Star *star, float radius, float &mass,
		      float &metallicity, float &coldgas_mass, 
		      float AvgVelocity[]);
  int GetEnclosedMass(FLOAT star_pos[], float radius, float &mass,
		      float &metallicity, float &coldgas_mass, 
		      float AvgVelocity[], float &OneOverRSquaredSum);
  int GetEnclosedMassInShell(Star *star, float radius0, float radius1, 
			     float &mass, float &metallicity2, 
			     float &metallicity3,
			     float &coldgas_mass, float AvgVelocity[]);

  int RemoveParticle(int ID, bool disable=false);

  int AddFeedbackSphere(Star *cstar, int level, float radius, float DensityUnits,
			float LengthUnits, float VelocityUnits, 
			float TemperatureUnits, float TimeUnits, double EjectaDensity, 
			double EjectaMetalDensity, double EjectaThermalEnergy,
			int &CellsModified);

  int SubtractAccretedMassFromSphere(Star *cstar, int level, float radius, float DensityUnits,
				     float LengthUnits, float VelocityUnits, 
				     float TemperatureUnits, float TimeUnits, double EjectaDensity, 
				     int &CellsModified);

  int MoveAllStars(int NumberOfGrids, grid* FromGrid[], int TopGridDimension);

  int MoveAllStarsOld(int NumberOfGrids, grid* FromGrid[], int TopGridDimension);

  int CommunicationSendStars(grid *ToGrid, int ToProcessor);

  int TransferSubgridStars(int NumberOfSubgrids, grid* ToGrids[], int AllLocal);
  
  int FindNewStarParticles(int level);

  int FindAllStarParticles(int level);

  int MirrorStarParticles(void);

  int UpdateStarParticles(int level);

  int AddH2Dissociation(Star *AllStars);

  int ReturnStarStatistics(int &Number, float &minLife);

//------------------------------------------------------------------------
// Radiative transfer methods that don't fit in the TRANSFER define
//------------------------------------------------------------------------

  int IdentifyRadiativeTransferFields(int &kphHINum, int &gammaNum,
				      int &kphHeINum, int &kphHeIINum, 
				      int &kdissH2INum);

#ifdef TRANSFER
#include "PhotonGrid_Methods.h"
#endif /* TRANSFER */

//------------------------------------------------------------------------
// Vertex interpolation (for radiative transfer and streaming data)
//------------------------------------------------------------------------

  int ComputeVertexCenteredField(int Num);
  int ComputeCellCenteredField(int Num);
  
  float ComputeInterpolatedValue(int Num, int vci, int vcj, int vck, 
				 float mx, float my, float mz);
  
  int NeighborIndices(int index, int vi[]);
  int NeighborVertexIndices(int index, int vi[]);

  void DeleteInterpolatedFields() {
    int i;
    for (i = 0; i < NumberOfBaryonFields; i++)
      if (InterpolatedField[i] != NULL) {
	delete [] InterpolatedField[i];
	InterpolatedField[i] = NULL;
      }
  }

//-----------------------------------------------------------------------
//  Returns radiative cooling by component
//-----------------------------------------------------------------------

  int ComputeLuminosity(float *luminosity, int NumberOfLuminosityFields);
  int ComputeMetalLineLuminosity(float *total_luminosity, float *all_emis, 
				 float *temperature);


//------------------------------------------------------------------------
//  Shearing Boundary Conditions
//------------------------------------------------------------------------

  bool isTopGrid(){
    for(int i=0; i<GridRank; i++){
      if (CellWidth[i][0]<TopGridDx[i]*0.95) return FALSE;
      if (CellWidth[i][0]>TopGridDx[i]*1.05) return FALSE;
    }
    return TRUE;};
  
//------------------------------------------------------------------------
//  Misc.
//------------------------------------------------------------------------

  int FindMinimumParticleMass(float &min_mass, int level);

  int FindMassiveParticles(float min_mass, int level, FLOAT *pos[], int &npart,
			   int CountOnly);

//------------------------------------------------------------------------
//  Inline FOF halo finder and particle interpolation using a tree
//------------------------------------------------------------------------

  int MoveParticlesFOF(int level, FOF_particle_data* &P, 
		       int &Index, FOFData AllVars, float VelocityUnits, 
		       double MassUnits, int CopyDirection);

  int InterpolateParticlesToGrid(FOFData *D);

//------------------------------------------------------------------------
//  Grid star particles onto the AMR mesh
//------------------------------------------------------------------------

  int InterpolateStarParticlesToGrid(int NumberOfSPFields);  

//------------------------------------------------------------------------
// new hydro & MHD routines
//------------------------------------------------------------------------

  int SetNumberOfColours(void);
  int SaveSubgridFluxes(fluxes *SubgridFluxes[], int NumberOfSubgrids,
                        float *Flux3D[], int flux, float fluxcoef, float dt);
  void ZeroFluxes(fluxes *SubgridFluxes[], int NumberOfSubgrids);
  int RungeKutta2_1stStep(fluxes *SubgridFluxes[],
                          int NumberOfSubgrids, int level,
                          ExternalBoundary *Exterior);
  int RungeKutta2_2ndStep(fluxes *SubgridFluxes[],
                          int NumberOfSubgrids, int level,
                          ExternalBoundary *Exterior);
  int ReturnHydroRKPointers(float **Prim, bool ReturnMassFractions = true);
  int ReturnOldHydroRKPointers(float **Prim, bool ReturnMassFractions = true);
  int UpdateElectronDensity(void);
  int UpdatePrim(float **dU, float c1, float c2);
  int Hydro3D(float **Prim, float **dU, float dt,
	      fluxes *SubgridFluxes[], int NumberOfSubgrids,
	      float fluxcoef, int fallback);
  int TurbulenceInitializeGrid(float CloudDensity, float CloudSoundSpeed, FLOAT CloudRadius, 
			       float CloudMachNumber, float CloudAngularVelocity, float InitialBField,
			       int SetTurbulence, int CloudType, int TurbulenceSeed, int PutSink, 
			       int level, int SetBaryonFields);
  int Collapse3DInitializeGrid(int n_sphere,
			       FLOAT r_sphere[MAX_SPHERES],
			       FLOAT rc_sphere[MAX_SPHERES],
			       float rho_sphere[MAX_SPHERES],
			       float p_sphere[MAX_SPHERES],
			       float cs_sphere[MAX_SPHERES],
			       FLOAT sphere_position[MAX_SPHERES][MAX_DIMENSION],
			       float omega_sphere[MAX_SPHERES],
			       int   sphere_type[MAX_SPHERES],
			       float rho_medium, float p_medium, int level);
  int Collapse1DInitializeGrid(FLOAT r_sphere,
			       FLOAT rc_sphere,
			       float rho_sphere,
			       float p_sphere,
			       float cs_sphere,
			       float omega_sphere,
			       int   sphere_type,
			       float rho_medium, float p_medium);
  int AddSelfGravity(float coef);
  int SourceTerms(float **dU);
  int MHD1DTestInitializeGrid(float rhol, float rhor,
			      float vxl,  float vxr,
			      float vyl,  float vyr,
			      float vzl,  float vzr,
			      float pl,   float pr,
			      float Bxl,  float Bxr,
			      float Byl,  float Byr,
			      float Bzl,  float Bzr);
  int MHD1DTestWavesInitializeGrid(float rhol, 
                                   float vxl,
                                   float vyl,
                                   float vzl,
                                   float etotl,
                                   float Bxl,
                                   float Byl,
                                   float Bzl);
  int MHD2DTestInitializeGrid(int MHD2DProblemType, 
			      int UseColour,
			      float RampWidth,
			      float rhol, float rhou,
			      float vxl,  float vxu,
			      float vyl,  float vyu,
			      float pl,   float pu,
			      float Bxl,  float Bxu,
			      float Byl,  float Byu);
  int MHD3DTestInitializeGrid(int MHD3DProblemType,
			      float rhol, float rhou,
			      float vxl,  float vxu,
			      float vyl,  float vyu,
			      float pl,   float pu,
			      float Bxl,  float Bxu,
			      float Byl,  float Byu);
  int CollapseMHD3DInitializeGrid(int n_sphere,
				  FLOAT r_sphere[MAX_SPHERES],
				  FLOAT rc_sphere[MAX_SPHERES],
				  float rho_sphere[MAX_SPHERES],
				  float p_sphere[MAX_SPHERES],
				  float cs_sphere[MAX_SPHERES],
				  FLOAT sphere_position[MAX_SPHERES][MAX_DIMENSION],
				  float omega_sphere[MAX_SPHERES], 
				  float turb_sphere[MAX_SPHERES], 
				  float Bnaught, float theta_B,
				  int Bdirection,
				  int   sphere_type[MAX_SPHERES],
				  float rho_medium, float p_medium, int level, int SetBaryonFields);
  int MHDTurbulenceInitializeGrid(float rho_medium, float cs_medium, float mach, 
				  float Bnaught, int seed, int level, int SetBaryonFields);
  int MHDDecayingRandomFieldInitializeGrid(float rho_medium, float cs_medium, float mach, 
					   float Bnaught, int seed, 
					   float Sindex, float Skmin, float Skmax, 
					   int level, int SetBaryonFields);

  int PrepareVelocityNormalization(double *v_rms, double *Volume);
  int NormalizeVelocities(Eflt factor);

  int PrepareAlfvenVelocityNormalization(double *v_rms, double *Volume);
  int NormalizeMagneticFields(Eflt factor);

  int GalaxyDiskInitializeGrid(int NumberOfHalos,
			       FLOAT HaloRadius[MAX_SPHERES],
			       FLOAT HaloCoreRadius[MAX_SPHERES],
			       float HaloDensity[MAX_SPHERES],
			       float HaloTemperature[MAX_SPHERES],
			       FLOAT HaloPosition[MAX_SPHERES][MAX_DIMENSION],
			       float HaloSpin[MAX_SPHERES],
			       float HaloVelocity[MAX_SPHERES][MAX_DIMENSION],
			       float HaloAngVel[MAX_SPHERES],
			       float HaloMagneticField,
			       FLOAT DiskRadius[MAX_SPHERES],
			       FLOAT DiskHeight[MAX_SPHERES],
			       float DiskDensity[MAX_SPHERES],
			       float DiskTemperature[MAX_SPHERES],
			       float DiskMassFraction[MAX_SPHERES],
			       float DiskFlaringParameter[MAX_SPHERES],
			       int   GalaxyType[MAX_SPHERES],
			       int   UseParticles, int UseGas,
			       float UniformVelocity[MAX_DIMENSION],
			       float MediumTemperature, float MediumDensity, int level);
  int AGNDiskInitializeGrid(float BlackHoleMass,
			    int BlackHoleType,
			    int DiskType,
			    float DiskDensity,
			    float DiskTemperature,
			    FLOAT DiskRadius,
			    FLOAT DiskHeight, 
			    int UseGas, int level);
  int MHDRK2_1stStep(fluxes *SubgridFluxes[], 
		     int NumberOfSubgrids, int level,
		     ExternalBoundary *Exterior);
  int MHDRK2_2ndStep(fluxes *SubgridFluxes[], 
		     int NumberOfSubgrids, int level,
		     ExternalBoundary *Exterior);
  int MHD3D(float **Prim, float **dU, float dt,
	    fluxes *SubgridFluxes[], int NumberOfSubgrids,
	    float fluxcoef, int fallback);
  int MHDSourceTerms(float **dU);
  int UpdateMHDPrim(float **dU, float c1, float c2);
  int SaveMHDSubgridFluxes(fluxes *SubgridFluxes[], int NumberOfSubgrids,
			   float *Flux3D[], int flux, float fluxcoef, float dt);
  int SetFloor();


  /* Poisson clean routines */

  int PoissonSolver(int level);

  int PoissonSolverSOR();
  int PoissonSolverSOR2();
  int PoissonSolverFFT();
  int PoissonSolverMultigrid();

  int PoissonSolverCGA(int difftype, double *divB_p);
  template <typename T> int multA(T* input, T* output,  int *MatrixStartIndex, int *MatrixEndIndex);
  template <typename T> int multA2(T* input, T* output,  int *MatrixStartIndex, int *MatrixEndIndex);
  template <typename T> T dot(T *a, T *b,  int size);
  template <typename T> int setNeumannBC(T* x, int *MatrixStartIndex, int *MatrixEndIndex,int type);
  template <typename T> int setDirichletBC(T* x, int *MatrixStartIndex, int *MatrixEndIndex);

  int PoissonCleanStep(int level);

  int GetIndex(int i, int j, int k) { 
    return i + j*(GridDimension[0])
      + k*(GridDimension[0])*(GridDimension[1]);
  }
  
  int PoissonSolverTestInitializeGrid(int TestType, float GeometryControl);

  

  int PrintToScreenBoundaries(float *field, char *display, int direction, int slice,
			      int check, float diffvalue);  
  int PrintToScreenBoundaries(float *field, char *display, int direction, int slice);
  int PrintToScreenBoundaries(float *field, char *display);
  int PrintToScreenBoundaries();
  int PrintToScreenBoundaries(int field);

  int getField(int i){return FieldType[i];};
  
  int ReduceWindBoundary();

  /* New particle routines */
  int CheckParticle();

  int ReturnMaximumParticleNumber();

  int ReturnNumberOfNewParticles() {
    int np = 0;
    for (int n = 0; n < NumberOfParticles; n++)
      if (ParticleNumber[n] < 0) np++;
    return np;
  };
  
  /* Non-ideal effects */

  int AddViscosity();
  int ComputeViscosity(float *viscosity, int DensNum);

  int AddAmbipolarDiffusion();

  int AddResistivity();
  int ComputeResistivity(float *resistivity, int DensNum);
  /* END OF NEW STANFORD HYDRO/MHD ROUTINES */

};

// inline int grid::ReadRandomForcingFields (FILE *main_file_pointer);

// inline int grid::TurbulenceSimulationInitializeGrid (TURBULENCE_INIT_PARAMETERS_DECL);

#ifdef NEW_PROBLEM_TYPES
class ProblemTypeGrid : private grid {
    friend class EnzoProblemType;
    friend class FieldContainer;
};
#endif


#endif