Source

enzo-timing-woc / src / enzo / EvolveLevel.C

The trunk branch has multiple heads

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
/***********************************************************************
/
/  EVOLVE LEVEL FUNCTION
/
/  written by: Greg Bryan
/  date:       November, 1994
/  modified1:  February, 1995 by GB
/              Overhauled to make sure that all the subgrid's of a grid
/              advance with in lock step (i.e. with the same timestep and
/              in order).  This was done to allow a subgrid to get it's
/              boundary values from another subgrid (with the same parent).
/              Previously, a subgrid' BVs were always interpolated from its
/              parent.
/  modified2:  August, 1995 by GB
/                1) All grids on a level are processed at the same time
/                 (rather than all the subgrids of one parent).
/                2) C routines are called to loop over subgrids
/                 (so parallelizing C compilers can be used).
/                3) Subgrid timesteps are not constant over top grid step.
/              June, 1999 by GB -- Clean up somewhat
/
/  modified3:  August, 2001 by Alexei Kritsuk
/                Added 2nd call of PrepareDensityField() to compute
/                grav. potential (to be written with other baryon fields).
/  modified4:  January, 2004 by Alexei Kritsuk
/                Added support for RandomForcing
/  modified5:  February, 2006 by Daniel Reynolds
/                Added PotentialBdry to EvolveLevel and 
/                PrepareDensityField calls, so that it can be used
/                within computing isolating BCs for self-gravity.
/  modified6:  January, 2007 by Robert Harkness
/                Group and in-core i/o
/  modified7:  December, 2007 by Robert Harkness
/                Optional StaticSiblingList for root grid
/  modified8:  April, 2009 by John Wise
/                Added star particle class and radiative transfer
/
/  PURPOSE:
/    This routine is the main grid evolution function.  It assumes that the
/    grids of level-1 have already been advanced by dt (passed
/    in the argument) and that their boundary values are properly set.
/    We then perform a complete update on all grids on level, including:
/       - for each grid: set the boundary values from parent/subgrids
/       - for each grid: get a list of its subgrids
/       - determine the timestep based on the minimum timestep for all grids
/       - subcycle over the grid timestep and for each grid:
/           - copy the fields to the old fields
/           - solve the hydro equations (and save fluxes around subgrid)
/           - set the boundary values from parent and/or other grids
/           - update time and check dt(min) for that grid against dt(cycle)
/           - call EvolveLevel(level+1)
/           - accumulate flux around this grid
/       - correct the solution on this grid based on subgrid solutions
/       - correct the solution on this grid based on improved subgrid fluxes
/
/    This routine essentially solves (completely) the grids of this level
/       and all finer levels and then corrects the solution of
/       grids on this level based on the improved subgrid solutions/fluxes.
/
/    Note: as a convenience, we store the current grid's fluxes (i.e. the
/          fluxes around the exterior of this grid) as the last entry in
/          the list of subgrids.
/
************************************************************************/
 
#ifdef USE_MPI
#include "mpi.h"
#endif /* USE_MPI */
 
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>

#include "performance.h"
#include "macros_and_parameters.h"
#include "typedefs.h"
#include "global_data.h"
#include "Fluxes.h"
#include "GridList.h"
#include "ExternalBoundary.h"
#include "Grid.h"
#include "Hierarchy.h"
#include "TopGridData.h"
#include "LevelHierarchy.h"
 
/* function prototypes */
 
void DeleteFluxes(fluxes *Fluxes);
int  RebuildHierarchy(TopGridData *MetaData,
		      LevelHierarchyEntry *LevelArray[], int level);
int  ReportMemoryUsage(char *header = NULL);
int  UpdateParticlePositions(grid *Grid);
int  CheckEnergyConservation(HierarchyEntry *Grids[], int grid,
			     int NumberOfGrids, int level, float dt);
float CommunicationMinValue(float Value);
int GenerateGridArray(LevelHierarchyEntry *LevelArray[], int level,
		      HierarchyEntry **Grids[]);
 
#ifdef FAST_SIB
int PrepareDensityField(LevelHierarchyEntry *LevelArray[],
			SiblingGridList SiblingList[],
			int level, TopGridData *MetaData, FLOAT When);
#else  // !FAST_SIB
int PrepareDensityField(LevelHierarchyEntry *LevelArray[],
                        int level, TopGridData *MetaData, FLOAT When);
#endif  // end FAST_SIB
 
#ifdef FAST_SIB
int SetBoundaryConditions(HierarchyEntry *Grids[], int NumberOfGrids,
			  SiblingGridList SiblingList[],
			  int level, TopGridData *MetaData,
			  ExternalBoundary *Exterior, LevelHierarchyEntry * Level);
#else
int SetBoundaryConditions(HierarchyEntry *Grids[], int NumberOfGrids,
                          int level, TopGridData *MetaData,
                          ExternalBoundary *Exterior, LevelHierarchyEntry * Level);
#endif

#ifdef SAB
#ifdef FAST_SIB
int SetAccelerationBoundary(HierarchyEntry *Grids[], int NumberOfGrids,
			    SiblingGridList SiblingList[],
			    int level, TopGridData *MetaData,
			    ExternalBoundary *Exterior,
			    LevelHierarchyEntry * Level,
			    int CycleNumber);
#else
int SetAccelerationBoundary(HierarchyEntry *Grids[], int NumberOfGrids,
			    int level, TopGridData *MetaData, 
			    ExternalBoundary *Exterior,
			    LevelHierarchyEntry * Level,
			    int CycleNumber);
#endif
#endif

#ifdef FLUX_FIX
int UpdateFromFinerGrids(int level, HierarchyEntry *Grids[], int NumberOfGrids,
			 int NumberOfSubgrids[],
			 fluxes **SubgridFluxesEstimate[],
			 LevelHierarchyEntry *SUBlingList[],
			 TopGridData *MetaData);
