Esempio n. 1
0
/*****************************************************************************
  RouteSubSurface()

  Sources: 
  Wigmosta, M. S., L. W. Vail, and D. P. Lettenmaier, A distributed 
      hydrology-vegetation model for complex terrain, Water Resour. Res.,
      30(6), 1665-1679, 1994.

  Quinn, P., K. Beven, P. Chevallier, and O. Planchon, The prediction of 
      hillslope flow paths for distributed hydrological modelling using 
      digital terrain models, Hydrological Processes, 5, 59-79, 1991.

  This routine follows Wigmosta et al. [1994] in calculating the subsurface
  flow.  The local gradient is based on the local hydraulic head, consisting 
  of the height of the pixel surface minus the depth of the water table 
  below the water surface.  This has the disadvantage that the local gradients
  have to be recalculated for each pixel for each timestep.  In Wigmosta et
  al. [1994] the local gradient is taken to be equal to the slope of the land
  surface, which is a reasonable assunption for mountainous areas.  For the 
  flat boreal forest landscape it is probably better to use the slope
  of the water surface.

  Set the gradient with pixels that are outside tha basin to zero.  This 
  ensures that there is no flux of water across the basin boundary.  In the 
  current implementation water can only leave the basin as surface flow.  
  This may not be entirely realistic, and should be analyzed further.  
  One consequence of this could be that the soil in the basin is more 
  saturated than it would be if subsurface flow out of the basin would
  be allowed.

  The surrounding grid cells are numbered in the following way

                |-----| DX

          0-----1-----2  ---
	  |\    |    /|   |
          | \   |   / |   |
          |  \  |  /  |   | DY
          |   \ | /   |   |
          |    \|/    |   |
          7-----*-----3  ---
          |    /|\    |
          |   / | \   |
          |  /  |  \  |
          | /   |   \ |
          |/    |    \|
          6-----5-----4

  For the current implementation it is assumed that the resolution is the 
  same in both the X and the Y direction.  If this is not the case an error
  message is generated and the program exits.  The reason is that the 
  formulation for the flow width in the diagonal direction changes if the
  grid is not square.  The method for defining the flow widths in the case
  of square grids is taken from Quinn et al [1991]

  Update Jan 2004 COD
  When Gradient = WATERTABLE, the watertable was used to route the
  surface water. This was because of the common use of TopoMap.Dir and 
  TopoMap.TotalDir. These are now for surface routing (always) and subsurface 
  routing (when Gradient = TOPOGRAPHY). Subsurface routing directions 
  and FlowGrad (SubDir, SubTotalDir, SubFlowGrad) for Gradient = WATERTABLE 
  are now determined locally here (in RouteSubsurface.c.)

  WORK IN PROGRESS
*****************************************************************************/
void RouteSubSurface(int Dt, MAPSIZE *Map, TOPOPIX **TopoMap,
		     VEGTABLE *VType, VEGPIX **VegMap,
		     ROADSTRUCT **Network, SOILTABLE *SType,
		     SOILPIX **SoilMap, CHANNEL *ChannelData,
		     TIMESTRUCT *Time, OPTIONSTRUCT *Options, 
		     char *DumpPath, SEDPIX **SedMap, FINEPIX ***FineMap,
		     SEDTABLE *SedType, int MaxStreamID, SNOWPIX **SnowMap)
{
  const char *Routine = "RouteSubSurface";
  int x;			/* counter */
  int y;			/* counter */
  int i,j, ii, jj, yy, xx;	/* counters for FineMap initialization */
  float BankHeight;
  float *Adjust;
  float fract_used;
  float depth;
  float OutFlow;
  float water_out_road;
  float Transmissivity;
  float AvailableWater;
  int k;
  float **SubFlowGrad;	        /* Magnitude of subsurface flow gradient
				   slope * width */
  unsigned char ***SubDir;         /* Fraction of flux moving in each direction*/ 
  unsigned int **SubTotalDir;	/* Sum of Dir array */

  /* variables for mass wasting trigger. */
  int count, totalcount;
  float mgrid, sat;
  char buffer[32];
  char satoutfile[100];          /* Character arrays to hold file name. */ 
  FILE *fs;                     /* File pointer. */

  /*****************************************************************************
   Allocate memory 
  ****************************************************************************/
  
  if (!(SubFlowGrad = (float **)calloc(Map->NY, sizeof(float *))))
    ReportError((char *) Routine, 1);
  for(i=0; i<Map->NY; i++) {
    if (!(SubFlowGrad[i] = (float *)calloc(Map->NX, sizeof(float))))
      ReportError((char *) Routine, 1);
  }
  
  if (!((SubDir) = (unsigned char ***) calloc(Map->NY, sizeof(unsigned char **))))
    ReportError((char *) Routine, 1);
  for(i=0; i<Map->NY; i++) {
    if (!((SubDir)[i] = (unsigned char **) calloc(Map->NX, sizeof(unsigned char*))))
	ReportError((char *) Routine, 1);
    for(j=0; j<Map->NX; j++) {
      if (!(SubDir[i][j] = (unsigned char *)calloc(NDIRS, sizeof(unsigned char ))))
    ReportError((char *) Routine, 1);
    }
  }

  if (!(SubTotalDir = (unsigned int **)calloc(Map->NY, sizeof(unsigned int *))))
    ReportError((char *) Routine, 1);
  for(i=0; i<Map->NY; i++) {
    if (!(SubTotalDir[i] = (unsigned int *)calloc(Map->NX, sizeof(unsigned int))))
      ReportError((char *) Routine, 1);
  }
  
  /* reset the saturated subsurface flow to zero */
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
	SoilMap[y][x].SatFlow = 0;
	/* ChannelInt and RoadInt are initialized in Aggregate.c Why are there here? */
	/* 	SoilMap[y][x].ChannelInt = 0; */
	SoilMap[y][x].RoadInt = 0;
      }
    }
  }

  if (Options->FlowGradient == WATERTABLE)
    HeadSlopeAspect(Map, TopoMap, SoilMap, SubFlowGrad, SubDir, SubTotalDir);

  /* next sweep through all the grid cells, calculate the amount of
     flow in each direction, and divide the flow over the surrounding
     pixels */

  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
	
	if (Options->FlowGradient == TOPOGRAPHY){
	  SubTotalDir[y][x] = TopoMap[y][x].TotalDir;
	  SubFlowGrad[y][x] = TopoMap[y][x].FlowGrad;
	  for (k = 0; k < NDIRS; k++) 
	    SubDir[y][x][k] = TopoMap[y][x].Dir[k];
	}

	BankHeight = (Network[y][x].BankHeight > SoilMap[y][x].Depth) ?
	  SoilMap[y][x].Depth : Network[y][x].BankHeight;
	Adjust = Network[y][x].Adjust;
	fract_used = 0.0f;
	water_out_road = 0.0;

	if (!channel_grid_has_channel(ChannelData->stream_map, x, y)) {
	  for (k = 0; k < NDIRS; k++) {
	    fract_used += (float) SubDir[y][x][k];
/* 	    fract_used += (float) TopoMap[y][x].Dir[k]; */
	  }
/* 	  fract_used /= 255.0f; */
/* 	  fract_used /= (float) TopoMap[y][x].TotalDir; */
	  if (SubTotalDir[y][x] > 0)
	    fract_used /= (float) SubTotalDir[y][x];
	  else
	    fract_used = 0.;

	  /* only bother calculating subsurface flow if water table is above bedrock */
	  if (SoilMap[y][x].TableDepth < SoilMap[y][x].Depth) {
	    depth =
	      ((SoilMap[y][x].TableDepth > BankHeight) ?
	       SoilMap[y][x].TableDepth : BankHeight);

	    Transmissivity =
	      CalcTransmissivity(SoilMap[y][x].Depth, depth,
				 SType[SoilMap[y][x].Soil - 1].KsLat,
				 SType[SoilMap[y][x].Soil - 1].KsLatExp,
				 SType[SoilMap[y][x].Soil - 1].DepthThresh);

	    OutFlow =
	      (Transmissivity * fract_used * SubFlowGrad[y][x] * Dt) /
	      (Map->DX * Map->DY);
/* 	      (Transmissivity * fract_used * TopoMap[y][x].FlowGrad * Dt) / */
/* 	      (Map->DX * Map->DY); */

	    /* check whether enough water is available for redistribution */

	    AvailableWater =
	      CalcAvailableWater(VType[VegMap[y][x].Veg - 1].NSoilLayers,
				 SoilMap[y][x].Depth,
				 VType[VegMap[y][x].Veg - 1].RootDepth,
				 SType[SoilMap[y][x].Soil - 1].Porosity,
				 SType[SoilMap[y][x].Soil - 1].FCap,
				 SoilMap[y][x].TableDepth, Adjust);

	    OutFlow = (OutFlow > AvailableWater) ? AvailableWater : OutFlow;
	  }
	  else {
	    depth = SoilMap[y][x].Depth;
	    OutFlow = 0.0f;
	  }

	  /* compute road interception if water table is above road cut */

	  if (SoilMap[y][x].TableDepth < BankHeight &&
	      channel_grid_has_channel(ChannelData->road_map, x, y)) {
/* 	    fract_used = ((float) Network[y][x].fraction / 255.0f); */
/* 	    fract_used = ((float) Network[y][x].fraction / (float)TopoMap[y][x].TotalDir); */
	    if (SubTotalDir[y][x] > 0)
	      fract_used = ((float) Network[y][x].fraction /
			    (float)SubTotalDir[y][x]);
	    else
	      fract_used = 0.;

	    Transmissivity =
	      CalcTransmissivity(BankHeight, SoilMap[y][x].TableDepth,
				 SType[SoilMap[y][x].Soil - 1].KsLat,
				 SType[SoilMap[y][x].Soil - 1].KsLatExp,
				 SType[SoilMap[y][x].Soil - 1].DepthThresh);
	    water_out_road = (Transmissivity * fract_used *
			      SubFlowGrad[y][x] * Dt) / (Map->DX *
							      Map->DY);
/*                               (Transmissivity * fract_used * */
/* 			      TopoMap[y][x].FlowGrad * Dt) / (Map->DX * */
/* 							      Map->DY); */

	    AvailableWater =
	      CalcAvailableWater(VType[VegMap[y][x].Veg - 1].NSoilLayers,
				 BankHeight,
				 VType[VegMap[y][x].Veg - 1].RootDepth,
				 SType[SoilMap[y][x].Soil - 1].Porosity,
				 SType[SoilMap[y][x].Soil - 1].FCap,
				 SoilMap[y][x].TableDepth, Adjust);
	    water_out_road = (water_out_road > AvailableWater) ? AvailableWater
	      : water_out_road;

	    /* increase lateral inflow to road channel */
	    SoilMap[y][x].RoadInt = water_out_road;
	    channel_grid_inc_inflow(ChannelData->road_map, x, y,
				    water_out_road * Map->DX * Map->DY);

	  }

	  /* Subsurface Component - Decrease water change by outwater */

	  SoilMap[y][x].SatFlow -= OutFlow + water_out_road;

	  /* Assign the water to appropriate surrounding pixels */

/* 	  OutFlow /= 255.0f; */
/* 	  OutFlow /= (float) TopoMap[y][x].TotalDir; */
	  if (SubTotalDir[y][x] > 0)
	    OutFlow /= (float) SubTotalDir[y][x];
	  else
	    OutFlow = 0.;

	  for (k = 0; k < NDIRS; k++) {
	    int nx = xdirection[k] + x;
	    int ny = ydirection[k] + y;
	    if (valid_cell(Map, nx, ny)) {
	      SoilMap[ny][nx].SatFlow += OutFlow * SubDir[y][x][k];
/* 	      SoilMap[ny][nx].SatFlow += OutFlow * TopoMap[y][x].Dir[k]; */
	    }
	  }

	}
	else {			/* cell has a stream channel */

	  if (SoilMap[y][x].TableDepth < BankHeight &&
	      channel_grid_has_channel(ChannelData->stream_map, x, y)) {
	    /* float gradient =  */
	    /*   (4.0 * SoilMap[y][x].Depth > 2.0 * MIN_GRAD * Map->DX) ?  */
	    /*   4.0 * SoilMap[y][x].Depth : 2.0 * MIN_GRAD * Map->DX; */

	    float gradient = 4.0 * (BankHeight - SoilMap[y][x].TableDepth);
	    if (gradient < 0.0)
	      gradient = 0.0;

	    Transmissivity =
	      CalcTransmissivity(BankHeight, SoilMap[y][x].TableDepth,
				 SType[SoilMap[y][x].Soil - 1].KsLat,
				 SType[SoilMap[y][x].Soil - 1].KsLatExp,
				 SType[SoilMap[y][x].Soil - 1].DepthThresh);

	    OutFlow = (Transmissivity * gradient * Dt) / (Map->DX * Map->DY);

	    /* check whether enough water is available for redistribution */

	    AvailableWater =
	      CalcAvailableWater(VType[VegMap[y][x].Veg - 1].NSoilLayers,
				 BankHeight,
				 VType[VegMap[y][x].Veg - 1].RootDepth,
				 SType[SoilMap[y][x].Soil - 1].Porosity,
				 SType[SoilMap[y][x].Soil - 1].FCap,
				 SoilMap[y][x].TableDepth, Adjust);

	    OutFlow = (OutFlow > AvailableWater) ? AvailableWater : OutFlow;

	    /* remove water going to channel from the grid cell */
	    SoilMap[y][x].SatFlow -= OutFlow;

	    /* contribute to channel segment lateral inflow */
	    channel_grid_inc_inflow(ChannelData->stream_map, x, y,
				    OutFlow * Map->DX * Map->DY);

	    SoilMap[y][x].ChannelInt += OutFlow;
	  }
	}
      }
    }
  }

 for(i=0; i<Map->NY; i++) { 
    free(SubTotalDir[i]);
    free(SubFlowGrad[i]);
    for(j=0; j<Map->NX; j++){
      free(SubDir[i][j]);
    }
    free(SubDir[i]);
  }
  free(SubDir);
  free(SubTotalDir);
  free(SubFlowGrad);

  /**********************************************************************/
  /* Dump saturation extent file to screen for Mass Wasting dates.
     Saturation extent is based on the number of pixels with a water table 
     that is at least MTHRESH of soil depth. */ 
  
  count =0;
  totalcount = 0;
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
	mgrid = (SoilMap[y][x].Depth - SoilMap[y][x].TableDepth)/SoilMap[y][x].Depth;
	if(mgrid > MTHRESH) count += 1;
	totalcount +=1;
      }
    }
  }
 
  sat = 100.*((float)count/(float)totalcount);
  
  sprintf(satoutfile, "%ssaturation_extent.txt", DumpPath);
  
  if((fs=fopen(satoutfile,"a")) == NULL){
    printf("Cannot open saturation extent output file.\n");
    exit(0);
  }
  
  SPrintDate(&(Time->Current), buffer);
  fprintf(fs, "%-20s %.4f \n", buffer, sat); 
  fclose(fs);    
  
  /* Initialize the mass wasting variables for all time steps
     to maintain the mass balance */
  if(Options->Sediment){
    for (y = 0; y < Map->NY; y++) {
      for (x = 0; x < Map->NX; x++) {
	if (INBASIN(TopoMap[y][x].Mask)) {
	  for(ii=0; ii< Map->DY/Map->DMASS; ii++) { /* Fine resolution counters. */
	    for(jj=0; jj< Map->DX/Map->DMASS; jj++) {
	      yy = (int) y*Map->DY/Map->DMASS + ii;
	      xx = (int) x*Map->DX/Map->DMASS + jj;
	      (*FineMap[yy][xx]).Probability = 0.;
	      (*FineMap[yy][xx]).MassWasting = 0.;
	      (*FineMap[yy][xx]).MassDeposition = 0.;
	      (*FineMap[yy][xx]).SedimentToChannel = 0.;
	    }
	  }
	}
      }
    }
    
    /* Call the mass wasting algorithm */
    if(Options->MassWaste){
      if(Time->NMWMTotalSteps > 0){
	if(Time->Current.Julian == Time->MWMnext.Julian){   
	  MainMWM(SedMap, FineMap, VType, SedType, ChannelData, DumpPath, SoilMap,
		  Time, Map, TopoMap, SType, VegMap, MaxStreamID, SnowMap);
	  
	  /* catch the next date */
	  for (i = 0; i < Time->NMWMTotalSteps; i++){
	    if(Time->MWMnext.Julian < Time->MWM[i].Julian){
	      Time->MWMnext = Time->MWM[i];
	      break;
	    }
	  }
	}
      }
      else{ /* Time->NMWMTotalSteps == 0 run the old way*/
	if((float)count/((float)totalcount) > SATPERCENT) {
	  MainMWM(SedMap, FineMap, VType, SedType, ChannelData, DumpPath, SoilMap,
		  Time, Map, TopoMap, SType, VegMap, MaxStreamID, SnowMap);
	}
      }
    }
  }
  
  /**********************************************************************/
  /* End added code. */
  
}
Esempio n. 2
0
/* -------------------------------------------------------------
   RouteChannel
   ------------------------------------------------------------- */
void
RouteChannel(CHANNEL * ChannelData, TIMESTRUCT * Time, MAPSIZE * Map,
	    TOPOPIX ** TopoMap, SOILPIX ** SoilMap, AGGREGATED * Total, 
	     OPTIONSTRUCT *Options, ROADSTRUCT ** Network, 
	     SOILTABLE * SType, PRECIPPIX ** PrecipMap, SEDPIX **SedMap,
	     float Tair, float Rh, float *SedDiams)
{
  int x, y;
  int flag;
  char buffer[32];
  float CulvertFlow;


  /* give any surface water to roads w/o sinks */
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {
	SoilMap[y][x].IExcessSed = SoilMap[y][x].IExcess;
	if (channel_grid_has_channel(ChannelData->road_map, x, y) && !channel_grid_has_sink(ChannelData->road_map, x, y)) {	/* road w/o sink */


	  SoilMap[y][x].RoadInt += SoilMap[y][x].IExcess;
	  channel_grid_inc_inflow(ChannelData->road_map, x, y,
				  SoilMap[y][x].IExcess * Map->DX * Map->DY);
	  SoilMap[y][x].IExcess = 0.0f;
	  
	}
      }
    }
  }
  
  if(Options->RoadRouting){
    RouteRoad(Map, Time, TopoMap, SoilMap, Network, SType, ChannelData, 
	      PrecipMap, SedMap, Tair, Rh, SedDiams);  
  }

  /* route the road network and save results */
  SPrintDate(&(Time->Current), buffer);
  flag = IsEqualTime(&(Time->Current), &(Time->Start));
  if (ChannelData->roads != NULL) {
    channel_route_network(ChannelData->roads, Time->Dt);
    channel_save_outflow_text(buffer, ChannelData->roads,
			      ChannelData->roadout, ChannelData->roadflowout,
			      flag);
  }
  
  /* add culvert outflow to surface water */
  Total->CulvertReturnFlow = 0.0;
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (INBASIN(TopoMap[y][x].Mask)) {

	CulvertFlow = ChannelCulvertFlow(y, x, ChannelData);
	CulvertFlow /= Map->DX * Map->DY;
	/* CulvertFlow = (CulvertFlow > 0.0) ? CulvertFlow : 0.0; */
	
	if (channel_grid_has_channel(ChannelData->stream_map, x, y)) {
	  channel_grid_inc_inflow(ChannelData->stream_map, x, y,
				  (SoilMap[y][x].IExcess + 
				   CulvertFlow) * Map->DX * Map->DY);
	  SoilMap[y][x].ChannelInt += SoilMap[y][x].IExcess;
	  
	  Total->CulvertToChannel += CulvertFlow;
	  Total->RunoffToChannel += SoilMap[y][x].IExcess;
	  
	  SoilMap[y][x].IExcess = 0.0f;

	}
	else {
	  SoilMap[y][x].IExcess += CulvertFlow;
	  Total->CulvertReturnFlow += CulvertFlow;
	  
	}
      }
    }
  }
  /* route stream channels */
  if (ChannelData->streams != NULL) {
    channel_route_network(ChannelData->streams, Time->Dt);
    channel_save_outflow_text(buffer, ChannelData->streams,
			      ChannelData->streamout,
			      ChannelData->streamflowout, flag);
	/* save parameters for John's RBM model */
	if (Options->StreamTemp)
	  channel_save_outflow_text_cplmt(Time, buffer,ChannelData->streams,ChannelData, flag);
  }
  
}
Esempio n. 3
0
/*****************************************************************************
  Function name: MassEnergyBalance()

  Purpose      : Calculate mass and energy balance

  Required     :

  Returns      : void

  Modifies     :

  Comments     :

  Reference    :
    Epema, G.F. and H.T. Riezbos, 1983, Fall Velocity of waterdrops at different
heights as a factor influencing erosivity of simulated rain. Rainfall simulation,
Runoff and Soil Erosion. Catena suppl. 4, Braunschweig. Jan de Ploey (Ed), 1-17.

  Laws, J.o., and D.A. Parsons, 1943, the relation of raindrop size to intensity.
Trans. Am. Geophys. Union, 24: 452-460.

  Wicks, J.M. and J.C. Bathurst, 1996, SHESED: a physically based, distributed
erosion and sediment yield component for the SHE hydrological modeling system,
Journal of Hydrology, 175, 213-238.

*****************************************************************************/
void MassEnergyBalance(OPTIONSTRUCT *Options, int y, int x, float SineSolarAltitude,
		       float DX, float DY, int Dt, int HeatFluxOption,
		       int CanopyRadAttOption, int RoadRouteOption,
		       int InfiltOption, int MaxVegLayers, PIXMET *LocalMet,
		       ROADSTRUCT *LocalNetwork, PRECIPPIX *LocalPrecip,
		       VEGTABLE *VType, VEGPIX *LocalVeg, SOILTABLE *SType,
		       SOILPIX *LocalSoil, SNOWPIX *LocalSnow,
		       EVAPPIX *LocalEvap, PIXRAD *TotalRad,
		       CHANNEL *ChannelData, float **skyview)
{
  PIXRAD LocalRad;			/* Radiation balance components (W/m^2) */
  float SurfaceWater;		/* Pixel average depth of water before infiltration is calculated (m) */

  float RoadWater;          /* Average depth of water on the road surface
							   (normalized by grid cell area)
							   before infiltration is calculated (m) */
  float ChannelWater;       /* Precip that hits the channel */
  float Infiltration;		/* Infiltration into the top soil layer (m) */
  float Infiltrability;     /* Dynamic infiltration capacity (m/s)*/
  float B;                  /* Capillary drive and soil saturation deficit used
							   in dynamic infiltration calculation*/
  float LowerRa;		    /* Aerodynamic resistance for lower layer (s/m) */

  float LowerWind;			/* Wind for lower layer (m/s) */
  float MaxInfiltration;	/* Maximum infiltration into the top soil layer (m) */

  float MaxRoadbedInfiltration;	/* Maximum infiltration through the road bed soil layer (m) */

  float MeltEnergy;			/* Energy used to melt snow and  change of cold content of snow pack */

  float MoistureFlux;		/* Amount of water transported from the pixel
							   to the atmosphere (m/timestep) */
  float NetRadiation;		/* Total Net long- and shortwave radiation for each veg layer (W/m2) */
  float PercArea;           /* Surface area of percolation corrected for
							   channel and road area, divided by the grid cell area (0-1)  */

  float Reference;			/* Reference height for sensible heat calculation (m) */

  float RoadbedInfiltration;/* Infiltration through the road bed (m) */
  float Roughness;			/* Roughness length (m) */
  float Rp;					/* radiation flux in visible part of the spectrum (W/m^2) */

  float UpperRa;		    /* Aerodynamic resistance for upper layer (s/m) */

  float UpperWind;			/* Wind for upper layer (m/s) */
  float SnowLongIn;			/* Incoming longwave radiation at snow surface (W/m2) */



  float SnowNetShort;		/* Net amount of short wave radiation at the snow surface (W/m2) */
  float SnowRa;				/* Aerodynamic resistance for snow */
  float SnowWind;		    /* Wind 2 m above snow */
  float Tsurf;				/* Surface temperature used in LongwaveBalance() (C) */
  float RainfallIntensity;  /* Rainfall intensity (mm/h) */
  float MS_Rainfall;        /* Momentum squared for rain throughfall((kg* m/s)^2 /(m^2 * s)) */
  int MS_Index;             /* Index for determining alpha and beta cooresponding to RainfallIntensity*/
  int   NVegLActual;		/* Number of vegetation layers above snow */
  float alpha[4]={2.69e-8,3.75e-8,6.12e-8,11.75e-8}; /* empirical coefficient
				for rainfall momentum after Wicks and Bathurst (1996) */
  float beta[4]={1.6896,1.5545,1.4242,1.2821};       /* empirical coefficient
				for rainfall momentum after Wicks and Bathurst (1996) */
  int i;
  float CanopyHeight[18] = {0.5,1,1.5,2,3,4,5,6,7,8,9,10,11,12,
			    13,14,15,16};        /* Canopy height at which drip fall
			          velocity is prescribed after Epema and Riezebos (1983) (m)*/
  float FallVelocity[18] = {2.96,4.12,5.12,5.82,6.84,7.54,8.05,8.36,
			    8.54,8.66,8.75,8.82,8.87,8.91,8.96,9.02,9.07,9.13};
                                     /* Drip fall velocity corresponding to
                                     CanopyHeight after Epema and Riezebos (1983) (m/s)*/
  float LD_FallVelocity;             /* Leaf drip fall velocity corresponding to the
                                     canopy height in vegetation map (m/s) */

  /* Calculate the number of vegetation layers above the snow */

  NVegLActual = VType->NVegLayers;
  if (LocalSnow->HasSnow == TRUE && VType->UnderStory == TRUE)
    --NVegLActual;

  /* initialize the total amount of evapotranspiration, and MeltEnergy */

  LocalEvap->ETot = 0.0;
  MeltEnergy = 0.0;
  MoistureFlux = 0.0;

  /* calculate the radiation balance for the ground/snow surface and the
     vegetation layers above that surface */
  /* related files: settings.h data.h Calendar.h  DHSVMerror.h massenergy.h constants.h
  */
//  RadiationBalance(Options, HeatFluxOption, CanopyRadAttOption, SineSolarAltitude,
//	       LocalMet->VICSin, LocalMet->Sin, LocalMet->SinBeam, LocalMet->SinDiffuse,
//		   LocalMet->Lin, LocalMet->Tair, LocalVeg->Tcanopy,
//		   LocalSoil->TSurf, SType->Albedo, VType, LocalSnow, &LocalRad);
	CRadiationBalance * crb = new CRadiationBalance;
	crb->init(Options, HeatFluxOption, CanopyRadAttOption, SineSolarAltitude,
	       LocalMet->VICSin, LocalMet->Sin, LocalMet->SinBeam, LocalMet->SinDiffuse,
		   LocalMet->Lin, LocalMet->Tair, LocalVeg->Tcanopy,
		   LocalSoil->TSurf, SType->Albedo, VType, LocalSnow, &LocalRad);
    crb->execute();
    delete crb;

  /* calculate the actual aerodynamic resistances and wind speeds */
  UpperWind = VType->U[0] * LocalMet->Wind;
  UpperRa = VType->Ra[0] / LocalMet->Wind;
  if (VType->OverStory == TRUE) {
    LowerWind = VType->U[1] * LocalMet->Wind;
    LowerRa = VType->Ra[1] / LocalMet->Wind;
  }
  else {
    LowerWind = UpperWind;
    LowerRa = UpperRa;
  }

  /* Leaf drip impact*/
  /* Find corresponding fall velocity for overstory and understory heights
     by weighting scheme */
  /* related files: independent module
  */
//  if (VType->OverStory){
//    /* staring at 1 assumes the overstory height > 0.5 m */
//    for (i = 1; i <= 17; i++ ) {
//      if (VType->Height[0] < CanopyHeight[i]) {
//        LD_FallVelocity = ((VType->Height[0] - CanopyHeight[i-1])
//			   *FallVelocity[i] +
//			   (CanopyHeight[i] - VType->Height[0])*FallVelocity[i-1]) /
//	  (CanopyHeight[i] - CanopyHeight[i-1]);
//      }
//    }
//    if (VType->UnderStory) {
//      /* ending at 16 assumes the understory height < 16 m */
//      for (i = 0; i <= 16; i++) {
//	if (VType->Height[1] < CanopyHeight[i]) {
//	  LD_FallVelocity = ((VType->Height[1] - CanopyHeight[i])*FallVelocity[i] +
//			     (CanopyHeight[i+1] - VType->Height[1])*FallVelocity[i-1]) /
//	    (CanopyHeight[i+1] - CanopyHeight[i]);
//	}
//      }
//    }
//  }
//  else if (VType->UnderStory) {
//    /* ending at 16 assumes the understory height < 16 m */
//    for (i = 0; i <= 16; i++) {
//      if (VType->Height[0] < CanopyHeight[i]) {
//	LD_FallVelocity = ((VType->Height[0] - CanopyHeight[i])*FallVelocity[i] +
//			   (CanopyHeight[i+1] - VType->Height[0])*FallVelocity[i-1]) /
//	  (CanopyHeight[i+1] - CanopyHeight[i]);
//      }
//    }
//  }
//  else LD_FallVelocity = 0;

    CLeafDripImpact * cLeafDripImpact = new CLeafDripImpact();
    cLeafDripImpact->init(VType, CanopyHeight, FallVelocity);
    cLeafDripImpact->execute();
    cLeafDripImpact->query(&LD_FallVelocity);
    delete cLeafDripImpact;


  /* RainFall impact */
  /* 3600 is conversion factor (number of seconds per hour) */
  /* related files: independant
  */
//  if (LocalPrecip->RainFall > 0.) {
//    RainfallIntensity = LocalPrecip->RainFall * (1./MMTOM) * (3600./Dt);
//
//    /* Momentum is later weighted with the overstory/understory fraction */
//    if (RainfallIntensity < 10.)
//      MS_Index = 0;
//    else if (RainfallIntensity >= 10. && RainfallIntensity < 100.)
//      MS_Index = floor((RainfallIntensity + 49)/50);
//    else
//      MS_Index = 3;
//
//    /* Eq. 1, Wicks and Bathurst (1996) */
//    MS_Rainfall = alpha[MS_Index] * pow(RainfallIntensity, beta[MS_Index]);
//
//    /* Calculating mediam raindrop diameter after Laws and Parsons (1943) */
//    LocalPrecip->Dm =  0.00124 * pow((double)RainfallIntensity, 0.182);
//  }
//  else {
//    MS_Rainfall = 0;
//    LocalPrecip->Dm = LEAF_DRIP_DIA;
//  }

    CRainfallImpact * cRainfallImpact = new CRainfallImpact();
    cRainfallImpact->init(LocalPrecip->RainFall, Dt);
    cRainfallImpact->execute();
    cRainfallImpact->query(&MS_Rainfall, &(LocalPrecip->Dm));
    delete cRainfallImpact;

  /* calculate the amount of interception storage, and the amount of
     throughfall.  Of course this only needs to be done if there is
     vegetation present. */
  /* related files:
  SnowInterception.c brent.h constants.h settings.h massenergy.h data.h
  Calendar.h snow.h functions.h DHSVMChannel.h getinit.h channel.h channel_grid.h

  RadiationBalance.c settings.h data.h Calendar.h  DHSVMerror.h massenergy.h constants.h

  InterceptionStorage.c settings.h data.h Calendar.h DHSVMerror.h massenergy.h constants.h

  SnowMelt.c brent.h constants.h settings.h massenergy.h data.h Calendar.h
  functions.h DHSVMChannel.h getinit.h channel.h channel_grid.h snow.h
  */

#ifndef NO_SNOW

  if (VType->OverStory == TRUE &&
      (LocalPrecip->IntSnow[0] || LocalPrecip->SnowFall > 0.0)) {
//    SnowInterception(y, x, Dt, VType->Fract[0], VType->LAI[0],
//		     VType->MaxInt[0], VType->MaxSnowInt, VType->MDRatio,
//		     VType->SnowIntEff, UpperRa, LocalMet->AirDens,
//		     LocalMet->Eact, LocalMet->Lv, &LocalRad, LocalMet->Press,
//		     LocalMet->Tair, LocalMet->Vpd, UpperWind,
//		     &(LocalPrecip->RainFall), &(LocalPrecip->SnowFall),
//		     &(LocalPrecip->IntRain[0]), &(LocalPrecip->IntSnow[0]),
//		     &(LocalPrecip->TempIntStorage),
//		     &(LocalSnow->CanopyVaporMassFlux), &(LocalVeg->Tcanopy),
//		     &MeltEnergy, &(LocalPrecip->MomentSq), VType->Height,
//		     VType->UnderStory, MS_Rainfall, LD_FallVelocity);

    CSnowInterception * cSnowInterception = new CSnowInterception();
    cSnowInterception->init(y, x, Dt, VType->Fract[0], VType->LAI[0],
		     VType->MaxInt[0], VType->MaxSnowInt, VType->MDRatio,
		     VType->SnowIntEff, UpperRa, LocalMet->AirDens,
		     LocalMet->Eact, LocalMet->Lv, &LocalRad, LocalMet->Press,
		     LocalMet->Tair, LocalMet->Vpd, UpperWind,
		     &(LocalPrecip->RainFall), &(LocalPrecip->SnowFall),
		     &(LocalPrecip->IntRain[0]), &(LocalPrecip->IntSnow[0]),
		     &(LocalPrecip->TempIntStorage),
		     &(LocalSnow->CanopyVaporMassFlux), &(LocalVeg->Tcanopy),
		     &MeltEnergy, &(LocalPrecip->MomentSq), VType->Height,
		     VType->UnderStory, MS_Rainfall, LD_FallVelocity);
    delete cSnowInterception;

    MoistureFlux -= LocalSnow->CanopyVaporMassFlux;

    /* Because we now have a new estimate of the canopy temperature we can
       recalculate the longwave balance */
    if (LocalSnow->HasSnow == TRUE)
      Tsurf = LocalSnow->TSurf;
    else if (HeatFluxOption == TRUE)
      Tsurf = LocalSoil->TSurf;
    else
      Tsurf = LocalMet->Tair;
    LongwaveBalance(Options, VType->OverStory, VType->Fract[0], LocalMet->Lin,
	               LocalVeg->Tcanopy, Tsurf, &LocalRad);
  }
  else if (VType->NVegLayers > 0) {
    LocalVeg->Tcanopy = LocalMet->Tair;
    LocalSnow->CanopyVaporMassFlux = 0.0;
    LocalPrecip->TempIntStorage = 0.0;
//    InterceptionStorage(VType->NVegLayers, NVegLActual, VType->MaxInt,
//			VType->Fract, LocalPrecip->IntRain,
//			&(LocalPrecip->RainFall), &(LocalPrecip->MomentSq),
//			VType->Height, VType->UnderStory, Dt, MS_Rainfall,
//			LD_FallVelocity);
    CInterceptionStorage * cInterceptionStorage = new CInterceptionStorage();
    cInterceptionStorage->init(VType->NVegLayers, NVegLActual, VType->MaxInt,
			VType->Fract, LocalPrecip->IntRain,
			&(LocalPrecip->RainFall), &(LocalPrecip->MomentSq),
			VType->Height, VType->UnderStory, Dt, MS_Rainfall,
			LD_FallVelocity);
    cInterceptionStorage->execute();
    delete cInterceptionStorage;

  }
  else {
    /* If no vegetation, kinetic energy is all due to direct precipitation. */
    if(LocalPrecip->RainFall > 0.0)
    LocalPrecip->MomentSq = MS_Rainfall;
  }

  /* If snow on the ground, assume no overland flow erosion. */
  if(LocalSnow->HasSnow)
    LocalPrecip->MomentSq = 0.0;

  /* if snow is present, simulate the snow pack dynamics */

  if (LocalSnow->HasSnow || LocalPrecip->SnowFall > 0.0) {

    if (VType->OverStory == TRUE) {
      SnowLongIn = LocalRad.LongIn[1];
      SnowNetShort = LocalRad.NetShort[1];
    }
    else {
      SnowLongIn = LocalRad.LongIn[0];
      SnowNetShort = LocalRad.NetShort[0];
    }

    SnowWind = VType->USnow * LocalMet->Wind;
    SnowRa = VType->RaSnow / LocalMet->Wind;

//    LocalSnow->Outflow =
//      SnowMelt(y, x, Dt, 2. + Z0_SNOW, 0.f, Z0_SNOW, SnowRa, LocalMet->AirDens,
//	       LocalMet->Eact, LocalMet->Lv, SnowNetShort, SnowLongIn,
//	       LocalMet->Press, LocalPrecip->RainFall, LocalPrecip->SnowFall,
//	       LocalMet->Tair, LocalMet->Vpd, SnowWind,
//	       &(LocalSnow->PackWater), &(LocalSnow->SurfWater),
//	       &(LocalSnow->Swq), &(LocalSnow->VaporMassFlux),
//	       &(LocalSnow->TPack), &(LocalSnow->TSurf), &MeltEnergy);

     CSnowMelt * cSnowMelt = new CSnowMelt();
     cSnowMelt->init(y, x, Dt, 2. + Z0_SNOW, 0.f, Z0_SNOW, SnowRa, LocalMet->AirDens,
	       LocalMet->Eact, LocalMet->Lv, SnowNetShort, SnowLongIn,
	       LocalMet->Press, LocalPrecip->RainFall, LocalPrecip->SnowFall,
	       LocalMet->Tair, LocalMet->Vpd, SnowWind,
	       &(LocalSnow->PackWater), &(LocalSnow->SurfWater),
	       &(LocalSnow->Swq), &(LocalSnow->VaporMassFlux),
	       &(LocalSnow->TPack), &(LocalSnow->TSurf), &MeltEnergy, &(LocalSnow->Outflow));
	 cSnowMelt->execute();
	 delete cSnowMelt;

    /* Rainfall was added to SurfWater of the snow pack and has to be set to zero */

    LocalPrecip->RainFall = 0.0;
    MoistureFlux -= LocalSnow->VaporMassFlux;

    /* Because we now have a new estimate of the snow surface temperature we
       can recalculate the longwave balance */

    Tsurf = LocalSnow->TSurf;
    LongwaveBalance(Options, VType->OverStory, VType->Fract[0], LocalMet->Lin,
		    LocalVeg->Tcanopy, Tsurf, &LocalRad);
  }
  else {
    LocalSnow->Outflow = 0.0;
    LocalSnow->VaporMassFlux = 0.0;
  }

  /* Determine whether a snow pack is still present, or whether everything
     has melted */

  if (LocalSnow->Swq > 0.0)
    LocalSnow->HasSnow = TRUE;
  else
    LocalSnow->HasSnow = FALSE;

  /*do the glacier add */
  if (LocalSnow->Swq < 1.0 && VType->Index == GLACIER) {
    printf("resetting glacier swe of %f to 5.0 meters\n", LocalSnow->Swq);
    LocalSnow->Glacier += (5.0 - LocalSnow->Swq);
    LocalSnow->Swq = 5.0;
    LocalSnow->TPack = 0.0;
    LocalSnow->TSurf = 0.0;
  }
#endif

#ifndef NO_ET
  /* calculate the amount of evapotranspiration from each vegetation layer
     above the ground/soil surface.  Also calculate the total amount of
     evapotranspiration from the vegetation */

  /* related files: EvapoTranspiration.c settings.h data.h Calendar.h DHSVMerror.h massenergy.h constants.h
                    SoilEvaporation.c settings.h DHSVMerror.h massenergy.h data.h Calendar.h constants.h
  */
  if (VType->OverStory == TRUE) {
    Rp = VISFRACT * LocalRad.NetShort[0];
    NetRadiation =
      LocalRad.NetShort[0] +
      LocalRad.LongIn[0] - 2 * VType->Fract[0] * LocalRad.LongOut[0];
//    EvapoTranspiration(0, Dt, LocalMet, NetRadiation, Rp, VType, SType,
//		       MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[0]),
//		       LocalEvap, LocalNetwork->Adjust, UpperRa);
    CEvapoTranspiration* cEvapoTranspiration = new CEvapoTranspiration();
    cEvapoTranspiration->init(0, Dt, LocalMet, NetRadiation, Rp, VType, SType,
		       MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[0]),
		       LocalEvap, LocalNetwork->Adjust, UpperRa);
    cEvapoTranspiration->execute();
    delete cEvapoTranspiration;

    MoistureFlux += LocalEvap->EAct[0] + LocalEvap->EInt[0];

    if (LocalSnow->HasSnow != TRUE && VType->UnderStory == TRUE) {
      Rp = VISFRACT * LocalRad.NetShort[1];
      NetRadiation =
	LocalRad.NetShort[1] +
	LocalRad.LongIn[1] - VType->Fract[1] * LocalRad.LongOut[1];
      EvapoTranspiration(1, Dt, LocalMet, NetRadiation, Rp, VType, SType,
			 MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[1]),
			 LocalEvap, LocalNetwork->Adjust, LowerRa);
      MoistureFlux += LocalEvap->EAct[1] + LocalEvap->EInt[1];
    }
    else if (VType->UnderStory == TRUE) {
      LocalEvap->EAct[1] = 0.;
      LocalEvap->EInt[1] = 0.;
    }
  }				/* end if(VType->OverStory == TRUE) */
  else if (LocalSnow->HasSnow != TRUE && VType->UnderStory == TRUE) {
    Rp = VISFRACT * LocalRad.NetShort[0];
    NetRadiation =
      LocalRad.NetShort[0] +
      LocalRad.LongIn[0] - VType->Fract[0] * LocalRad.LongOut[0];
    EvapoTranspiration(0, Dt, LocalMet, NetRadiation, Rp, VType, SType,
		       MoistureFlux, LocalSoil, &(LocalPrecip->IntRain[0]),
		       LocalEvap, LocalNetwork->Adjust, LowerRa);
    MoistureFlux += LocalEvap->EAct[0] + LocalEvap->EInt[0];
  }
  else if (VType->UnderStory == TRUE) {
    LocalEvap->EAct[0] = 0.;
    LocalEvap->EInt[0] = 0.;
  }

  /* Calculate soil evaporation from the upper soil layer if no snow is
     present and there is no understory */

  if (LocalSnow->HasSnow != TRUE && VType->UnderStory != TRUE) {

    if (VType->OverStory == TRUE)
      NetRadiation =
	LocalRad.NetShort[1] + LocalRad.LongIn[1] - LocalRad.LongOut[1];
    else
      NetRadiation =
	LocalRad.NetShort[0] + LocalRad.LongIn[0] - LocalRad.LongOut[0];

//    LocalEvap->EvapSoil =
//      SoilEvaporation(Dt, LocalMet->Tair, LocalMet->Slope, LocalMet->Gamma,
//		      LocalMet->Lv, LocalMet->AirDens, LocalMet->Vpd,
//		      NetRadiation, LowerRa, MoistureFlux, SType->Porosity[0],
//		      SType->Ks[0], SType->Press[0], SType->PoreDist[0],
//		      VType->RootDepth[0], &(LocalSoil->Moist[0]),
//		      LocalNetwork->Adjust[0]);
{
    CSoilEvaporation * cSoilEvaporation = new CSoilEvaporation();
    cSoilEvaporation->init(Dt, LocalMet->Tair, LocalMet->Slope, LocalMet->Gamma,
		      LocalMet->Lv, LocalMet->AirDens, LocalMet->Vpd,
		      NetRadiation, LowerRa, MoistureFlux, SType->Porosity[0],
		      SType->Ks[0], SType->Press[0], SType->PoreDist[0],
		      VType->RootDepth[0], &(LocalSoil->Moist[0]),
		      LocalNetwork->Adjust[0], &(LocalEvap->EvapSoil));
    cSoilEvaporation->execute();
    delete cSoilEvaporation;
}


  }
  else
    LocalEvap->EvapSoil = 0.0;

  MoistureFlux += LocalEvap->EvapSoil;
  LocalEvap->ETot += LocalEvap->EvapSoil;