#else
int UpdateFromFinerGrids(int level, HierarchyEntry *Grids[], int NumberOfGrids,
			 int NumberOfSubgrids[],
			 fluxes **SubgridFluxesEstimate[]);
#endif
 
int RadiationFieldUpdate(LevelHierarchyEntry *LevelArray[], int level,
			 TopGridData *MetaData);


OutputFromEvolveLevel(LevelHierarchyEntry *LevelArray[],TopGridData *MetaData,
		      int level, ExternalBoundary *Exterior);
 
int ComputeRandomForcingNormalization(LevelHierarchyEntry *LevelArray[],
                                      int level, TopGridData *MetaData,
                                      float * norm, float * pTopGridTimeStep);

int FastSiblingLocatorInitializeStaticChainingMesh(ChainingMeshStructure *Mesh, int Rank,
						   int TopGridDims[]); 
int FastSiblingLocatorInitialize(ChainingMeshStructure *Mesh, int Rank,
				 int TopGridDims[]);
int FastSiblingLocatorFinalize(ChainingMeshStructure *Mesh);
 
#ifdef FLUX_FIX
int CreateSUBlingList(TopGridData *MetaData,
		      HierarchyEntry *Grids[],
		      int NumberOfGrids,
		      LevelHierarchyEntry ***SUBlingList);
int DeleteSUBlingList(int NumberOfGrids,
		      LevelHierarchyEntry **SUBlingList);
#endif

int StarParticleInitialize(LevelHierarchyEntry *LevelArray[], int ThisLevel,
			   TopGridData *MetaData, Star *&AllStars);
int StarParticleFinalize(HierarchyEntry *Grids[], TopGridData *MetaData,
			 int NumberOfGrids, LevelHierarchyEntry *LevelArray[], 
			 int level, Star *&AllStars);
int AdjustRefineRegion(LevelHierarchyEntry *LevelArray[], 
		       TopGridData *MetaData);

#ifdef TRANSFER
int EvolvePhotons(TopGridData *MetaData,LevelHierarchyEntry *LevelArray[],
		  Star *AllStars);
int RadiativeTransferPrepare(LevelHierarchyEntry *LevelArray[], int level,
			     TopGridData *MetaData, Star *&AllStars,
			     float dtLevelAbove);
#endif

void my_exit(int status);
 
 
int LevelCycleCount[MAX_DEPTH_OF_HIERARCHY];
double LevelWallTime[MAX_DEPTH_OF_HIERARCHY];
double LevelZoneCycleCount[MAX_DEPTH_OF_HIERARCHY];
double LevelZoneCycleCountPerProc[MAX_DEPTH_OF_HIERARCHY];
 
static float norm = 0.0;            //AK
static float TopGridTimeStep = 0.0; //AK

static int StaticSiblingListInitialized = 0;

#ifdef STATIC_SIBLING_LIST
static SiblingGridList StaticSiblingList[MAX_NUMBER_OF_SUBGRIDS];
static int StaticLevelZero = 1;
#else
static int StaticLevelZero = 0;
#endif

#define TIME_MESSAGING 


int EvolveLevel(TopGridData *MetaData, LevelHierarchyEntry *LevelArray[],
		int level, float dtLevelAbove, ExternalBoundary *Exterior)
{
  /* Declarations */

  int dbx = 0;
 
  FLOAT When;
  float dtThisLevelSoFar = 0.0, dtThisLevel, dtGrid, dtActual, dtLimit;
  int RefinementFactors[MAX_DIMENSION];
  int cycle = 0, counter = 0, grid1, subgrid, grid2;
  HierarchyEntry *NextGrid;
  int dummy_int;
 
#if defined(USE_JBPERF) && defined(JB_PERF_LEVELS)
  Eint32 jb_level = level;
  jbPerf.attribute ("level",&jb_level,JB_INT);
#endif

  /* Create an array (Grids) of all the grids. */

  JBPERF_START("evolve-level-01"); // GenerateGridArray ()

  typedef HierarchyEntry* HierarchyEntryPointer;
  HierarchyEntry **Grids;
  int NumberOfGrids = GenerateGridArray(LevelArray, level, &Grids);
  int *NumberOfSubgrids = new int[NumberOfGrids];
  fluxes ***SubgridFluxesEstimate = new fluxes **[NumberOfGrids];

  JBPERF_STOP("evolve-level-01"); // GenerateGridArray ()

  JBPERF_START("evolve-level-02"); // SetBoundaryConditions()
  TIME_MSG("Entered EvolveLevel");

#ifdef FLUX_FIX
  /* Create a SUBling list of the subgrids */
 
  LevelHierarchyEntry **SUBlingList;
#endif

  /* Initialize the chaining mesh used in the FastSiblingLocator. */

  if (dbx) fprintf(stderr, "EL: Initialize FSL \n"); 

  // If this is level 0 the SiblingList does not change and can be static

#ifdef STATIC_SIBLING_LIST
  if ( StaticLevelZero == 1 && level == 0 ) {

    if (!StaticSiblingListInitialized) {

      if (debug) fprintf(stderr, "INITIALIZE Level 0 StaticSiblingList\n");

      ChainingMeshStructure StaticChainingMesh;

      FastSiblingLocatorInitializeStaticChainingMesh
	(&StaticChainingMesh, MetaData->TopGridRank, MetaData->TopGridDims);

      for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
        Grids[grid1]->GridData->FastSiblingLocatorAddGrid(&StaticChainingMesh);

      for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
        if (Grids[grid1]->GridData->FastSiblingLocatorFindSiblings(
                              &StaticChainingMesh, &StaticSiblingList[grid1],
                              MetaData->LeftFaceBoundaryCondition,
                              MetaData->RightFaceBoundaryCondition) == FAIL) {
          fprintf(stderr, "Error in grid->FastSiblingLocatorFindSiblings.\n");
          return FAIL;
        }

      /* Clean up the chaining mesh. */

      FastSiblingLocatorFinalize(&StaticChainingMesh);

      StaticSiblingListInitialized = 1;

    }

  } // if StaticLevelZero && level == 0
#endif

  SiblingGridList *SiblingList = new SiblingGridList[NumberOfGrids];

  ChainingMeshStructure ChainingMesh;

#ifdef STATIC_SIBLING_LIST
  if (StaticLevelZero == 1 && level == 0 ) {

    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
      SiblingList[grid1].NumberOfSiblings = StaticSiblingList[grid1].NumberOfSiblings;
      SiblingList[grid1].GridList = StaticSiblingList[grid1].GridList;
    }

  }