#endif

  /* add the water that was not intercepted to the upper soil layer */

#ifndef NO_SOIL

  /* This has been modified so that PercArea for infiltration is calculated
     locally to account for the fact that some cells have roads and streams.
     I am not sure if the old PercArea (which does not account for the fact
     that some cells have roads and streams) needs to remain the same.
     Currently, the old PercArea is passed to UnsaturatedFlow */

  MaxRoadbedInfiltration = 0.;
  MaxInfiltration = 0.;
  ChannelWater = 0.;
  RoadWater = 0.;
  SurfaceWater = 0.;
  PercArea = 1.;
  RoadbedInfiltration = 0.;

  /* ChannelWater is precipitation falling on the channel */
  /* (if there is no road, LocalNetwork->RoadArea = 0) */
  if (channel_grid_has_channel(ChannelData->stream_map, x, y)){
    PercArea = 1. - (LocalNetwork->Area + LocalNetwork->RoadArea)/(DX*DY);
    ChannelWater = LocalNetwork->Area/(DX*DY) * LocalPrecip->RainFall;
  }
  /* If there is a road and no channel, the PercArea is
     based on the road only */
  else if (channel_grid_has_channel(ChannelData->road_map, x, y)){
    PercArea = 1. - (LocalNetwork->RoadArea)/(DX*DY);
    MaxRoadbedInfiltration = (1. - PercArea) *
      LocalNetwork->MaxInfiltrationRate * Dt;
  }

  /* SurfaceWater is rain falling on the hillslope +
     snowmelt on the hillslope (there is no snowmelt on the channel) +
     existing IExcess */
  /* related files: independant
  */