#endif

  if (( StaticLevelZero == 1 && level != 0 ) || StaticLevelZero == 0 ) {

  FastSiblingLocatorInitialize(&ChainingMesh, MetaData->TopGridRank,
			       MetaData->TopGridDims);
 
  /* Add all the grids to the chaining mesh. */

  if (dbx) fprintf(stderr, "EL: FSL AddGrid entry \n");
  for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
    Grids[grid1]->GridData->FastSiblingLocatorAddGrid(&ChainingMesh);

  if (dbx) fprintf(stderr, "EL: FSL AddGrid exit \n");
 
  /* For each grid, get a list of possible siblings from the chaining mesh. */
 
  for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
    if (Grids[grid1]->GridData->FastSiblingLocatorFindSiblings(
                              &ChainingMesh, &SiblingList[grid1],
			      MetaData->LeftFaceBoundaryCondition,
			      MetaData->RightFaceBoundaryCondition) == FAIL) {
      fprintf(stderr, "Error in grid->FastSiblingLocatorFindSiblings.\n");
      return FAIL;
    }
 
  /* Clean up the chaining mesh. */
 
  FastSiblingLocatorFinalize(&ChainingMesh);

  }

  /* On the top grid, adjust the refine region so that only the finest
     particles are included.  We don't want the more massive particles
     to contaminate the high-resolution region. */

  if (RefineRegionAutoAdjust && level == 0)
    if (AdjustRefineRegion(LevelArray, MetaData) == FAIL) {
      fprintf(stderr, "Error in AdjustRefineRegion.\n");
      return FAIL;
    }

  /* ================================================================== */
  /* For each grid: a) interpolate boundaries from its parent.
                    b) copy any overlapping zones.  */
 
#ifdef FAST_SIB
  if (SetBoundaryConditions(Grids, NumberOfGrids, SiblingList,
			    level, MetaData, Exterior, LevelArray[level]) == FAIL)
    return FAIL;
#else
  if (SetBoundaryConditions(Grids, NumberOfGrids, level, MetaData,
                            Exterior, LevelArray[level]) == FAIL)
    return FAIL;
#endif
 
  JBPERF_STOP("evolve-level-02"); // SetBoundaryConditions()

  /* Clear the boundary fluxes for all Grids (this will be accumulated over
     the subcycles below (i.e. during one current grid step) and used to by the
     current grid to correct the zones surrounding this subgrid (step #18). */
 
  TIME_MSG("after SetBoundaryConditions");
  JBPERF_START("evolve-level-03"); // ClearBoundaryFluxes()

  for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
    Grids[grid1]->GridData->ClearBoundaryFluxes();
 
  JBPERF_STOP("evolve-level-03"); // ClearBoundaryFluxes()

  /* ================================================================== */
  /* Loop over grid timesteps until the elapsed time equals the timestep
     from the level above (or loop once for the top level). */
 
  while (dtThisLevelSoFar < dtLevelAbove) {
 
    /* Determine the timestep for this iteration of the loop. */
 
    JBPERF_START("evolve-level-04"); // SetTimeStep()

    if (level == 0) {
 
      /* For root level, use dtLevelAbove. */
 
      dtThisLevel      = dtLevelAbove;
      dtThisLevelSoFar = dtLevelAbove;
      dtActual         = dtLevelAbove;
 
    } else {
 
      /* Compute the mininum timestep for all grids. */
 
      dtThisLevel = huge_number;
      for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
	dtGrid      = Grids[grid1]->GridData->ComputeTimeStep();
	dtThisLevel = min(dtThisLevel, dtGrid);
      }
      dtThisLevel = CommunicationMinValue(dtThisLevel);

      dtActual = dtThisLevel;

#ifdef USE_DT_LIMIT

//    dtLimit = LevelZeroDeltaT/(4.0)/POW(RefineBy,level);

      dtLimit = 0.5/(4.0)/POW(2.0,level);

      if ( dtActual < dtLimit ) {
        dtThisLevel = dtLimit;
      }

#endif
 
      /* Advance dtThisLevelSoFar (don't go over dtLevelAbove). */
 
      if (dtThisLevelSoFar+dtThisLevel*1.05 >= dtLevelAbove) {
	dtThisLevel      = dtLevelAbove - dtThisLevelSoFar;
	dtThisLevelSoFar = dtLevelAbove;
      }
      else
	dtThisLevelSoFar += dtThisLevel;
 
    }

    if (debug) printf("Level[%"ISYM"]: dt = %"GSYM"  %"GSYM"  (%"GSYM"/%"GSYM")\n", level, dtThisLevel, dtActual,
		      dtThisLevelSoFar, dtLevelAbove);
 
    /* Set all grid's timestep to this minimum dt. */
 
    for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
      Grids[grid1]->GridData->SetTimeStep(dtThisLevel);
 
    JBPERF_STOP("evolve-level-04"); // SetTimeStep()

    /* Initialize the star particles */

    Star *AllStars = NULL;
    if (StarParticleCreation || StarParticleFeedback)
      if (StarParticleInitialize(LevelArray, level, MetaData, 
				 AllStars) == FAIL) {
	fprintf(stderr, "Error in StarParticleInitalize.\n");
	return FAIL;
      }

    /* Initialize the radiative transfer */

#ifdef TRANSFER
    if (RadiativeTransfer)
      if (RadiativeTransferPrepare(LevelArray, level, MetaData, AllStars, 
				   dtLevelAbove) == FAIL) {
	fprintf(stderr, "Error in RadiativeTransferPrepare.\n");
	return FAIL;
      }
#endif /* TRANSFER */

    /* For each grid, compute the number of it's subgrids. */
 
    JBPERF_START("evolve-level-05"); // compute number of subgrids

    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
      NextGrid = Grids[grid1]->NextGridNextLevel;
      counter = 0;
      while (NextGrid != NULL) {
	NextGrid = NextGrid->NextGridThisLevel;
	if (++counter > MAX_NUMBER_OF_SUBGRIDS) {
	  fprintf(stderr, "More subgrids than MAX_NUMBER_OF_SUBGRIDS.\n");
	  return FAIL;
	}
      }
      NumberOfSubgrids[grid1] = counter + 1;
    }
 
    JBPERF_STOP("evolve-level-05"); // compute number of subgrids
    TIME_MSG("Before subgrid fluxes");


    /* For each grid, create the subgrid list. */
 
    JBPERF_START("evolve-level-06"); // create subgrid list

    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
 
      /* Allocate the subgrid fluxes for this grid. */
 
      SubgridFluxesEstimate[grid1] = new fluxes *[NumberOfSubgrids[grid1]];
 
      for (subgrid = 0; subgrid < NumberOfSubgrids[grid1]; subgrid++)
	SubgridFluxesEstimate[grid1][subgrid] = NULL;
 
      /* Collect the flux data and store it in the newly minted fluxes.
	 Or rather that's what we should do.  Instead, we create fluxes one
	 by one in this awkward array of pointers to pointers.  This should be
	 changed so that all the routines take arrays of flux rather than
	 arrays of pointers to flux.  Dumb. */
 
      counter = 0;

      // Only allocate fluxes for local grids: saves a *lot* of storage

      if (MyProcessorNumber ==
          Grids[grid1]->GridData->ReturnProcessorNumber()) {
 
	NextGrid = Grids[grid1]->NextGridNextLevel;
	while (NextGrid != NULL) {
	  SubgridFluxesEstimate[grid1][counter] = new fluxes;
	  Grids[grid1]->GridData->ComputeRefinementFactors
	                              (NextGrid->GridData, RefinementFactors);
	  NextGrid->GridData->ReturnFluxDims
             (*(SubgridFluxesEstimate[grid1][counter++]), RefinementFactors);
	  NextGrid = NextGrid->NextGridThisLevel;
	}
 
	/* Add the external boundary of this subgrid to the subgrid list. This
	   makes it easy to keep adding up the fluxes of this grid, but we must
	   keep in mind that the last subgrid should be ignored elsewhere. */
 
	SubgridFluxesEstimate[grid1][counter] = new fluxes;
	Grids[grid1]->GridData->ComputeRefinementFactors
                                   (Grids[grid1]->GridData, RefinementFactors);
	Grids[grid1]->GridData->ReturnFluxDims
               (*(SubgridFluxesEstimate[grid1][counter]), RefinementFactors);

      }
 
    } // end loop over grids (create Subgrid list)
 
    JBPERF_STOP("evolve-level-06"); // create subgrid list
    TIME_MSG("After subgrid fluxes");


    /* ------------------------------------------------------- */
    /* Prepare the density field (including particle density). */
 
//  fprintf(stderr, "%"ISYM": EvolveLevel: Enter PrepareDensityField\n", MyProcessorNumber);
 
    JBPERF_START("evolve-level-07"); // PrepareDensityField()

    When = 0.5;
 
#ifdef FAST_SIB
    if (SelfGravity)
      if (PrepareDensityField(LevelArray, SiblingList,
			      level, MetaData, When) == FAIL) {
	fprintf(stderr, "Error in PrepareDensityField.\n");
	return FAIL;
      }
#else   // !FAST_SIB
    if (SelfGravity)
      if (PrepareDensityField(LevelArray, level, MetaData, When) == FAIL) {
        fprintf(stderr, "Error in PrepareDensityField.\n");
        return FAIL;
      }
#endif  // end FAST_SIB
 
 
//  fprintf(stderr, "%"ISYM": EvolveLevel: Exit PrepareDensityField\n", MyProcessorNumber);
 
    /* Prepare normalization for random forcing. Involves top grid only. */
 
    if (RandomForcing && MetaData->CycleNumber > 0 && level == 0)
      if ( ComputeRandomForcingNormalization(LevelArray, 0, MetaData,
                                             &norm, &TopGridTimeStep)
           == FAIL ) {
        fprintf(stderr, "Error in ComputeRandomForcingNormalization.\n");
        return FAIL;
      }
 
    JBPERF_STOP("evolve-level-07"); // PrepareDensityField()

    /* ------------------------------------------------------- */
    /* Evolve all grids by timestep dtThisLevel. */
 
    TIME_MSG("EvolveLevel: before main loop");
    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
 
      /* Call analysis routines. */
 
      JBPERF_START_LOW("evolve-level-08"); // Call analysis routines