//  SurfaceWater = (PercArea * LocalPrecip->RainFall) +
//    ((1. - (LocalNetwork->RoadArea)/(DX*DY)) * LocalSnow->Outflow) +
//    LocalSoil->IExcess;
    CSurfaceWater * cSurfaceWater = new CSurfaceWater();
    //float m_PercArea, float m_Rainfall, float m_RoadArea, float m_DX, float m_DY, float m_Outflow, float m_IExcess
    cSurfaceWater->init(PercArea,LocalPrecip->RainFall,LocalNetwork->RoadArea, DX, DY, LocalSnow->Outflow, LocalSoil->IExcess );
    cSurfaceWater->execute();
    cSurfaceWater->query(&SurfaceWater);
    delete cSurfaceWater;

  /* RoadWater is rain falling on the road surface +
     snowmelt on the road surface + existing Road IExcess
     (Existing road IExcess = 0). WORK IN PROGRESS*/
  /* related files: independant
  */
//  RoadWater = (LocalNetwork->RoadArea/(DX*DY) *
//	       (LocalPrecip->RainFall + LocalSnow->Outflow)) +
//    LocalNetwork->IExcess;
    CRoadWater * cRoadWater = new CRoadWater();
    cRoadWater->init(LocalNetwork->RoadArea, DX, DY, LocalPrecip->RainFall, LocalSnow->Outflow, LocalNetwork->IExcess);
    cRoadWater->execute();
    cRoadWater->query(&RoadWater);
    delete cRoadWater;

  /* Infiltration module
  *  related files or modules: SurfaceWater, RoadWater,UnsaturatedFlow.c
								constants.h settings.h functions.h
								data.h Calendar.h DHSVMChannel.h getinit.h channel.h
								channel_grid.h soilmoisture.h
  */
  if(InfiltOption == STATIC)
    MaxInfiltration = (1. - VType->ImpervFrac) * PercArea * SType->MaxInfiltrationRate * Dt;

  else { /* InfiltOption == DYNAMIC
	    Dynamic Infiltration Capacity after Parlange and Smith 1978,
	    as used in KINEROS and THALES */
    Infiltration = 0.0;

    if (SurfaceWater > 0.) {
      /* Infiltration is a function of the amount of water infiltrated since
	 the storm started */
      if (LocalPrecip->PrecipStart){
	LocalSoil->MoistInit = LocalSoil->Moist[0];
	LocalSoil->InfiltAcc = 0.0;
      }

      /* Check that the B parameter > 0 */
      if ((LocalSoil->InfiltAcc > 0.) && (SType->Porosity[0] > LocalSoil->MoistInit)) {

	B = (SType->Porosity[0] - LocalSoil->MoistInit) *
	  (SType->G_Infilt + SurfaceWater);
	Infiltrability = SType->Ks[0] * exp((LocalSoil->InfiltAcc)/B) /
	  (exp((LocalSoil->InfiltAcc)/B) - 1.);
      }

      else
	Infiltrability = SurfaceWater/Dt ;

      MaxInfiltration = Infiltrability * PercArea *
	(1. - VType->ImpervFrac) *  Dt;

      LocalPrecip->PrecipStart = FALSE;
    }/* end  if (SurfaceWater > 0.) */
    else
      LocalPrecip->PrecipStart = TRUE;

  } /* end Dynamic MaxInfiltration calculation */

  Infiltration = (1. - VType->ImpervFrac) * SurfaceWater;

  if (Infiltration > MaxInfiltration)
    Infiltration = MaxInfiltration;

  RoadbedInfiltration = RoadWater;

  if (RoadbedInfiltration > MaxRoadbedInfiltration)
    RoadbedInfiltration = MaxRoadbedInfiltration;

  if (RoadRouteOption == FALSE)
    LocalSoil->IExcess = SurfaceWater - Infiltration +
      RoadWater - RoadbedInfiltration;
  else {
    LocalSoil->IExcess = SurfaceWater - Infiltration;
    LocalNetwork->IExcess = RoadWater - RoadbedInfiltration;
    if (LocalNetwork->IExcess < 0.){
      LocalNetwork->IExcess = 0.;
      printf("MEB: NetIExcess(%f), reset to 0\n", LocalNetwork->IExcess);
    }
  }

  if (LocalSoil->IExcess < 0.){
    printf("MEB: SoilIExcess(%f), reset to 0\n", LocalSoil->IExcess);
    LocalSoil->IExcess = 0.;
  }

  /*Add water that hits the channel network to the channel network */
  /* related files: channel_grid.c channel_grid.h channel.h settings.h
					data.h Calendar.h tableio.h errorhandler.h DHSVMChannel.h
					getinit.h
  */
  if (ChannelWater > 0.){
    channel_grid_inc_inflow(ChannelData->stream_map, x, y, ChannelWater * DX * DY);
    LocalSoil->ChannelInt += ChannelWater;
   }

  /* Calculate unsaturated soil water movement, and adjust soil water
     table depth */
  /* related files: UnsaturatedFlow.c constants.h settings.h functions.h
					data.h Calendar.h DHSVMChannel.h getinit.h channel.h
					channel_grid.h soilmoisture.h
  */