//      if (ProblemType == 24)
//	Grids[grid1]->GridData->SphericalInfallGetProfile(level, 1);
//      if (ProblemType == 30)
//	Grids[grid1]->GridData->AnalyzeTrackPeaks(level, 0);
//      if (ProblemType == 27)
//	if (Grids[grid1]->GridData->ReturnProcessorNumber()==MyProcessorNumber){
//	  float AM[3], MeanVelocity[3], DMVelocity[3];
//	  FLOAT Center[] = {0,0,0}, CenterOfMass[3], DMCofM[3];
//	  Grids[grid1]->GridData->CalculateAngularMomentum(Center, AM,
//			   MeanVelocity, DMVelocity, CenterOfMass, DMCofM);
//	  fprintf(stdout, "level = %"ISYM" %"ISYM" %"ISYM"  Vel %"FSYM" %"FSYM" %"FSYM"  DMVel %"FSYM" %"FSYM" %"FSYM"  CofM %"PSYM" %"PSYM" %"PSYM"  DMCofM %"FSYM" %"FSYM" %"FSYM"\n",
//		level, LevelCycleCount[level], grid1, MeanVelocity[0],
//		MeanVelocity[1], MeanVelocity[2],
//		DMVelocity[0], DMVelocity[1], DMVelocity[2],
//		-CenterOfMass[0], -CenterOfMass[1], -CenterOfMass[2],
//		DMCofM[0], DMCofM[1], DMCofM[2]);
//	}
 
      JBPERF_STOP_LOW("evolve-level-08"); // Call analysis routines

      /* Gravity: compute acceleration field for grid and particles. */
 
      JBPERF_START("evolve-level-09"); // Compute self-gravity acceleration


      if (SelfGravity) {
	int Dummy;
	if (level <= MaximumGravityRefinementLevel) {
 
	  /* Compute the potential. */
 
	  if (level > 0)
	    if (Grids[grid1]->GridData->SolveForPotential(Dummy, level)
		== FAIL) {
	      fprintf(stderr, "Error in grid->SolveForPotential.\n");
	      return FAIL;
	    }
	  if (Grids[grid1]->GridData->ComputeAccelerations(level) == FAIL) {
	    fprintf(stderr, "Error in grid->ComputeAccelerations.\n");
	    return FAIL;
	  }
	}
	  /* otherwise, interpolate potential from coarser grid, which is
	     now done in PrepareDensity. */
 
      } // end: if (SelfGravity)
 
      JBPERF_STOP("evolve-level-09"); // Compute self-gravity acceleration


      /* Gravity: compute field due to preset sources. */
 
      JBPERF_START_LOW("evolve-level-10"); // ComputeAccelerationFieldExternal()

      if (UniformGravity || PointSourceGravity)
	if (Grids[grid1]->GridData->ComputeAccelerationFieldExternal() ==FAIL) {
	  fprintf(stderr,"Error in grid->ComputeAccelerationFieldExternal.\n");
	  return FAIL;
	}
 
      JBPERF_STOP_LOW("evolve-level-10"); // ComputeAccelerationFieldExternal()

      /* Radiation Pressure: add to acceleration field */

#ifdef TRANSFER
      if (RadiativeTransfer && RadiationPressure)
	if (Grids[grid1]->GridData->AddRadiationPressureAcceleration() == FAIL) {
	  fprintf(stderr,"Error in grid->AddRadiationPressureAcceleration.\n");
	  return FAIL;
	}
#endif /* TRANSFER */

      /* Check for energy conservation. */
/*
      if (ComputePotential)
	if (CheckEnergyConservation(Grids, grid, NumberOfGrids, level,
				    dtThisLevel) == FAIL) {
	  fprintf(stderr, "Error in CheckEnergyConservation.\n");
	  return FAIL;
	}
*/
#ifdef SAB
    } // End of loop over grids

    //This ensures that all subgrids agree in the boundary.
    //Not a big deal for hydro, but essential for DivB = 0 in MHD runs.
    //Only called on level > 0 because the root grid is dealt with differently than SG's.


    if ( (SelfGravity || UniformGravity || PointSourceGravity) && level > 0) {
#ifdef FAST_SIB
      if( SetAccelerationBoundary(Grids, NumberOfGrids,
				  SiblingList,
				  level, MetaData,
				  Exterior, LevelArray[level], LevelCycleCount[level]) == FAIL ) {
	fprintf(stderr,"Error with AccelerationBoundary.\n");
	return FAIL;
      }
#else
      if( SetAccelerationBoundary(Grids, NumberOfGrids,
				  level, MetaData,
				  Exterior, LevelArray[level], LevelCycleCount[level]) == FAIL ) {
	fprintf(stderr,"Error with AccelerationBoundary.\n");
	return FAIL;
      }
#endif
    }


    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
#endif //SAB.
      /* Copy current fields (with their boundaries) to the old fields
	  in preparation for the new step. */
 
      JBPERF_START("evolve-level-11"); // CopyBaryonFieldToOldBaryonField()

	if (Grids[grid1]->GridData->CopyBaryonFieldToOldBaryonField() == FAIL) {
	  fprintf(stderr, "Error in grid->CopyBaryonFieldToOldBaryonField.\n");
	  return FAIL;
	}
 
      JBPERF_STOP("evolve-level-11"); // CopyBaryonFieldToOldBaryonField()

      /* Add RandomForcing fields to velocities after the copying of current
         fields to old. I also update the total energy accordingly here.
         It makes no sense to force on the very first time step. */
 
      JBPERF_START_LOW("evolve-level-12"); // AddRandomForcing()

      if (RandomForcing && MetaData->CycleNumber > 0) //AK
        if(Grids[grid1]->GridData->AddRandomForcing(&norm,
                                                   TopGridTimeStep) == FAIL)
          fprintf(stderr, "Error in AddRandomForcing.\n");
 
      JBPERF_STOP_LOW("evolve-level-12"); // AddRandomForcing()

      /* Call hydro solver and save fluxes around subgrids. */
 
      JBPERF_START("evolve-level-13"); // SolveHydroEquations()

//      fprintf(stderr, "%"ISYM": Calling Hydro\n", MyProcessorNumber);
 
      if (Grids[grid1]->GridData->SolveHydroEquations(LevelCycleCount[level],
	 NumberOfSubgrids[grid1], SubgridFluxesEstimate[grid1], level) == FAIL) {
	fprintf(stderr, "Error in grid->SolveHydroEquations.\n");
	return FAIL;
      }
 
      JBPERF_STOP("evolve-level-13"); // SolveHydroEquations()

//      fprintf(stderr, "%"ISYM": Called Hydro\n", MyProcessorNumber);
 
      /* Solve the radiative transfer */
	
#ifdef TRANSFER
      while ((dtPhoton > 0.) && RadiativeTransfer &&
	     (Grids[grid1]->GridData->ReturnTime() >= PhotonTime))  {
	if (debug) 
	  printf("EvolvePhotons[%"ISYM"]: dt = %"GSYM", Time = %"FSYM", ", 
		 level, dtPhoton, PhotonTime);
	if (EvolvePhotons(MetaData, LevelArray, AllStars) == FAIL) {
	  fprintf(stderr, "Error in EvolvePhotons.\n");
	  return FAIL;
	}
      } /* ENDWHILE evolve photon */
#endif /* TRANSFER */

      /* Solve the cooling and species rate equations. */
 
//      fprintf(stderr, "%"ISYM": Calling SolveCoolAndRateEquations\n", MyProcessorNumber);

      if (MultiSpecies && RadiativeCooling) {
 
	JBPERF_START("evolve-level-14"); // change this?

	if (Grids[grid1]->GridData->SolveRateAndCoolEquations() == FAIL) {
	  fprintf(stderr, "Error in grid->SolveRateEquations.\n");
	  return FAIL;
	}
 
	JBPERF_STOP("evolve-level-14"); // change this?

//      fprintf(stderr, "%"ISYM": Called SolveCoolAndRateEquations\n", MyProcessorNumber);

      } else {

//      fprintf(stderr, "%"ISYM": Calling MultiSpecies\n", MyProcessorNumber);
 
	JBPERF_START("evolve-level-14"); // SolveRateEquations()

	if (MultiSpecies)
	  if (Grids[grid1]->GridData->SolveRateEquations() == FAIL) {
	    fprintf(stderr, "Error in grid->SolveRateEquations.\n");
	    return FAIL;
	  }
 
	JBPERF_STOP("evolve-level-14"); // SolveRateEquations()

//      fprintf(stderr, "%"ISYM": Called MultiSpecies\n", MyProcessorNumber);
 
	/* Include radiative cooling/heating. */
 
//      fprintf(stderr, "%"ISYM": Calling RadiativeCooling\n", MyProcessorNumber);
 
	JBPERF_START("evolve-level-15"); // SolveRadiativeCooling()

	if (RadiativeCooling)
	  if (Grids[grid1]->GridData->SolveRadiativeCooling() == FAIL) {
	    fprintf(stderr, "Error in grid->SolveRadiativeCooling.\n");
	    return FAIL;
	  }
 
	JBPERF_STOP("evolve-level-15"); // SolveRadiativeCooling()

//      fprintf(stderr, "%"ISYM": Called RadiativeCooling\n", MyProcessorNumber);

      }

      /* Update particle positions (if present). */
 
//      fprintf(stderr, "%"ISYM": Calling UpdatePP\n", MyProcessorNumber);
 
      JBPERF_START("evolve-level-16"); // UpdateParticlePositions()

      if (UpdateParticlePositions(Grids[grid1]->GridData) == FAIL) {
	fprintf(stderr, "Error in UpdateParticlePositions.\n");
	return FAIL;
      }
 
      JBPERF_STOP("evolve-level-16"); // UpdateParticlePositions()

//      fprintf(stderr, "%"ISYM": Called UpdatePP\n", MyProcessorNumber);
 
      /* Include 'star' particle creation and feedback.
         (first, set the under_subgrid field). */
 
      JBPERF_START_LOW("evolve-level-17"); // star particle creation/feedback

      if (StarParticleCreation || StarParticleFeedback) {
	Grids[grid1]->GridData->ZeroSolutionUnderSubgrid(NULL,
						 ZERO_UNDER_SUBGRID_FIELD);
	LevelHierarchyEntry *Temp2 = LevelArray[level+1];
	while (Temp2 != NULL) {
	  Grids[grid1]->GridData->ZeroSolutionUnderSubgrid(Temp2->GridData,
					 ZERO_UNDER_SUBGRID_FIELD);
	  Temp2 = Temp2->NextGridThisLevel;
	}
      }

      if (StarParticleCreation || StarParticleFeedback) {
	if (Grids[grid1]->GridData->StarParticleHandler(level) == FAIL) {
	  fprintf(stderr, "Error in grid->StarParticleWrapper");
	  return FAIL;
	}
      }
 
      JBPERF_STOP_LOW("evolve-level-17"); // star particle creation/feedback

      /* Gravity: clean up AccelerationField. */

      JBPERF_START_LOW("evolve-level-18"); // clean up AccelerationField

      if (SelfGravity || UniformGravity || PointSourceGravity) {
	if (level != MaximumGravityRefinementLevel ||
	    MaximumGravityRefinementLevel == MaximumRefinementLevel)
	  Grids[grid1]->GridData->DeleteAccelerationField();
	Grids[grid1]->GridData->DeleteParticleAcceleration();
      }
 
      JBPERF_STOP_LOW("evolve-level-18"); // clean up AccelerationField

      /* Update current problem time of this subgrid. */
 
      JBPERF_START_LOW("evolve-level-19"); // SetTimeNextTimestep()

      Grids[grid1]->GridData->SetTimeNextTimestep();
 
      JBPERF_STOP_LOW("evolve-level-19"); // SetTimeNextTimestep()

      /* If using comoving co-ordinates, do the expansion terms now. */
 
      JBPERF_START("evolve-level-20"); // ComovingExpansionTerms()

      if (ComovingCoordinates)
	Grids[grid1]->GridData->ComovingExpansionTerms();
 
      JBPERF_STOP("evolve-level-20"); // ComovingExpansionTerms()

    }  // end loop over grids
 
    /* For each grid: a) interpolate boundaries from the parent grid.
                      b) copy any overlapping zones from siblings. */
 
    JBPERF_START("evolve-level-21"); // SetBoundaryConditions()
    TIME_MSG("EvolveLevel: after main loop");