//		  LocalSoil->Depth, LocalNetwork->Area, VType->RootDepth,
//		  SType->Ks, SType->PoreDist, SType->Porosity, SType->FCap,
//		  LocalSoil->Perc, LocalNetwork->PercArea,
//		  LocalNetwork->Adjust, LocalNetwork->CutBankZone,
//		  LocalNetwork->BankHeight, &(LocalSoil->TableDepth),
//		  &(LocalSoil->IExcess), LocalSoil->Moist, RoadRouteOption,
//		  InfiltOption, &(LocalNetwork->IExcess));

    CUnsaturatedFlow * cUnsaturatedFlow = new CUnsaturatedFlow();
    cUnsaturatedFlow->init(Dt, DX, DY, Infiltration, RoadbedInfiltration,
		  LocalSoil->SatFlow, SType->NLayers,
		  LocalSoil->Depth, LocalNetwork->Area, VType->RootDepth,
		  SType->Ks, SType->PoreDist, SType->Porosity, SType->FCap,
		  LocalSoil->Perc, LocalNetwork->PercArea,
		  LocalNetwork->Adjust, LocalNetwork->CutBankZone,
		  LocalNetwork->BankHeight, &(LocalSoil->TableDepth),
		  &(LocalSoil->IExcess), LocalSoil->Moist, RoadRouteOption,
		  InfiltOption, &(LocalNetwork->IExcess));
    cUnsaturatedFlow->execute();
    delete cUnsaturatedFlow;

  /* Infiltration is updated in UnsaturatedFlow and accumulated
     below */
  if ((InfiltOption == DYNAMIC) && (SurfaceWater > 0.))
    LocalSoil->InfiltAcc += Infiltration;

  if (HeatFluxOption == TRUE) {
    if (LocalSnow->HasSnow == TRUE) {
      Reference = 2. + Z0_SNOW;
      Roughness = Z0_SNOW;
    }
    else {
      Reference = 2. + Z0_GROUND;
      Roughness = Z0_GROUND;
    }

	/* Calculate sensible heat flux
	related file: SensibleHeatFlux.c settings.h data.h Calendar.h
				  DHSVMerror.h massenergy.h constants.h brent.h functions.h
				  DHSVMChannel.h getinit.h channel.h channel_grid.h
	*/
//    SensibleHeatFlux(y, x, Dt, LowerRa, Reference, 0.0f, Roughness,
//		     LocalMet, LocalRad.PixelNetShort, LocalRad.PixelLongIn,
//		     MoistureFlux, SType->NLayers, VType->RootDepth,
//		     SType, MeltEnergy, LocalSoil);

    CSensibleHeatFlux *cSensibleHeatFlux = new CSensibleHeatFlux();
    cSensibleHeatFlux->init(y, x, Dt, LowerRa, Reference, 0.0f, Roughness,
		     LocalMet, LocalRad.PixelNetShort, LocalRad.PixelLongIn,
		     MoistureFlux, SType->NLayers, VType->RootDepth,
		     SType, MeltEnergy, LocalSoil);
	cSensibleHeatFlux->execute();
    delete cSensibleHeatFlux;
    Tsurf = LocalSoil->TSurf;

	/* Calculate long wave balance
	related files: RadiationBalance.c settings.h data.h Calendar.h
				   DHSVMerror.h massenergy.h constants.h
	*/
    LongwaveBalance(Options, VType->OverStory, VType->Fract[0], LocalMet->Lin,
		    LocalVeg->Tcanopy, Tsurf, &LocalRad);
  }
  else

    /* Calculate No sensible heat flux
	related files: SensibleHeatFlux.c settings.h data.h Calendar.h
					DHSVMerror.h massenergy.h constants.h brent.h functions.h
					DHSVMChannel.h getinit.h channel.h channel_grid.h
	*/