#ifdef FAST_SIB
    if (SetBoundaryConditions(Grids, NumberOfGrids, SiblingList,
			      level, MetaData, Exterior, LevelArray[level]) == FAIL)
      return FAIL;
#else
    if (SetBoundaryConditions(Grids, NumberOfGrids, level, MetaData,
                              Exterior, LevelArray[level]) == FAIL)
      return FAIL;
#endif

    JBPERF_STOP("evolve-level-21"); // SetBoundaryConditions()
    TIME_MSG("after SetBoundaryConditions");

    /* Finalize (accretion, feedback, etc.) star particles */
 
    JBPERF_START("evolve-level-22"); // StarParticleFinalize()

    if (StarParticleFinalize(Grids, MetaData, NumberOfGrids, LevelArray,
			     level, AllStars) == FAIL) {
      fprintf(stderr, "Error in StarParticleFinalize.\n");
      return FAIL;
    }

    JBPERF_STOP("evolve-level-22"); // StarParticleFinalize()
    /* If cosmology, then compute grav. potential for output if needed. */
 
    JBPERF_START("evolve-level-25"); // PrepareDensityField()

    if (ComovingCoordinates && SelfGravity && WritePotential) {
      CopyGravPotential = TRUE;
      When = 0.0;
 
#ifdef FAST_SIB
      if (PrepareDensityField(LevelArray, SiblingList, level, MetaData, When) == FAIL) {
        fprintf(stderr, "Error in PrepareDensityField.\n");
        return FAIL;
      }
#else   // !FAST_SIB
      if (PrepareDensityField(LevelArray, level, MetaData, When) == FAIL) {
        fprintf(stderr, "Error in PrepareDensityField.\n");
        return FAIL;
      }
#endif  // end FAST_SIB
 
      CopyGravPotential = FALSE;
 
      for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
        int Dummy;
        if (level <= MaximumGravityRefinementLevel) {
 
          /* Compute the potential. */
 
          if (level > 0)
            if (Grids[grid1]->GridData->SolveForPotential(Dummy, level)
                == FAIL) {
              fprintf(stderr, "Error in grid->SolveForPotential.\n");
              return FAIL;
            }
          // fprintf(stderr, "Call CP from EvolveLevel\n");
          Grids[grid1]->GridData->CopyPotentialToBaryonField();
        }
        /* otherwise output empty potential field. */
 
      } //  end loop over grids
    } // if WritePotential
 
    JBPERF_STOP("evolve-level-25"); // PrepareDensityField()


    /* For each grid, delete the GravitatingMassFieldParticles. */
 
    JBPERF_START("evolve-level-27"); // DeleteGravitatingMassFieldParticles()

    for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
      Grids[grid1]->GridData->DeleteGravitatingMassFieldParticles();
 
    JBPERF_STOP("evolve-level-27"); // DeleteGravitatingMassFieldParticles()

    /* ----------------------------------------- */
    /* Evolve the next level down (recursively). */
 
    MetaData->FirstTimestepAfterRestart = FALSE;
    if (dbx) fprintf(stderr, "EL Level %"ISYM" going to Level %"ISYM"\n", level, level+1);
    if (LevelArray[level+1] != NULL) {
      if (EvolveLevel(MetaData, LevelArray, level+1, dtThisLevel, Exterior) == FAIL) {
	fprintf(stderr, "Error in EvolveLevel (%"ISYM").\n", level);
	return FAIL;
      }
    }

#if defined(USE_JBPERF) && defined(JB_PERF_LEVELS)
    jbPerf.attribute ("level",&jb_level,JB_INT);
#endif


    OutputFromEvolveLevel(LevelArray,MetaData,level,Exterior);
    /* Update SubcycleNumber if this is the bottom of the hierarchy --
       Note that this not unique based on which level is the highest,
       it just keeps going */

    if (LevelArray[level+1] == NULL) MetaData->SubcycleNumber += 1;  


    if (dbx) fprintf(stderr, "EL Level %"ISYM" returns from Level %"ISYM"\n", level, level+1);

    /* ------------------------------------------------------- */
    /* For each grid,
     * (a) project the subgrid's solution into this grid (step #18)
     * (b) correct for the difference between this grid's fluxes and the
     *     subgrid's fluxes. (step #19)
     */
 
    JBPERF_START("evolve-level-28"); // UpdateFromFinerGrids()
    TIME_MSG("Before update from finer grids");

#ifdef FLUX_FIX

    SUBlingList = new LevelHierarchyEntry*[NumberOfGrids];
    for(int list=0; list < NumberOfGrids; list++)
      SUBlingList[list] = NULL;

 
    if (FluxCorrection) {

      /* Fill in the SUBling list */

      if (dbx) fprintf(stderr, "EL: CSL entry \n");
      if (CreateSUBlingList(MetaData, Grids,
                              NumberOfGrids, &SUBlingList) == FAIL) {
        fprintf(stderr, "Error in CreateSUBlingList.\n");
        return FAIL;
      }
      if (dbx) fprintf(stderr, "EL: CSL exit \n");
    }

/* 
    LevelHierarchyEntry *NextMonkey;
 
    for(grid1 = 0; grid1 < NumberOfGrids; grid1++){
      NextMonkey = SUBlingList[grid1];
      while (NextMonkey != NULL) {
        // fprintf(stderr, "SGcheckEL%"ISYM": SUBling[%"ISYM"]->Grid pointer %p\n",
        //         MyProcessorNumber, grid1, NextMonkey->GridData);
        NextMonkey=NextMonkey->NextGridThisLevel;
      }
    }
*/