//    NoSensibleHeatFlux(Dt, LocalMet, MoistureFlux, LocalSoil);


{
    CNoSensibleHeatFlux *cNoSensibleHeatFlux = new CNoSensibleHeatFlux();
    cNoSensibleHeatFlux->init(Dt, LocalMet, MoistureFlux, LocalSoil);
    cNoSensibleHeatFlux->execute();
    delete cNoSensibleHeatFlux;
}

#endif

  /* add the components of the radiation balance for the current pixel to
     the total */
  /* related files: AggregateRadiation.c settings.h data.h Calendar.h massenergy.h
  */
//  AggregateRadiation(MaxVegLayers, VType->NVegLayers, &LocalRad, TotalRad);

  CAggregateRadiation *cAggregateRadiation = new CAggregateRadiation();
  cAggregateRadiation->init(MaxVegLayers, VType->NVegLayers, &LocalRad, TotalRad);
  cAggregateRadiation->execute();
  delete cAggregateRadiation;

  /* For RBM model, save the energy fluxes for outputs */
  /* related files: channel_grid.c channel_grid.h channel.h settings.h
					data.h Calendar.h tableio.h errorhandler.h DHSVMChannel.h
					getinit.h
  */
  if (Options->StreamTemp) {
    if (channel_grid_has_channel(ChannelData->stream_map, x, y))
      channel_grid_inc_other(ChannelData->stream_map, x, y, &LocalRad, LocalMet, skyview[y][x]);
  }
}