#endif

#ifdef FLUX_FIX
    if (UpdateFromFinerGrids(level, Grids, NumberOfGrids, NumberOfSubgrids,
			     SubgridFluxesEstimate,
			     SUBlingList,
			     MetaData) == FAIL)
      return FAIL;
#else
    if (UpdateFromFinerGrids(level, Grids, NumberOfGrids, NumberOfSubgrids,
			     SubgridFluxesEstimate) == FAIL)
      return FAIL;
#endif

    JBPERF_STOP("evolve-level-28"); // UpdateFromFinerGrids()

    if (dbx) fprintf(stderr, "OK after UpdateFromFinerGrids \n");

#ifdef FLUX_FIX
    if ( FluxCorrection ) {
      /* Clean up SUBlings */
      if (DeleteSUBlingList( NumberOfGrids, SUBlingList ) == FAIL) {
        fprintf(stderr, "Error in DeleteSUBlingList.\n");
        return FAIL;
      }
    }
#endif

    if (dbx) fprintf(stderr, "OK after DeleteSUBlingList \n");
 
    /* ------------------------------------------------------- */
    /* Add the saved fluxes (in the last subsubgrid entry) to the exterior
       fluxes for this subgrid .
       (Note: this must be done after CorrectForRefinedFluxes). */
 
    JBPERF_START("evolve-level-29"); // AddToBoundaryFluxes()
    TIME_MSG("Before saving fluxes");

    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {

      // Only deallocate fluxes for local grids

      if (MyProcessorNumber ==
          Grids[grid1]->GridData->ReturnProcessorNumber()) {
 
      if (FluxCorrection)
	if (Grids[grid1]->GridData->AddToBoundaryFluxes
	    (SubgridFluxesEstimate[grid1][NumberOfSubgrids[grid1] - 1])
	    == FAIL) {
	  fprintf(stderr, "Error in grid->AddToBoundaryFluxes.\n");
	  return FAIL;
	}
 
      /* Delete fluxes pointed to by SubgridFluxesEstimate[subgrid]. */
 
      for (subgrid = 0; subgrid < NumberOfSubgrids[grid1]; subgrid++) {
	DeleteFluxes(SubgridFluxesEstimate[grid1][subgrid]);
	delete       SubgridFluxesEstimate[grid1][subgrid];
      }
      delete [] SubgridFluxesEstimate[grid1];

      }
 
    } // end of loop over grids
 
    JBPERF_STOP("evolve-level-29"); // AddToBoundaryFluxes()

    /* Recompute radiation field, if requested. */
 
    JBPERF_START("evolve-level-30"); // RadiationFieldUpdate()
    TIME_MSG("Done saving fluxes");

    if (RadiationFieldType >= 10 && RadiationFieldType <= 11 &&
	level <= RadiationFieldLevelRecompute)
      if (RadiationFieldUpdate(LevelArray, level, MetaData) == FAIL) {
	fprintf(stderr, "Error in RecomputeRadiationField.\n");
	return FAIL;
      }
 
    JBPERF_STOP("evolve-level-30"); // RadiationFieldUpdate()

    /* Rebuild the Grids on the next level down.
       Don't bother on the last cycle, as we'll rebuild this grid soon. */
 
    JBPERF_START("evolve-level-31"); // RebuildHierarchy()

    if (dtThisLevelSoFar < dtLevelAbove) {
      if (RebuildHierarchy(MetaData, LevelArray, level) == FAIL) {
	fprintf(stderr, "Error in RebuildHierarchy.\n");
	return FAIL;
      }
    }

    /* Count up number of grids on this level. */
 
    int GridMemory, NumberOfCells, CellsTotal, Particles;
    float AxialRatio, GridVolume;
    for (grid1 = 0; grid1 < NumberOfGrids; grid1++) {
      Grids[grid1]->GridData->CollectGridInformation
        (GridMemory, GridVolume, NumberOfCells, AxialRatio, CellsTotal, Particles);
      LevelZoneCycleCount[level] += NumberOfCells;
      if (MyProcessorNumber == Grids[grid1]->GridData->ReturnProcessorNumber())
	LevelZoneCycleCountPerProc[level] += NumberOfCells;
    }
 
    JBPERF_STOP("evolve-level-31"); // RebuildHierarchy()

    cycle++;
    LevelCycleCount[level]++;
 
  } // end of loop over subcycles
 
  if (debug)
    fprintf(stdout, "EvolveLevel[%"ISYM"]: NumberOfSubCycles = %"ISYM" (%"ISYM" total)\n", level,
           cycle, LevelCycleCount[level]);
 
  /* If possible & desired, report on memory usage. */
 
  //  if (debug)
  ReportMemoryUsage("Memory usage report: Evolve Level");
 
#if defined(USE_JBPERF) && defined(JB_PERF_LEVELS)
  jbPerf.attribute ("level",0,JB_NULL);
#endif

  /* Clean up. */
 
#ifdef UNUSED
  if (level > MaximumGravityRefinementLevel &&
      level == MaximumRefinementLevel)
    ZEUSQuadraticArtificialViscosity /= 1;
#endif
 
  delete [] NumberOfSubgrids;
  delete [] Grids;
  delete [] SubgridFluxesEstimate;
 
  /* Clean up the sibling list. */

  if (( StaticLevelZero == 1 && level != 0 ) || StaticLevelZero == 0 ) {
    for (grid1 = 0; grid1 < NumberOfGrids; grid1++)
      delete [] SiblingList[grid1].GridList;
    delete [] SiblingList;
  }

  if (dbx) fprintf(stderr, "Return from EL Level %"ISYM"\n", level);
 
  return SUCCESS;
 
}