#include "HeatFluxCal.h"
#include "HeatMetrics_Calc.h"

//Note: Refactor CoolAir energy balance
// 1. For RefStation cell with estimated R_aero find Tair and AbsHum of adjacent air layer based on Yang (2013) H and LE
// 2. For every other cell find H and LE based on Yang (2013) for energy balance with R_aero and Tair and AbsHum of adjacent layer
// 3. Scale Yang (2013) H and LE values to Capodimonte values. 
// 4. Compute Tair_mesoscale and AbsHum_mesoscale, one value for all cells, based on boundary layer diurnal behavior, stability theory (USEPA, 2000; Turner's Method page 6-12)
// 5. Compute R_aero for each cell that satisfies Eq 1, etc. of Yang (2013) given Tair_mesocale and AbsHum_mesoscale and scaled H and LE (Capodimonte)
// *. Isolate the reference station for folder: if (folder->ParamDict["MapPixel_ID"] == reffolder->ParamDict["MapPixel_ID"]) {}
// *. Isolate teh reference station for input: input->DEM[input->MapPixel_ReferenceStation_ID];
// 

//Note: Refactor to clarify land cover height vs as roughness length; should HydroPlusConfig.xml height inputs be transformed to roughness length with 0.123 or 0.0123 coefficients
//Note: Refactor HeatFluxCal.cpp to consider Masson (2000) Eq 13 to 17, adjusting solar radiation between roof, wall, and road based on canyon orientation
//Note: Refactor temporal or seasonal variation in a1 to a3 coefficients as in Sun et al. (2017) or Ward et al. (2016), and combined impervious and building values for urban as in Ward (2016)
//Note: Holstag et al. (1988) evaluated nighttime energy budget which may help us obtain additional cooling

//Note: Theory of Cool Air model captured by following statement of McNaughton et al. (1995): a) complex model: b) single layer big-leaf model; c) and two-layer model:
//Note: ... Models that describe small-scale processes very well are frequently unsuitable for large-scale applications because the generalized data available on the large scale do not justify precise calculations. For this reason, there often exists a hierarchy of models for the same processes, each with its own data requirements and each with its own degree of approximation to the real world. Canopy energy balance models are no exception. 
//Note: ... A. At the complex end of the range are canopy models that require a detailed description of canopy structure and state and employ a detailed description of turbulent transport processes. The transport processes can be based on diffusion ('K') theory (e.g., Philip, 1965; Waggoner and Reifsnyder, 1968), higher-order closure theory (e.g., Meyers and Paw U, 1987) or Lagrangian theory (e.g., Wilson, 1981; Raupach, 1989a). Of these, K theory is now considered inadequate for precise work because eddy size scales in canopies are large compared to the height intervals over which gradients change appreciably (Raupach and Thom, 1981). /f-theory models, for example, won't allow fluxes 'up' concentration gradients, even though this phenomenon is well documented in nature (Denmead and Bradley, 1985). Whatever turbulence theory is used, all detailed models require too much information on canopy and turbulence structure to be worth using in large-scale applications such as catchment hydrology or representing vegetation in global climate models. 
//Note: ... B. At the simple end of the range is the 'big-leaf' model of Penman and Monteith (Monteith, 1965). This model requires no information on canopy structure apart from the aerodynamic roughness length and displacement height, and it represents turbulent transport by the assumption that air within the canopy is well mixed, with each leaf 'seeing' the same temperature and humidity as all others. It provides no information at all on how microclimate varies within the canopy. The PenmanMonteith model has been very popular in large-scale applications. 
//Note: ... C. Between these extremes lie the two-layer models (e.g., Shuttleworth and Wallace, 1985; Choudhury and Monteith, 1988). These models go one step beyond the simple Penman-Monteith model by giving separate account of conditions at the ground and within the overstorey. The motive for this complication of the basic Penman-Monteith model is that evaporation from soil or shallow-rooted ground vegetation often behaves in a very different way to evaporation from deeper-rooted overstorey vegetation. This can significantly affect the overall energy balance of sparse canopies where a substantial fraction of the incoming solar radiation reaches the ground. The task of a two-layer model is to differentiate the environment near the ground from that within the overstorey canopy. Turbulent transport between the ground and the overstorey canopy is represented explicitly in these models even though the air within the overstorey is still treated as well mixed. 


//Energy balance determines surface heat flux and evaporative cooling or heating of air, as described by Yang et al. (2013)
//NR = H_total_W_p_m2 + LE_total_W_p_m2 + DeltaQ_W_p_m2, where NR is net radiation of shortwave and longwave terms, H_total_W_p_m2 is sensible heat flux, LE_total_W_p_m2 is latent heat flux, and DeltaQ_W_p_m2 is ground storage heat flux

//References:
//Bradley, A., Thornes, J., Chapman, L., Unwin, D., & Roy, M. (2002). Modeling spatial and temporal road thermal climatology in rural and urban areas using a GIS. Climate Research - CLIMATE RES, 22, 41-55. doi:10.3354/cr022041
//Grimmond, C. S. B., & Oke, T. R. (1999). Heat storage in urban areas: Local-scale observations and evaluation of a simple model. Journal of Applied Meteorology, 38(7), 922-940. doi:10.1175/1520-0450(1999)038<0922:hsiual>2.0.co;2
//Holtslag, A. A. M., & De Bruin, H. A. R. (1988). Applied Modeling of the Nighttime Surface Energy Balance over Land. Journal of Applied Meteorology and Climatology, 27(6), 689-704. doi:10.1175/1520-0450(1988)027<0689:Amotns>2.0.Co;2
//Kumar, L., Skidmore, A. K., & Knowles, E. (1997). Modelling topographic variation in solar radiation in a GIS environment. International Journal of Geographical Information Science, 11(5), 475-497. doi:10.1080/136588197242266
//Kusaka et al. (2001), A simple single - layer urban canopy model for atmospheric models : Comparison with multi - layer and slab models, Boundary Layer Meteorol., 101(3), 329–358.
//McNaughton, K. G., & Van Den Hurk, B. J. J. M. (1995). A ‘Lagrangian’ revision of the resistors in the two-layer model for calculating the energy budget of a plant canopy. Boundary-Layer Meteorology, 74(3), 261-288. doi:10.1007/BF00712121
//Masson (2000), A Physically based scheme for the urban energy budget in atmospheric models, Boundary Layer Meteorology, 94: 357-397.
//Offerle, B., Grimmond, C. S. B., & Oke, T. R. (2003). Parameterization of net all-wave radiation for urban areas. Journal of Applied Meteorology, 42(8), 1157-1173. doi:10.1175/1520-0450(2003)042<1157:ponarf>2.0.co;2
//Oke, T. R., Mills, G., Christen, A., & Voogt, J. A. (2017). Radiation. In Urban Climates (pp. 122-155). Cambridge: Cambridge University Press. DOI: https://doi.org/10.1017/9781139016476.007
//Reda, I., & Andreas, A. (2003). Solar Position Algorithm for Solar Radiation Applications National Renewable Energy Laboratory, NREL/TP-560-34302. Revised 2008, 55. 
//Shuttleworth, J. W. (1993). Evaporation. In D. R. Maidment (Ed.), Handbook of Hydrology (pp. 4.1-4.5.3). New York: McGraw-Hill.
//Stull, R. (2017) "Practical Meteorology: An Algebra-based Survey of Atmospheric Science" -version 1.02b.  Univ. of British Columbia.  940 pages.  isbn 978-0-88865-283-6. https://www.eoas.ubc.ca/books/Practical_Meteorology/
//Stull, R. B. (2000). Meteorology for Scientists and Engineers (2nd ed.). Pacific Grove, CA: Brooks/Cole.
//Sun, T., Wang, Z. H., Oechel, W. C., & Grimmond, S. (2017). The Analytical Objective Hysteresis Model (AnOHM v1.0): methodology to determine bulk storage heat flux coefficients. Geosci. Model Dev., 10(7), 2875-2890. doi:10.5194/gmd-10-2875-2017
//USEPA (2000). Meteorological Monitoring Guidance for Regulatory Modeling Applications. US Environmental Protection Agency, Office of Air Quality. Washington, DC. EPA-454/R-99-005. 
//Vanek, F., Albright, L., & Angenent, L. (2012). Energy Systems Engineering: Evaluation and Implementation, Second Edition (2nd ed.). New York: McGraw-Hill
//Ward, H.C., Kotthaus, S., Järvi, L., & Grimmond, C.S.B. (2016). Surface Urban Energy and Water Balance Scheme (SUEWS): Development and evaluation at two UK sites.Urban Climate, 18, 1 - 32. doi : https ://doi.org/10.1016/j.uclim.2016.05.001
//Yang, Y., Endreny, T. A., & Nowak, D. J. (2013). A physically based analytical spatial air temperature and humidity model. Journal of Geophysical Research-Atmospheres, 118(18), 10449-10463. doi:10.1002/jgrd.50803

//Theory: Albedo is assigned by cell land cover type 21 to 24 based on the assumption impervious cover increases from ~20 to 80%.
//Note: A strategic alternative is albedo is assigned by actual cell land cover fraction exposed to incoming shortwave radiation.
//Note: Land cover albedo values are in Table 2-3 in Stull, 2000. Meteorology for Scientists and Engineers, 2nd Edition, Brooks Cole.
//Note: Road albedo = 5 to 15; Building albedo = 9; Concrete albedo = 15 to 37
//Note: Tree albedo changes type (max albedo = 15 coniferous vs 25 deciduous, min albedo = 5 coniferous vs 10 deciduous) 
//Note: Tree albedo deciduous should change with leaf on dates
//Note: Green grass albedo = 26; Agricultural cover emerges as gap area (TC+IC<100%) for NCLD LC types, and albedo ranges 5 to 32
//Note: Soil albedo changes with wetness (albedo = 7 wet vs 17 dry) and percent clay (100% clay is albedo = 16 wet vs 23 dry) 
//Note: Snow albedo might be simulated (old snow albedo = 35 to 70; new snow albedo = 75 to 90)

//Theory: Emissivity is assigned as a constant for cell land cover type 21 to 24 and then by land cover type tree, short veg, soil, and water
//Note: A strategic alternative is emissivity is assigned by actual cell impervious cover fraction exposed for outgoing longwave radiation
//Note: Land cover emissivity values are in Table 2-2 in Stull, 2000. Meteorology for Scientists and Engineers, 2nd Edition, Brooks Cole.
//Note: Asphalt  = 0.95; Concrete = 0.71-0.9; Bricks (red) = 0.92; Soils = 0.9-0.98; Desert = 0.84-0.91; Grass lawn = 0.97; Grass = 0.9-0.95; 
//Note: Tree Coniferous = 0.97; Tree Deciduous = 0.95; Snow (old to new) = 0.82-0.99; Shrubs = 0.9; Alfalfa = 0.95; Leaf 10um = 0.97-0.98				

//Theory: Ground heat storage, DeltaQ_W_p_m2, depends on a1, a2, and a3 parameters from inputs, and on NR (net radiation)
//Note: Algorithm Based on Eq 3 in Grimmond and Oke (1999), which is objective hysteresis model (OHM), calculating the storage heat flux as a function of net all-wave radiation and the surface properties of the site. 
//Note: Influence of DeltaQ_W_p_m2 to a1, a2, and a3 and NR explained below:
//Note:	... Parameter a1 (unitless) determines the magnitude of influence of NR on DeltaQ_W_p_m2.
//Note: ... Parameter a2 (hr) determines the phase of influence of d(NR) / dt on DeltaQ_W_p_m2.When a2 = 0, the DeltaQ_W_p_m2 curve matches, is in phase with, the NR curve, as a2 gets more positive, the DeltaQ_W_p_m2 curve precedes the NR curve, peaking sooner.
//Note: ... Parameter a3 (W/m^2) determines the size of DeltaQ_W_p_m2 when NR becomes negative.A large negative a3 creates a negative DeltaQ_W_p_m2 before NR is negative.
//Note: ... Values of a1, a2, a3 for NLCD Class 21 to 24 based on paved and building values in Table 4 of Ward et al. (2014), weighted by building fraction
/*
Coefficients for Objective Hysteresis Model: Table 4 of Ward et al. (2016); see OHM monthly diurnal patterns in Sun et al. (2017)
	Land Cover				a1 (frac),a2 (hr),a3 (W/m2)
	Paved					0.676,	0.300,	-42.4
	Bldgs					0.477,	0.337,	-33.9
	EveTr					0.215,	0.325,	−19.9
	DecTr					0.215,	0.325,	−19.9
	Grass					0.215,	0.325,	−19.9
	BSoil					0.355,	0.335,	−35.3
	Water shallow, turbid	0.500,	0.210,	−39.1
	//Water values for NLCD 11 from Endreny based on a1 < Mixed forest, a2 < Bare soil-wet, a3 < Mixed forest
	//Note: Endreny's values for water a1, a2, a3 create water hotter in day, cooler in night compared with values of GY&O
	Water deep, NLCD=11		0.050,	0.050,	−05.0
Coefficients for Objective Hysteresis Model: Table 4 of Grimmond and Oke (1999)
	Land Cover				a1 (frac),a2 (hr),a3 (W/m2)
	Mixed forest			0.11,	0.11,	-12.3
	Short grass				0.32,	0.54,	-27.4
	Bare soil				0.38,	0.56,	-27.3
	Bare soil—wet			0.33,	0.07,	-34.9
	Bare soil—dry			0.35,	0.43,	-36.5
	Soil 					0.36,	0.27,	-42.4
	Water—shallow turbid	0.5,	0.21,	-39.1
	Rooftop Vancouver		0.17,	0.1,	-17
	Rooftop Uppsala			0.44,	0.57,	-28.9
	Rooftop Kyoto			0.82,	0.34,	-55.7
	Concrete Doll			0.81,	0.48,	-79.9
	Concrete Asaeada		0.85,	0.32,	-28.5
	Asphalt Narita			0.36,	0.23,	-19.3
	Asphalt Asaeada			0.64,	0.32,	-43.6
	Asphalt Anandakumar		0.82,	0.68,	-20.1
	UrbanCanyon North-South	0.32,	0.01,	-27.7
	UrbanCanyon Easth-West	0.71	0.04,	-39.7
*/
//Define and initialize the static variables:
vector<double> HeatFluxCal::AH_total_W_p_m2_vec;
vector<double> HeatFluxCal::Imp_AH_W_p_m2_vec;
vector<double> HeatFluxCal::Tree_AH_W_p_m2_vec;
vector<double> HeatFluxCal::SVeg_AH_W_p_m2_vec;
vector<double> HeatFluxCal::Soil_AH_W_p_m2_vec;
vector<double> HeatFluxCal::Water_AH_W_p_m2_vec;
vector<double> HeatFluxCal::NR_total_W_p_m2_vec;
vector<double> HeatFluxCal::DeltaQ_W_p_m2_vec;
vector<double> HeatFluxCal::WaterDeltaQ_W_p_m2_vec;
vector<double> HeatFluxCal::SoilDeltaQ_W_p_m2_vec;
vector<double> HeatFluxCal::SVegDeltaQ_W_p_m2_vec;
vector<double> HeatFluxCal::TreeDeltaQ_W_p_m2_vec;
vector<double> HeatFluxCal::ImpDeltaQ_W_p_m2_vec;

//Constructor for HeatFluxCal with both SolarCalculator and Inputs pointer
//Note: Initialization list : or colon after function name initializes SolarCalculator and resistanceVar objects
//Note: ResistanceCal constructor of the ResistanceCal class initializes variables shared across void functions, shared globally
// Constructor for HeatFluxCal with both SolarCalculator and Inputs pointers
HeatFluxCal::HeatFluxCal(Inputs* input, SolarCalculator* solarCalc)
	: input(input), solarCalculator(solarCalc), resistanceVar(nullptr) {
	// If resistanceVar needs to be initialized based on input
	resistanceVar = new ResistanceCal(input);

	//Flag_UrbanCanyonResistance is flag (1 or 0) from HydroPlusConfig.xml for Uban21 to Urban24, where 1 = simulate urban canyon geometry for radiation balance, 0 = neglect urban canyon geometry
	//Note: In 2023 this Flag was named Flag_ExperimentalResistanceFunction in HydroPlusConfig.xml and in HydroPlus.sln
	Flag_UrbanCanyonResistance = input->TemperatureCalculationParams["Flag_UrbanCanyonResistance"];

	//Tree parameters
	//a1_OHM_Tree_frac, a2_OHM_Tree_hr, a3_OHM_Tree_W_p_m2 are terms to compute ground heat storage based on net radiation and Eq 3 in Grimmond and Oke (1999) objective hysteresis model (OHM)
	a1_OHM_Tree_frac = input->TemperatureCalculationParams["a1_OHM_Tree_frac"];
	a2_OHM_Tree_hr = input->TemperatureCalculationParams["a2_OHM_Tree_hr"];
	a3_OHM_Tree_W_p_m2 = input->TemperatureCalculationParams["a3_OHM_Tree_W_p_m2"];

	//Height_Tree_m (m) is average height of feature for roughness in turbulence exchange calculations
	Height_Tree_m = input->RefParams["Height_Avg_TreeCover_m"];
	//Albedo_Tree_frac (fraction) is albedo of feature for reflecting shortwave radiation
	Albedo_Tree_frac = input->TemperatureCalculationParams["Albedo_Tree_frac"];
	//Emissivity_Tree_frac (fraction) is emissivity of feature  for emitting longwave radiation
	Emissivity_Tree_frac = input->TemperatureCalculationParams["Emissivity_Tree_frac"];
	//Storage_per_LAI_BAI_Tree_m (m) is converted from mm depth
	//Note: Refactor to update HydroPlusConfig.xml to rename LeafAreaStorage_Tree_mm as Storage_per_LAI_mm and perhaps create Storage_per_BAI_mm
	Storage_per_LAI_BAI_Tree_m = input->RefParams["LeafAreaStorage_Tree_mm"] * Ratio_m_to_mm;

	//Short vegetation parameters
	//a1_OHM_SVeg_frac, a2_OHM_SVeg_hr, a3_OHM_SVeg_W_p_m2 are terms to compute ground heat storage based on net radiation and Eq 3 in Grimmond and Oke (1999) objective hysteresis model (OHM)
	a1_OHM_SVeg_frac = input->TemperatureCalculationParams["a1_OHM_SVeg_frac"];
	a2_OHM_SVeg_hr = input->TemperatureCalculationParams["a2_OHM_SVeg_hr"];
	a3_OHM_SVeg_W_p_m2 = input->TemperatureCalculationParams["a3_OHM_SVeg_W_p_m2"];

	//Height_SVeg_m (m) is average height of feature for roughness in turbulence exchange calculations
	Height_SVeg_m = input->RefParams["Height_Avg_SVegCover_m"];
	//Albedo_SVeg_frac (fraction) is albedo of feature for reflecting shortwave radiation
	Albedo_SVeg_frac = input->TemperatureCalculationParams["Albedo_SVeg_frac"];
	//Emissivity_SVeg_frac (fraction) is emissivity of feature for emitting longwave radiation
	Emissivity_SVeg_frac = input->TemperatureCalculationParams["Emissivity_SVeg_frac"];
	//Storage_per_LAI_BAI_SVeg_m (m) is converted from mm depth; PASATH had set it to 50% of Storage_per_LAI_BAI_Tree_m
	Storage_per_LAI_BAI_SVeg_m = input->RefParams["LeafAreaStorage_SVeg_mm"] * Ratio_m_to_mm;

	//Soil parameters
	//a1_OHM_Soil_frac, a2_OHM_Soil_hr, a3_OHM_Soil_W_p_m2 are terms to compute ground heat storage based on net radiation and Eq 3 in Grimmond and Oke (1999) objective hysteresis model (OHM)
	a1_OHM_Soil_frac = input->TemperatureCalculationParams["a1_OHM_Soil_frac"];
	a2_OHM_Soil_hr = input->TemperatureCalculationParams["a2_OHM_Soil_hr"];
	a3_OHM_Soil_W_p_m2 = input->TemperatureCalculationParams["a3_OHM_Soil_W_p_m2"];

	Height_Soil_m = input->TemperatureCalculationParams["Height_Avg_SoilCover_m"];
	Albedo_Soil_frac = input->TemperatureCalculationParams["Albedo_Soil_frac"];
	Emissivity_Soil_frac = input->TemperatureCalculationParams["Emissivity_Soil_frac"];

	//Water parameters
	//a1_OHM_Water_frac, a2_OHM_Water_hr, a3_OHM_Water_W_p_m2 are terms to compute ground heat storage based on net radiation and Eq 3 in Grimmond and Oke (1999) objective hysteresis model (OHM)
	//Note: OHM Table 4 of Ward et al. (2016), Water shallow, turbid a1=0.500, a2=0.210, a3=−39.1
	//Note: OHM Yang 2013 and in PASATH was a1=0.8 a2=0.7, a3=-100
	//Note: OHM Endreny for NLCD Class 11, a1=0.05, a2=0.05, a3=−5.0, so a1 < Mixed forest, a2 < Bare soil-wet, a3 < Mixed forest
	a1_OHM_Water_frac = input->TemperatureCalculationParams["a1_OHM_Water_frac"];
	a2_OHM_Water_hr = input->TemperatureCalculationParams["a2_OHM_Water_hr"];
	a3_OHM_Water_W_p_m2 = input->TemperatureCalculationParams["a3_OHM_Water_W_p_m2"];
	//Flag_Water_Diurnal_pattern (0 or 1) read from HydroPlusConfig.xml element Flag_Water_Diurnal_pattern to modulate water evaporation rates
	Flag_Water_Diurnal_pattern = input->TemperatureCalculationParams["Flag_Water_Diurnal_pattern"];
	//If Flag_Water_Diurnal_pattern is not zero, then read Water_Diurnal_max_frac and Water_Diurnal_min_frac to modulate water evaporation rates and air temperature 
	if (Flag_Water_Diurnal_pattern != 0) {
		Water_Diurnal_max_frac = input->TemperatureCalculationParams["Water_Diurnal_max_frac"];
		Water_Diurnal_min_frac = input->TemperatureCalculationParams["Water_Diurnal_min_frac"];
	}

	//Height_Water_m  (m) is average height of feature for roughness in turbulence exchange calculations
	Height_Water_m = input->TemperatureCalculationParams["Height_Avg_WaterCover_m"];
	//Albedo_Water_frac  (fraction) is albedo of feature for reflecting shortwave radiation
	Albedo_Water_frac = input->TemperatureCalculationParams["Albedo_Water_frac"];
	//Emissivity_Water_frac (fraction) is emissivity of surface feature for emitting longwave radiation
	Emissivity_Water_frac = input->TemperatureCalculationParams["Emissivity_Water_frac"];

	//Albedo_Asphalt_frac is average albedo for asphalt road (0.05 to 0.15) from Table 2.3 Stull (2000); comparable with Paved in Table 2 Ward et al. (2016)
	Albedo_Asphalt_frac = 0.1;
	//Emissivity_Asphalt_frac is emissivity for asphalt from Table 2.2 Stull (2000); comparable with Paved in Table 2 Ward et al. (2016)
	Emissivity_Asphalt_frac = 0.95;
	//Albedo_Concrete_frac is average albedo for concrete (0.15 to 0.37) from Table 2.3 Stull (2000)
	Albedo_Concrete_frac = 0.26;
	//Emissivity_Asphalt_frac is average emissivity for concrete (0.71 to 0.9) from Table 2.2 Stull (2000); comparable with Paved in Table 2 Ward et al. (2016)
	Emissivity_Concrete_frac = 0.805;
	//Albedo_Wall_frac is albedo for buildings from Table 2.3 Stull (2000)
	Albedo_Wall_frac = 0.09;
	//Emissivity_Wall_frac is average emissivity for bricks and lumber from Table 2.2 Stull (2000); comparable with Buildings in Table 2 Ward et al. (2016)
	Emissivity_Wall_frac = 0.91;
	//Albedo_Window_frac is albedo for Glass from Table 2 Bradley et al. (2002)
	Albedo_Window_frac = 0.305;
	//Emissivity_Wall_frac is average emissivity for glass from Table 2.2 Stull (2000); comparable with Glass in Table 2 Bradley et al. (2002)
	Emissivity_Window_frac = 0.905;
	//SkyViewFactor_Ground_Open_frac is 1 for open areas, beyond urban canyons
	SkyViewFactor_Ground_Open_frac = 1;
	//SkyViewFactor_Ground_Wall_frac is 0.5 for open areas, beyond urban canyons, and is multiplied by 2 for both walls
	SkyViewFactor_Ground_Wall_frac = 0.5;
}

//HeatFluxCal::~HeatFluxCal Destructor: clean up dynamically allocated memory
HeatFluxCal::~HeatFluxCal() {
	delete resistanceVar; // Free memory allocated for resistanceVar
	resistanceVar = nullptr; // Set pointer to nullptr for safety
}

//EnergyFlux_WaterFlux_DefineTerms function calculates energy balance once for each folder at each timeStep, before heading into the water balance calculations
//Note: For model = SpatialTemperatureHydro, MapPixel_ID has maximum = maxRows * maxCols, and DataFolder_ID typically has maximum = 1
void HeatFluxCal::EnergyFlux_WaterFlux_DefineTerms(Inputs* input, DataFolder* reffolder, DataFolder* folder, int MapPixel_ID, bool Flag_simulateReferenceStation, int timeStep, WeatherPreprocessor* Weatherpre, string StationID_string)
{

	//If Flag_MultipleStation is true and Flag_simulateReferenceStation is true then read in Weatherpre->WeatherMap ReferenceStation values
	//Note: Conditional obtains reference station Tair_K and Tdew_K (K) for Flag_MultipleStation = 1
	if (input->SimulationStringParams["Flag_MultipleStation"] == "1" && Flag_simulateReferenceStation == 1) {
		//StationMapID_string equals StationID_string
		string StationMapID_string = StationID_string;
		string keyname_Radiation_Longwave_Downwelling_Wpm2 = StationMapID_string + "_" + "Radiation_Longwave_Downwelling_Wpm2";
		string keyname_Radiation_Longwave_Upwelling_Wpm2 = StationMapID_string + "_" + "Radiation_Longwave_Upwelling_Wpm2";
		string keyname_WindSp_mps = StationMapID_string + "_" + "WindSpd_mps";
		string keyname_Tair_F = StationMapID_string + "_" + "Tair_F";
		string keyname_Tdew_F = StationMapID_string + "_" + "Tdew_F";

		//Radiation_Longwave_Down_W_p_m2 (W/m2) is from reference station
		//Note: Radiation is positive downward, w/ Radiation_Longwave_Down_W_p_m2 (W/m2) added within net radiation balances
		Radiation_Longwave_Down_W_p_m2 = Weatherpre->RadiationMap[keyname_Radiation_Longwave_Downwelling_Wpm2][timeStep];
		//Radiation_Longwave_Down_W_p_m2 (W/m2) is from reference station
		//Note: Radiation is positive downward, w/ Radiation_Longwave_Up_W_p_m2 (W/m2) subtracted within net radiation balances
		Radiation_Longwave_Up_W_p_m2 = Weatherpre->RadiationMap[keyname_Radiation_Longwave_Upwelling_Wpm2][timeStep];
		//WindSpeed_Reference_m_p_s (m/w) is the measured wind speed at the reference station
		WindSpeed_Reference_m_p_s = Weatherpre->WeatherMap[keyname_WindSp_mps][timeStep];
		//Tair_localCell_K (K) is converted from Tair_F (F), Fahrenheit, K = (F-32) * 5/9 + 273.15
		Tair_localCell_K = (Weatherpre->WeatherMap[keyname_Tair_F][timeStep] - 32) * 5.0 / 9.0 + 273.15;
		//Tair_referenceCell_K (K) set to Tair_localCell_K (K) for error handling
		Tair_referenceCell_K = Tair_localCell_K;
		//Tdew_localCell_K (K) is converted from Tdew_F (F), Fahrenheit, K = (F-32) * 5/9 + 273.15	
		Tdew_localCell_K = (Weatherpre->WeatherMap[keyname_Tdew_F][timeStep] - 32) * 5.0 / 9.0 + 273.15;
	}
	//Else If Flag_MultipleStation is true and Flag_simulateReferenceStation is false then read in Weatherpre->WeightedInputMap MapPixel_ID values
	//Note: Conditional either obtains local pixel Tair_K and Tdew_K (K) for Flag_MultipleStation = 0
	else if (input->SimulationStringParams["Flag_MultipleStation"] == "1" && Flag_simulateReferenceStation != 1) {
		//MapPixel_ID_string equals StationID_string
		string MapPixel_ID_string = to_string(MapPixel_ID);

		//Radiation_Longwave_Down_W_p_m2 (W/m2) is from reference station
		//Note: Radiation is positive downward, w/ Radiation_Longwave_Down_W_p_m2 (W/m2) added within net radiation balances
		Radiation_Longwave_Down_W_p_m2 = Weatherpre->WeightedInputMap[MapPixel_ID]["Radiation_Longwave_Downwelling_Wpm2"][timeStep];
		//Radiation_Longwave_Down_W_p_m2 (W/m2) is from reference station
		//Note: Radiation is positive downward, w/ Radiation_Longwave_Up_W_p_m2 (W/m2) subtracted within net radiation balances
		Radiation_Longwave_Up_W_p_m2 = Weatherpre->WeightedInputMap[MapPixel_ID]["Radiation_Longwave_Upwelling_Wpm2"][timeStep];
		//WindSpeed_Reference_m_p_s (m/w) is the measured wind speed at the reference station
		WindSpeed_Reference_m_p_s = Weatherpre->WeightedInputMap[MapPixel_ID]["WindSpd_mps"][timeStep];
		//Tair_localCell_K (K) is Weatherpre->WeightedInputMap[MapPixel_ID]["Tair_F"][timeStep] - 32) * 5.0/9.0 + 273.15, not lapse rate adjsuted
		Tair_localCell_K = (Weatherpre->WeightedInputMap[MapPixel_ID]["Tair_F"][timeStep] - 32) * 5.0/9.0 + 273.15;
		//Tair_referenceCell_K (K) set to Tair_localCell_K (K) for error handling
		Tair_referenceCell_K = Tair_localCell_K;
		//Tdew_localCell_K (K) is (Weatherpre->WeightedInputMap[MapPixel_ID]["Tdew_F"][timeStep] - 32) * 5.0 / 9.0 + 273.15, not lapse rate adjsuted
		Tdew_localCell_K = (Weatherpre->WeightedInputMap[MapPixel_ID]["Tdew_F"][timeStep] - 32) * 5.0 / 9.0 + 273.15;
	}
	//Else If Flag_MultipleStation and Flag_simulateReferenceStation are false then read in input-> meteorological values
	//Note: Conditional either obtains reference station and local pixel Tair_K and Tdew_K (K) for Flag_MultipleStation = 0
	//Note: if Flag_MultipleStation false then input-> meteorological values are from single instance of Weather.csv, Radiation.csv 
	//Note: if Flag_MultipleStation true then input-> meteorological values are from weighted instances of Weather.csv, Radiation.csv 
	else {
		//Radiation_Longwave_Down_W_p_m2 (W/m2) is from reference station
		//Note: Radiation is positive downward, w/ Radiation_Longwave_Down_W_p_m2 (W/m2) added within net radiation balances
		Radiation_Longwave_Down_W_p_m2 = input->Radiation_Longwave_Downwelling_Wpm2[timeStep];
		//Radiation_Longwave_Down_W_p_m2 (W/m2) is from reference station
		//Note: Radiation is positive downward, w/ Radiation_Longwave_Up_W_p_m2 (W/m2) subtracted within net radiation balances
		Radiation_Longwave_Up_W_p_m2 = input->Radiation_Longwave_Upwelling_Wpm2[timeStep];
		//WindSpeed_Reference_m_p_s (m/w) is the measured wind speed at the reference station
		WindSpeed_Reference_m_p_s = input->WindSpd_mps[timeStep];
		//Tair_localCell_K (K) is converted from Tair_F (F), Fahrenheit, K = (F-32) * 5/9 + 273.15
		Tair_localCell_K = (input->Tair_F[timeStep] - 32) * 5.0 / 9.0 + 273.15;
		//Tair_referenceCell_K (K) set to Tair_localCell_K (K) for error handling
		Tair_referenceCell_K = Tair_localCell_K;
		//Tdew_localCell_K (K) is converted from Tdew_F (F), Fahrenheit, K = (F-32) * 5/9 + 273.15
		Tdew_localCell_K = (input->Tdew_F[timeStep] - 32) * 5.0 / 9.0 + 273.15;
	}

	//If Tdew_localCell_K > Tair_localCell_K then set equal to handle mistaken weather inputs caused by sensor or rounding errors
	if (Tdew_localCell_K > Tair_localCell_K) { Tdew_localCell_K = Tair_localCell_K; }

	//Tdew_localCell_C (C) is converted from Tdew_localCell_K (K) to degrees C by subtracting 273.15
	double Tdew_localCell_C = Tdew_localCell_K - 273.15;
	//VaporPressure_Actual_kPa (kPa) as Tetens' formula in Eq 4.2.2 Shuttleworth (1993), e_kPa=0.6108*exp[(17.27*T_C)/(237.3+T_C)]
	//Note: Used in UrbanCanyon_RadiationLongwave calculation
	VaporPressure_Actual_kPa = 0.6108 * exp((17.27 * Tdew_localCell_C) / (237.3 + Tdew_localCell_C));

	//LandCover_Class_NLCD (Class) defined with input->NLCDLandCoverData for MapPixel_ID
	LandCover_Class_NLCD = input->NLCDLandCoverData[MapPixel_ID];
	//TreeCover_frac (frac) defined with folder->ParamDict["TreeCover_frac"], adjusted for each MapPixel_ID
	TreeCover_frac = folder->ParamDict["TreeCover_frac"];
	ImperviousCover_frac = folder->ParamDict["ImperviousCover_frac"];
	SoilCover_noTreeCanopy_frac = folder->ParamDict["SoilCover_noTreeCanopy_frac"];
	PermeablePavementCover_noTreeCanopy_frac = folder->ParamDict["PermeablePavementCover_noTreeCanopy_frac"];
	ShortVegCover_noTreeCanopy_frac = folder->ParamDict["ShortVegCover_noTreeCanopy_frac"];
	ImperviousCover_noTreeCanopy_frac = folder->ParamDict["ImperviousCover_noTreeCanopy_frac"];
	WaterCover_noTreeCanopy_frac = folder->ParamDict["WaterCover_noTreeCanopy_frac"];

	double RoadArea_frac = 0;
	//keynamepart1 and related strings used with StationInfoMap variables across Multiple Weather Stations 
	string keynamepart1{};
	string keyname_Radiation_ShortWave_Direct_W_p_m2{};
	string keyname_Radiation_Shortwave_Diffuse_W_p_m2{};
	string keyname_ImpNR_priorTS_W_p_m2{};
	string keyname_TreeNR_priorTS_W_p_m2{};
	string keyname_SVegNR_priorTS_W_p_m2{};
	string keyname_SoilNR_priorTS_W_p_m2{};
	string keyname_WaterNR_priorTS_W_p_m2{};
	string keyname_RoofNR_priorTS_W_p_m2{};


	//LAI_BAI_Tree_m2pm2 is LAI + BAI tree and has time varying impact on water storage 
	LAI_BAI_Tree_m2pm2 = input->LAI_BAI_Tree_m2_p_m2[timeStep];
	//LAI_BAI_SVeg_m2pm2  is LAI + BAI short vegetation and has time varying impact on water storage 
	LAI_BAI_SVeg_m2pm2 = input->LAI_BAI_SVeg_m2_p_m2[timeStep];
	//LAI_BAI_Tree_m2pm2 is LAI tree and has time varying impact on water storage 
	LAI_Tree_m2pm2 = input->LAI_Tree_m2_p_m2[timeStep];
	//LAI_BAI_SVeg_m2pm2  is LAI short vegetation and has time varying impact on water storage 
	LAI_SVeg_m2pm2 = input->LAI_SVeg_m2_p_m2[timeStep];

	//Consider Refactor to allow smaller depths of ponding for full evaporation, using concept such as Storage_PerviousSurfaceAdheringWater_Max_m
	//Storage_Depression_Max_Pervious_m (m) is depth of storage for ponded water in folder surface, scaled from mm to m with Ratio_m_to_mm
	Storage_Depression_Max_Pervious_m = folder->ParamDict["PerviousDepressionStorage_mm"] * Ratio_m_to_mm;
	//Annual_Month_MM of 0 to 11 from ((SimulationDate_GD[timeStep] / 100) % 100) -1; where /100 removes days, %100 removes years, -1 indexes at 0
	Annual_Month_MM = ((input->SimulationDate_GD[timeStep] / 100) % 100) - 1;
	//Diurnal_Hour_HH of 0 to 23 hours from SimulationTime_HMS[] vector w stoi and substr functions, starting at 0, selecting 2 places	
	Diurnal_Hour_HH = stoi(input->SimulationTime_HMS[timeStep].substr(0, 2));

	//If Flag_CA_AH_Flux_Qcr_Qncr_not_Qtotal and Flag_CoolAir_AnthropogenicHeat_Flux are 1 then enter
	//Note: Flag_CA_AH_Flux_Qcr_Qncr_not_Qtotal with Qcr is commercial residential AH flux, and Qncr is non commercial residential AH flux
	//Note: AnthropogenicHeat_Flux_ComRes_Avg_Wpm2 and AnthropogenicHeat_Flux_NonCR_Avg_Wpm2 are read
	if (input->SimulationStringParams["Flag_CA_AH_Flux_Qcr_Qncr_not_Qtotal"] == "1" && input->SimulationStringParams["Flag_CoolAir_AnthropogenicHeat_Flux"] == "1") {
		//AnthropogenicHeat_Flux_Total_Avg_Wpm2[MapPixel_ID] = AnthropogenicHeat_Flux_ComRes_Avg_Wpm2[MapPixel_ID] + AnthropogenicHeat_Flux_NonCR_Avg_Wpm2[MapPixel_ID]
		//Note: AnthropogenicHeat_Flux_Total_Avg_Wpm2 is sum of AnthropogenicHeat_Flux_ComRes_Avg_Wpm2 and AnthropogenicHeat_Flux_NonCR_Avg_Wpm2 
		//Note: AnthropogenicHeat_Flux_ComRes_Avg_Wpm2 and AnthropogenicHeat_Flux_NonCR_Avg_Wpm2 set to 0 if Flag_CoolAir_AnthropogenicHeat_Flux != 1
		input->AnthropogenicHeat_Flux_Total_Avg_Wpm2[MapPixel_ID] = input->AnthropogenicHeat_Flux_ComRes_Avg_Wpm2[MapPixel_ID] + input->AnthropogenicHeat_Flux_NonCR_Avg_Wpm2[MapPixel_ID];
		//If Flag_CA_AH_Flux_Qcr_DegreeHour_Dependent then redefine AnthropogenicHeat_Flux_ComRes_Avg_Wpm2 based on degree hour generating building waste energy 
		//Note: Effect of degree hour on building waste energy is a simplification of detailed system behavior used to capture temporal variability in AHE
		if (input->SimulationStringParams["Flag_CA_AH_Flux_Qcr_DegreeHour_Dependent"] == "1") {
			//AnthropogenicHeat_Qcr_Climate_Wpm2 (W/m2) is AnthropogenicHeat_Flux_ComRes_Avg_Wpm2 * AH_Flux_Hour_Ratio[Diurnal_Hour_HH] * AH_Flux_Month_Ratio[Annual_Month_MM]
			//Note: AnthropogenicHeat_Flux_ComRes_Avg_Wpm2 is annual average value, and AH_Flux_Hour_Ratio scales it to hour, AH_Flux_Month_Ratio scales it to month
			//Note: AnthropogenicHeat_Flux_ComRes_Avg_Wpm2 is primarily commercial and residential heating and cooling, which can be influenced by tree cover scenario
			//Note: AnthropogenicHeat_Flux_ComRes_Avg_Wpm2 set to 0 if Flag_CoolAir_AnthropogenicHeat_Flux != 1
			//Note: Diurnal_Hour_HH ranges from 0 to 23, and [Diurnal_Month_MM] ranges from 0 to 11 when extracted above by using -1 
			double AnthropogenicHeat_Qcr_Climate_Wpm2 = input->AnthropogenicHeat_Flux_ComRes_Avg_Wpm2[MapPixel_ID] * input->AH_Flux_Hour_Ratio[Diurnal_Hour_HH] * input->AH_Flux_Month_Ratio[Annual_Month_MM];
			//Tair_threshold_K (K) is typiclly 291.483 K, based on 65 F (or 18.333 C) as average daily temperature for cooling and heating degree day threshold
			double Tair_Cooling_or_Heating_DegreeDay_Threshold_K = stod(input->TemperatureExecutionParams["DegreeHour_Threshold_K"]);
			//Climate_Year_Start_YYYY is stoi(TemperatureExecutionParams["DegreeHour_Year_Start"]), string of start year of time series for DegreeHour_Year_Ratio
			int Climate_Year_Start_YYYY = stoi(input->TemperatureExecutionParams["DegreeHour_Year_Start"]);
			//Climate_Year_index of 0 to # from int (SimulationDate_GD[timeStep] /10000) - Climate_Year_Start_YYYY
			int Climate_Year_index = int(input->SimulationDate_GD[timeStep] / 10000) - Climate_Year_Start_YYYY;

			//static once_flag set as negative_flag set for controlling entrance to cout
			static once_flag negative_flag;
			//If Climate_Year_index < 0 then set to 0 and alert user
			if (Climate_Year_index < 0) {
				Climate_Year_index = 0;
				call_once(negative_flag, []() {
					cout << "Note: The HydroPlusConfig.xml element DegreeHour_Year_Start exceeds StartDate_YYYYMMDD, indicating an error." << endl;
					cout << "Note: This inconsistency results in using the first value in HydroPlusConfig.xml element DegreeHour_Year_Ratio." << endl;
					});
			}
			//Climate_Year_index >= input->DegreeHour_Year_Ratio.size() then set to maximum value
			if (Climate_Year_index >= input->DegreeHour_Year_Cooling_Ratio.size()) {
				Climate_Year_index = input->DegreeHour_Year_Cooling_Ratio.size() - 1;
				call_once(negative_flag, []() {
					cout << "Note: The HydroPlusConfig.xml element DegreeHour_Year_Start precedes StopDate_YYYYMMDD, indicating an error." << endl;
					cout << "Note: This inconsistency results in using the last value in HydroPlusConfig.xml element DegreeHour_Year_Ratio." << endl;
					});
			}
			//Annual_Month_MM of 0 to 11 from ((SimulationDate_GD[timeStep] / 100) % 100) -1; where /100 removes days, %100 removes years, -1 indexes at 0
			Annual_Month_MM = ((input->SimulationDate_GD[timeStep] / 100) % 100) - 1;
			//Diurnal_Hour_HH of 0 to 23 hours from SimulationTime_HMS[] vector w stoi and substr functions, starting at 0, selecting 2 places	
			Diurnal_Hour_HH = stoi(input->SimulationTime_HMS[timeStep].substr(0, 2));
			//If timeStep > 0 then use Annual_Month_MM and Diurna_Hour_HH from prior timeStep to align with calculation of DegreeHour_Hour_Scenario
			if (timeStep > 0) {
				//Annual_Month_MM of 0 to 11 from ((SimulationDate_GD[timeStep] / 100) % 100) -1; where /100 removes days, %100 removes years, -1 indexes at 0
				Annual_Month_MM = ((input->SimulationDate_GD[timeStep - 1] / 100) % 100) - 1;
				//Diurnal_Hour_HH of 0 to 23 hours from SimulationTime_HMS[] vector w stoi and substr functions, starting at 0, selecting 2 places	
				Diurnal_Hour_HH = stoi(input->SimulationTime_HMS[timeStep - 1].substr(0, 2));
			}
			//Tair_K is ternary function of timeStep, if not 0 then folder Tair_K, else Tair_localCell_K or reffolder Tair_K
			double Tair_K = (timeStep != 0) ? folder->VarDict["Tair_K"] : Tair_localCell_K;

			//DegreeHour_Hour_Scenario is from model, abs(Tair_K - Tair_Cooling_or_Heating_DegreeDay_Threshold_K), absolute difference for cooling and heating
			//Note: Tair_K is from last time step, avoiding computational burden of computing it during this time step, given it is function of AHE
			//Note: Hourly rather than daily values are used to modify AHE for each hour which provides greater temporal resolution on heating and cooling
			double DegreeHour_Hour_Scenario = Tair_K - Tair_Cooling_or_Heating_DegreeDay_Threshold_K;

			//DegreeHour_Hour_Climate is initialized to zero, updated based on climate data, and is staggered to be one hour prior to align with model
			double DegreeHour_Hour_Climate = 0;
			//If DegreeHour_Hour_Scenario > 0 then Tair_K > Tair_Cooling_or_Heating_DegreeDay_Threshold_K and Cooling
			if (DegreeHour_Hour_Scenario > 0) {
				//DegreeHour_Hour_Climate = DegreeHour_Year_Cooling_Ratio * DegreeHour_Month_Cooling_Ratio * DegreeHour_Hour_Cooling_K
				//Note: Equation developed by Endreny after analyzing 10 yrs of hourly temperature data with the Tair_Cooling_or_Heating_DegreeDay_Threshold_K
				DegreeHour_Hour_Climate = input->DegreeHour_Year_Cooling_Ratio[Climate_Year_index] * input->DegreeHour_Month_Cooling_Ratio[Annual_Month_MM] * input->DegreeHour_Hour_Cooling_K[Diurnal_Hour_HH];
			}
			//Else If DegreeHour_Hour_Scenario < 0 then Tair_K < Tair_Cooling_or_Heating_DegreeDay_Threshold_K and Heating
			else if (DegreeHour_Hour_Scenario < 0) {
				//DegreeHour_Hour_Climate = DegreeHour_Year_Heating_Ratio * DegreeHour_Month_Heating_Ratio * DegreeHour_Hour_Heating_K
				//Note: Equation developed by Endreny after analyzing 10 yrs of hourly temperature data with the Tair_Cooling_or_Heating_DegreeDay_Threshold_K
				DegreeHour_Hour_Climate = input->DegreeHour_Year_Heating_Ratio[Climate_Year_index] * input->DegreeHour_Month_Heating_Ratio[Annual_Month_MM] * input->DegreeHour_Hour_Heating_K[Diurnal_Hour_HH];
			}

			//AnthropogenicHeat_Qcr_Scenario_Wpm2 = (DegreeHour_Hour_Scenario / DegreeHour_Hour_Climate) * AnthropogenicHeat_Qcr_Climate_Wpm2
			//Note: Formula based on weighted scaling of AnthropogenicHeat_Qcr_Climate_Wpm2
			double AnthropogenicHeat_Qcr_Scenario_Wpm2 = (DegreeHour_Hour_Scenario / DegreeHour_Hour_Climate) * AnthropogenicHeat_Qcr_Climate_Wpm2;

			//AnthropogenicHeat_Flux_Total_Avg_Wpm2[MapPixel_ID] = AnthropogenicHeat_Qcr_Scenario_Wpm2 + AnthropogenicHeat_Flux_NonCR_Avg_Wpm2[MapPixel_ID]
			//Note: AnthropogenicHeat_Flux_NonCR_Avg_Wpm2 set to 0 if Flag_CoolAir_AnthropogenicHeat_Flux != 1
			input->AnthropogenicHeat_Flux_Total_Avg_Wpm2[MapPixel_ID] = AnthropogenicHeat_Qcr_Scenario_Wpm2 + input->AnthropogenicHeat_Flux_NonCR_Avg_Wpm2[MapPixel_ID];
			//cte 2025 Consider refactor to alert user when DegreeHour_Hour_Scenario >> (DegreeHour_Hour_Climate and AHE is overadjusted
			if (DegreeHour_Hour_Scenario > (DegreeHour_Hour_Climate * 30)) {
				cout << "timeStep= " << timeStep << endl;
				cout << "DegreeHour_Hour_Scenario= " << DegreeHour_Hour_Scenario << endl;
				cout << "DegreeHour_Hour_Climate= " << DegreeHour_Hour_Climate << endl;
				cout << "AnthropogenicHeat_Qcr_Climate_Wpm2= " << AnthropogenicHeat_Qcr_Climate_Wpm2 << endl;
				cout << "AnthropogenicHeat_Qcr_Scenario_Wpm2= " << AnthropogenicHeat_Qcr_Scenario_Wpm2 << endl;
				cout << endl;
			}
		}
	}
	//If MapPixel_ReferenceStation_ID is MapPixel_ID then update reference station AnthropogenicHeat_Flux_Total_Avg_Wpm2
	if (input->MapPixel_ReferenceStation_ID == MapPixel_ID) {
		//If Flag_CoolAir_AnthropogenicHeat_Flux is 1 & RefWeatherLocationAH_Flux_Total_Avg_Wpm2 >= 0 then update map value with HydroPlusConfig.xml element
		//Note: Else the reference station AnthropogenicHeat_Flux_Total_Avg_Wpm2 will have the resampled (including Qcr+Qncr) or original map value of AHF total
		//Note: RefWeatherLocationAH_Flux_Total_Avg_Wpm2 is 0 when representing isolation of meteorological station from AHE, but depends on location
		if (input->SimulationStringParams["Flag_CoolAir_AnthropogenicHeat_Flux"] == "1" && input->TemperatureCalculationParams["RefWeatherLocationAH_Flux_Total_Avg_Wpm2"] >= 0) {
			//AnthropogenicHeat_Flux_Total_Avg_Wpm2[MapPixel_ReferenceStation_ID] = RefWeatherLocationAH_Flux_Total_Avg_Wpm2, often set to 0
			input->AnthropogenicHeat_Flux_Total_Avg_Wpm2[input->MapPixel_ReferenceStation_ID] = input->TemperatureCalculationParams["RefWeatherLocationAH_Flux_Total_Avg_Wpm2"];
		}
	}
	//AnthropogenicHeat_Flux_Total_Wpm2 (W/m2) is AnthropogenicHeat_Flux_Total_Avg_Wpm2 * AH_Flux_Hour_Ratio[Diurnal_Hour_HH] * AH_Flux_Month_Ratio[Annual_Month_MM]
	//Note: AnthropogenicHeat_Flux_Total_Avg_Wpm2 is annual average value, and AH_Flux_Hour_Ratio scales it to hour, AH_Flux_Month_Ratio scales it to month
	//Note: AnthropogenicHeat_Flux_Total_Avg_Wpm2 is total anthropogenic heat flux, containing Qcr (commercial and residential) and Qncr (non-cr)
	//Note: Diurnal_Hour_HH ranges from 0 to 23, and [Diurnal_Month_MM] ranges from 0 to 11 when extracted above by using -1 
	//Note: AnthropogenicHeat_Flux_Total_Avg_Wpm2 set to 0 if Flag_CoolAir_AnthropogenicHeat_Flux != 1
	//Note: Anthropogenic heat emission (W/m2) is generated and associated with land where vehicles, people, and buildings are placed
	//Note: Ward et al. (2016) demonstrated how anthropogenic heat is added to last coefficient in OHM w 
	//Note: Ward et al. (2016) developed Eq 5 with Table 3 coefficient values to predict annual variation in anthropogenic heat.
	AnthropogenicHeat_Flux_Total_Wpm2 = input->AnthropogenicHeat_Flux_Total_Avg_Wpm2[MapPixel_ID] * input->AH_Flux_Hour_Ratio[Diurnal_Hour_HH] * input->AH_Flux_Month_Ratio[Annual_Month_MM];

	//NLCD Class is 21
	if (LandCover_Class_NLCD == 21) {
		//Albedo_Urban_frac (fraction) is albedo of surface feature for reflecting shortwave radiation; 1 = perfect reflector, 0 = perfect absorber
		Albedo_Urban_frac = input->TemperatureCalculationParams["Albedo_Urban21_frac"];
		//Height_UrbanBuilding_m (m) is average height of surface feature, transformed later for roughness in turbulence exchange calculations
		Height_UrbanBuilding_m = input->TemperatureCalculationParams["Height_Avg_Urban21_m"];
		//Width_UrbanCanyon_m (m) is average width of surface feature for urban canyon calculations
		Width_UrbanCanyon_m = input->TemperatureCalculationParams["Width_Road_Urban21_m"];
		//Emissivity_Urban_frac (fraction) is emissivity of surface feature for emitting longwave radiation, 1 = perfect emission, 0 = no emission
		Emissivity_Urban_frac = input->TemperatureCalculationParams["Emissivity_Urban21_frac"];
		//Storage_Depression_Max_Impervious_m (m) is depth of storage for ponded water in folder surface, scaled from mm to m with Ratio_m_to_mm
		Storage_Depression_Max_Impervious_m = folder->ParamDict["ImperviousDepressionStorage_mm"] * Ratio_m_to_mm;
		//Building_Area_frac (fraction) is area of folder surface with buildings vs road; if TC > (1-Building_Area_frac), then TC is on roof
		Building_Area_frac = input->TemperatureCalculationParams["Area_Roof_Urban21_frac"];
		//a1_OHM_Urban_frac, a2_OHM_Urban_hr, a3_OHM_Urban_W_p_m2 are terms to compute ground heat storage based on net radiation and Eq 3 in Grimmond and Oke (1999) objective hysteresis model (OHM)
		a1_OHM_Urban_frac = input->TemperatureCalculationParams["a1_OHM_Urban21_frac"];
		a2_OHM_Urban_hr = input->TemperatureCalculationParams["a2_OHM_Urban21_hr"];
		a3_OHM_Urban_W_p_m2 = input->TemperatureCalculationParams["a3_OHM_Urban21_W_p_m2"];
	}
	//NLCD Class is 22
	if (LandCover_Class_NLCD == 22) {
		//Albedo_Urban_frac (fraction) is albedo of surface feature for reflecting shortwave radiation; 1 = perfect reflector, 0 = perfect absorber
		Albedo_Urban_frac = input->TemperatureCalculationParams["Albedo_Urban22_frac"];
		//Height_UrbanBuilding_m (m) is average height of surface feature, transformed later for roughness in turbulence exchange calculations
		Height_UrbanBuilding_m = input->TemperatureCalculationParams["Height_Avg_Urban22_m"];
		//Width_UrbanCanyon_m (m) is average width of surface feature for urban canyon calculations
		Width_UrbanCanyon_m = input->TemperatureCalculationParams["Width_Road_Urban22_m"];
		//Emissivity_Urban_frac (fraction) is emissivity of surface feature for emitting longwave radiation, 1 = perfect emission, 0 = no emission
		Emissivity_Urban_frac = input->TemperatureCalculationParams["Emissivity_Urban22_frac"];
		//Storage_Depression_Max_Impervious_m (m) is depth of storage for ponded water in folder surface, scaled from mm to m with Ratio_m_to_mm
		Storage_Depression_Max_Impervious_m = folder->ParamDict["ImperviousDepressionStorage_mm"] * Ratio_m_to_mm;
		//Building_Area_frac (fraction) is area of folder surface with buildings vs road; if TC > (1-Building_Area_frac), then TC is on roof
		Building_Area_frac = input->TemperatureCalculationParams["Area_Roof_Urban22_frac"];
		//a1_OHM_Urban_frac, a2_OHM_Urban_hr, a3_OHM_Urban_W_p_m2 are terms to compute ground heat storage based on net radiation and Eq 3 in Grimmond and Oke (1999) objective hysteresis model (OHM)
		a1_OHM_Urban_frac = input->TemperatureCalculationParams["a1_OHM_Urban22_frac"];
		a2_OHM_Urban_hr = input->TemperatureCalculationParams["a2_OHM_Urban22_hr"];
		a3_OHM_Urban_W_p_m2 = input->TemperatureCalculationParams["a3_OHM_Urban22_W_p_m2"];
	}
	//NLCD Class is 23
	if (LandCover_Class_NLCD == 23) {
		//Albedo_Urban_frac (fraction) is albedo of surface feature for reflecting shortwave radiation; 1 = perfect reflector, 0 = perfect absorber
		Albedo_Urban_frac = input->TemperatureCalculationParams["Albedo_Urban23_frac"];
		//Height_UrbanBuilding_m (m) is average height of surface feature, transformed later for roughness in turbulence exchange calculations
		Height_UrbanBuilding_m = input->TemperatureCalculationParams["Height_Avg_Urban23_m"];
		//Width_UrbanCanyon_m (m) is average width of surface feature for urban canyon calculations
		Width_UrbanCanyon_m = input->TemperatureCalculationParams["Width_Road_Urban23_m"];
		//Emissivity_Urban_frac (fraction) is emissivity of surface feature for emitting longwave radiation, 1 = perfect emission, 0 = no emission
		Emissivity_Urban_frac = input->TemperatureCalculationParams["Emissivity_Urban23_frac"];
		//Storage_Depression_Max_Impervious_m (m) is depth of storage for ponded water in folder surface, scaled from mm to m with Ratio_m_to_mm
		Storage_Depression_Max_Impervious_m = folder->ParamDict["ImperviousDepressionStorage_mm"] * Ratio_m_to_mm;
		//Building_Area_frac (fraction) is area of folder surface with buildings vs road; if TC > (1-Building_Area_frac), then TC is on roof
		Building_Area_frac = input->TemperatureCalculationParams["Area_Roof_Urban23_frac"];
		//a1_OHM_Urban_frac, a2_OHM_Urban_hr, a3_OHM_Urban_W_p_m2 are terms to compute ground heat storage based on net radiation and Eq 3 in Grimmond and Oke (1999) objective hysteresis model (OHM)
		a1_OHM_Urban_frac = input->TemperatureCalculationParams["a1_OHM_Urban23_frac"];
		a2_OHM_Urban_hr = input->TemperatureCalculationParams["a2_OHM_Urban23_hr"];
		a3_OHM_Urban_W_p_m2 = input->TemperatureCalculationParams["a3_OHM_Urban23_W_p_m2"];
	}
	//NLCD Class is 24
	if (LandCover_Class_NLCD == 24) {
		//Albedo_Urban_frac (fraction) is albedo of surface feature for reflecting shortwave radiation; 1 = perfect reflector, 0 = perfect absorber
		Albedo_Urban_frac = input->TemperatureCalculationParams["Albedo_Urban24_frac"];
		//Height_UrbanBuilding_m (m) is average height of surface feature, transformed later for roughness in turbulence exchange calculations
		Height_UrbanBuilding_m = input->TemperatureCalculationParams["Height_Avg_Urban24_m"];
		//Width_UrbanCanyon_m (m) is average width of surface feature for urban canyon calculations
		Width_UrbanCanyon_m = input->TemperatureCalculationParams["Width_Road_Urban24_m"];
		//Emissivity_Urban_frac (fraction) is emissivity of surface feature for emitting longwave radiation, 1 = perfect emission, 0 = no emission
		Emissivity_Urban_frac = input->TemperatureCalculationParams["Emissivity_Urban24_frac"];
		//Storage_Depression_Max_Impervious_m (m) is depth of storage for ponded water in folder surface, scaled from mm to m with Ratio_m_to_mm
		Storage_Depression_Max_Impervious_m = folder->ParamDict["ImperviousDepressionStorage_mm"] * Ratio_m_to_mm;
		//Building_Area_frac (fraction) is area of folder surface with buildings vs road; if TC > (1-Building_Area_frac), then TC is on roof
		Building_Area_frac = input->TemperatureCalculationParams["Area_Roof_Urban24_frac"];
		//a1_OHM_Urban_frac, a2_OHM_Urban_hr, a3_OHM_Urban_W_p_m2 are terms to compute ground heat storage based on net radiation and Eq 3 in Grimmond and Oke (1999) objective hysteresis model (OHM)
		a1_OHM_Urban_frac = input->TemperatureCalculationParams["a1_OHM_Urban24_frac"];
		a2_OHM_Urban_hr = input->TemperatureCalculationParams["a2_OHM_Urban24_hr"];
		a3_OHM_Urban_W_p_m2 = input->TemperatureCalculationParams["a3_OHM_Urban24_W_p_m2"];
	}

	//If NLCD Class < 21 or > 24 then not urban then set parameters for impervious without buildings
	//Note: Consider refactor to define for reference station the Height_UrbanBuilding_m, Width_UrbanCanyon_m and Building_Area_frac when Flag_simulateReferenceStation == 1
	if ((LandCover_Class_NLCD < 21 || LandCover_Class_NLCD > 24)) {
		//Albedo_Urban_frac (fraction) is albedo of surface feature for reflecting shortwave radiation; 1 = perfect reflector, 0 = perfect absorber
		Albedo_Urban_frac = input->TemperatureCalculationParams["Albedo_Urban21_frac"];
		//Height_UrbanBuilding_m (m) is set H = 0.25 m, height for impervious cover without buildings that yields 0.123 * H = roughness height = 0.03 m from Stull (2000) Table 4.1
		Height_UrbanBuilding_m = 0.25;
		//Width_UrbanCanyon_m (m) is average width of surface feature for urban canyon calculations
		Width_UrbanCanyon_m = input->TemperatureCalculationParams["Width_Road_Urban21_m"];
		//Emissivity_Urban_frac (fraction) is emissivity of surface feature for emitting longwave radiation, 1 = perfect emission, 0 = no emission
		Emissivity_Urban_frac = input->TemperatureCalculationParams["Emissivity_Urban21_frac"];
		//Storage_Depression_Max_Impervious_m (m) is depth of storage for ponded water in folder surface, scaled from mm to m with Ratio_m_to_mm
		Storage_Depression_Max_Impervious_m = folder->ParamDict["ImperviousDepressionStorage_mm"] * Ratio_m_to_mm;
		//Building_Area_frac (fraction) is set to zero for impervious cover without buildings
		Building_Area_frac = 0;
		//Building_Area_frac = input->TemperatureCalculationParams["Area_Roof_Urban21_frac"];
		//a1_OHM_Urban21_frac, a2_OHM_Urban21_hr, a3_OHM_Urban21_W_p_m2 are terms to compute ground heat storage based on net radiation and Eq 3 in Grimmond and Oke (1999) objective hysteresis model (OHM)
		a1_OHM_Urban_frac = input->TemperatureCalculationParams["a1_OHM_Urban21_frac"];
		a2_OHM_Urban_hr = input->TemperatureCalculationParams["a2_OHM_Urban21_hr"];
		a3_OHM_Urban_W_p_m2 = input->TemperatureCalculationParams["a3_OHM_Urban21_W_p_m2"];
	}

	//If (ImperviousCover_noTreeCanopy_frac + SoilCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac + WaterCover_noTreeCanopy_frac) <= Building_Area_frac then
	//Note: Algorithm is creating RoadArea_frac on under tree canopy if space is availble given Building_Area_frac
	if ((ImperviousCover_noTreeCanopy_frac + SoilCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac + WaterCover_noTreeCanopy_frac) < Building_Area_frac) {
		//RoadArea_frac equals zero
		RoadArea_frac = 0;
	}
	//Else If (ImperviousCover_noTreeCanopy_frac + SoilCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac + WaterCover_noTreeCanopy_frac) > Building_Area_frac then
	else {
		//RoadArea_frac equals (ImperviousCover_noTreeCanopy_frac + SoilCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac + WaterCover_noTreeCanopy_frac) - Building_Area_frac
		//Note: Algorithm is creating RoadArea_frac on under tree canopy if space is availble given Building_Area_frac
		RoadArea_frac = (ImperviousCover_noTreeCanopy_frac + SoilCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac + WaterCover_noTreeCanopy_frac) - Building_Area_frac;
	}

	//If Building_Area_frac < 1 then proceed to define ratios of ground based on cover
	if (Building_Area_frac < 1) {
		//Ratio_Road_to_Ground defined as RoadArea_frac / (1.0 - Building_Area_frac)
		//Ratio_Road_to_Ground is defined by TEB as ZRD = T%XROAD(JJ) / (T%XROAD(JJ)+T%XGARDEN(JJ))
		Ratio_Road_to_Ground = RoadArea_frac / (1.0 - Building_Area_frac);
		//Ratio_Garden_to_Ground defined as 1 - Ratio_Road_to_Ground
		Ratio_Garden_to_Ground = 1 - Ratio_Road_to_Ground;
	}
	//If Building_Area_frac = 1 then proceed to define ratios of ground as zero
	else {
		//Ratio_Road_to_Ground defined as zero given there is no ground
		Ratio_Road_to_Ground = 0;
		//Ratio_Garden_to_Ground defined as zero given there is no ground
		Ratio_Garden_to_Ground = 0;
	}	//Albedo_Roof_frac presumed equal to Albedo_Asphalt_frac, but this could be defined in HydroPlusConfig.xml for high albedo white or living green roofs

	Albedo_Roof_frac = Albedo_Asphalt_frac;
	//Emissivity_Roof_frac presumed equal to Emissivity_Asphalt_frac, but this could be defined in HydroPlusConfig.xml for high albedo white or living green roofs
	Emissivity_Roof_frac = Emissivity_Asphalt_frac;
	//Albedo_Road_frac presumed equal to Albedo_Asphalt_frac, but this could be defined in HydroPlusConfig.xml
	Albedo_Road_frac = Albedo_Asphalt_frac;
	//Emissivity_Road_frac presumed equal to Emissivity_Asphalt_frac, but this could be defined in HydroPlusConfig.xml
	Emissivity_Road_frac = Emissivity_Asphalt_frac;

	//If (TreeCover_frac + ShortVegCover_noTreeCanopy_frac) > 0 then enter for division
	if ((TreeCover_frac + ShortVegCover_noTreeCanopy_frac) > 0) {
		//Albedo_Garden_frac presumed fraction of tree cover and short vegetation cover, but this could be defined in HydroPlusConfig.xml
		Albedo_Garden_frac = (TreeCover_frac * Albedo_Tree_frac + ShortVegCover_noTreeCanopy_frac * Albedo_SVeg_frac) /
			(TreeCover_frac + ShortVegCover_noTreeCanopy_frac);
		//Emissivity_Garden_frac presumed fraction of tree cover and short vegetation cover, but this could be defined in HydroPlusConfig.xml
		Emissivity_Garden_frac = (TreeCover_frac * Emissivity_Tree_frac + ShortVegCover_noTreeCanopy_frac * Emissivity_SVeg_frac) /
			(TreeCover_frac + ShortVegCover_noTreeCanopy_frac);
	}
	//Else If (TreeCover_frac + ShortVegCover_noTreeCanopy_frac) <= 0 then define terms without division by zero
	else {
		//Albedo_Garden_frac presumed equal part tree cover and short vegetation cover, but this could be defined in HydroPlusConfig.xml
		Albedo_Garden_frac = (Albedo_Tree_frac + Albedo_SVeg_frac) / 2;
		//Emissivity_Garden_frac presumed equal part tree cover and short vegetation cover, but this could be defined in HydroPlusConfig.xml
		Emissivity_Garden_frac = (Emissivity_Tree_frac + Emissivity_SVeg_frac) / 2;
	}

	//Height_LandCover_Min_m (m) defined as 0.001 m
	double Height_LandCover_Min_m = 0.001;
	//Height_LandCover_Average_m (m) is weighted sum of tree cover and all other land cover types without tree cover
	//Note: Height_LandCover_Average_m is computed as simple average, not log based which would likely overemphasize influence of small heights
	//Note: Refactor Option: Create Height_PermeablePavement_m for PermeablePavementCover_noTreeCanopy_frac and ...
	//Note: Refactor Option: Create Height_ImpermeableCover_m as alternative to Height_UrbanBuilding_m
	Height_LandCover_Average_m = TreeCover_frac * Height_Tree_m + ShortVegCover_noTreeCanopy_frac * Height_SVeg_m +
		SoilCover_noTreeCanopy_frac * Height_Soil_m + PermeablePavementCover_noTreeCanopy_frac * Height_Soil_m + WaterCover_noTreeCanopy_frac * Height_Water_m + ImperviousCover_noTreeCanopy_frac * Height_UrbanBuilding_m;

	//If Height_LandCover_Average_m < Height_LandCover_Min_m (e.g., 0.001 m) then Height_LandCover_Average_m = Height_LandCover_Min_m
	//RoughnessLength_Water_m = 0.00137 m, based on roughness length (m) for water set to z0 = 0.00137 m Chin (2021) and Thom and Oliver (1977)
	//Note: Chin, D. A. (2021). Water Resources Engineering, Fourth Edition. Hoboken, NJ: Pearson Education.
	//Note: Thom, A. S., & Oliver, H. R. (1977). On Penman's equation for estimating regional evaporation. Quarterly Journal of the Royal Meteorological Society, 103(436), 345-357. doi:https://doi.org/10.1002/qj.49710343610
	if (Height_LandCover_Average_m < Height_LandCover_Min_m) { Height_LandCover_Average_m = Height_LandCover_Min_m; }

	//Component (S/Smax) of Eq 22 in Yang et al. (2013)
	//If Storage_per_LAI_BAI_Tree_m * LAI_BAI_Tree_m2pm2 > 0 then enter for division
	if (Storage_per_LAI_BAI_Tree_m * LAI_BAI_Tree_m2pm2 > 0) {
		//Saturation_TreeStorage_frac is function of Storage_per_LAI_BAI_Tree_m (LAI and BAI unit storage depth) and LAI_BAI_Tree_m2pm2
		Saturation_TreeStorage_frac = folder->VarDict["Storage_Rain_TreeCanopy_m"] / (Storage_per_LAI_BAI_Tree_m * LAI_BAI_Tree_m2pm2);
		//Saturation_TreeStorage_frac precision = 3 to maintain constant variable between same weather station in different quads when Flag_MultipleStation=1
		//Note: Without this control it seems a rounding error variation causes changes in subsequent LE and H calculations
		Saturation_TreeStorage_frac = static_cast<int>(Saturation_TreeStorage_frac * 1000) / 1000.0;
	}
	//Else If Storage_per_LAI_BAI_Tree_m * LAI_BAI_Tree_m2pm2 = 0 then there is no storage potential and set Saturation_TreeStorage_frac = 0
	else {
		Saturation_TreeStorage_frac = 0;
	}

	//Component (S/Smax) of Eq 22 in Yang et al. (2013)
	//If Storage_per_LAI_BAI_SVeg_m * LAI_BAI_SVeg_m2pm2 > 0 then enter for division
	if (Storage_per_LAI_BAI_SVeg_m * LAI_BAI_SVeg_m2pm2 > 0) {
		//Saturation_SVegStorage_frac is function of Storage_per_LAI_BAI_SVeg_m (LAI and BIA unit storage depth) and LAI_BAI_SVeg_m2pm2
		Saturation_SVegStorage_frac = folder->VarDict["Storage_Rain_SVegCanopy_m"] / (Storage_per_LAI_BAI_SVeg_m * LAI_BAI_SVeg_m2pm2);
		//Saturation_SVegStorage_frac precision = 3 to maintain constant variable between same weather station in different quads when Flag_MultipleStation=1
		//Note: Without this control it seems a rounding error variation causes changes in subsequent LE and H calculations
		Saturation_SVegStorage_frac = static_cast<int>(Saturation_SVegStorage_frac * 1000) / 1000.0;
	}
	//Else If Storage_per_LAI_BAI_Tree_m * LAI_BAI_Tree_m2pm2 = 0 then there is no storage potential and set Saturation_SVegStorage_frac = 0
	else {
		Saturation_SVegStorage_frac = 0;
	}															

	//Component [1-(D/Dmax)] of Eq 20 in Yang et al. (2013); available capillary held water in the soil for evaporation
	//If StorageDeficit_FieldCapacity_SoilEvapZone_Max_m (m) > zero then enter for division
	if (folder->VarDict["StorageDeficit_FieldCapacity_SoilEvapZone_Max_m"] > 0) {
		//Saturation_SoilStorage_frac (frac) ranges from 0=dry, 1=saturated; available water in the soil to evaporate; it equals [1-(D/Dmax)] in Eq 20 of Yang et al. (2013)
		//Note: StorageDeficit_FieldCapacity_SoilEvapZone_TI_m[] is vector with values indexed by topographic index; groundwater can enter the SoilEvapZone
		Saturation_SoilStorage_frac = 1 - (folder->VarVecDict["StorageDeficit_FieldCapacity_SoilEvapZone_TI_m"][0] /
			folder->VarDict["StorageDeficit_FieldCapacity_SoilEvapZone_Max_m"]);
		//Saturation_SoilStorage_frac precision = 3 to maintain constant variable between same weather station in different quads when Flag_MultipleStation=1
		//Note: Without this control it seems a rounding error variation causes changes in Resistance_Surface_SVeg_s_p_m and subsequent LE and H calculations
		Saturation_SoilStorage_frac = static_cast<int>(Saturation_SoilStorage_frac * 1000) / 1000.0;
	}
	//Else StorageDeficit_FieldCapacity_SoilEvapZone_Max_m (m) is zero, then there is no deficit and capillarity is filled and Saturation_SoilStorage_frac is 1
	else {
		//Saturation_SoilStorage_frac (frac) ranges from 0=dry, 1=saturated; available water in the soil to evaporate; it equals [1-(D/Dmax)] in Eq 20 of Yang et al. (2013)
		Saturation_SoilStorage_frac = 1;
	}

	//Algorithm to adjust a1, a2, and a3 coefficients in Objective Hysteresis Model for terms where ground heat flux depends on soil moisture
	//Note: Pre-adjustment for Naples, Italy along hippodrome on 2017071512 when soil moisture approached wilting point the ground heat flux was too low, ...
	//Note: ... and the ground heat flux coefficients a1, a2, a3 for soil, sveg and tree cover remained constant for all values of soil moisture, ...
	//Note: ... and in drought ground heat flux for soil, sveg and tree cover was much lower than ground heat flux for impervious cover, ...
	//Note: ... and this led to air temperature for soil, sveg and tree cover being higher than air temperature for impervious cover
	//Note: Adjustment of coefficients a1, a2, a3 for soil, sveg and tree increases their ground heat flux with lower soil moisture, approaching impervious 
	//Note: The rate of change in coefficients a1, a2, a3 is taken as Saturation_SoilStorage_frac ^ 0.5, which generates concave down curve, and ...
	//Note: ... small changes in coefficients a1, a2, a3 occur when the soil is > 50% wet, large changes occur when moisture approaches lower bound of 0
	//Note: Adjustment to coefficients a1, a2, and a3 for soil, sveg, and tree cover are identical, yet these could vary in a future refactor 

	//a1_OHM_Tree_ts_frac, a2_OHM_Tree_ts_hr, a3_OHM_Tree_ts_W_p_m2 initalized for ts, timestep
	double a1_OHM_Tree_ts_frac, a2_OHM_Tree_ts_hr, a3_OHM_Tree_ts_W_p_m2;
	double a1_OHM_SVeg_ts_frac, a2_OHM_SVeg_ts_hr, a3_OHM_SVeg_ts_W_p_m2;
	double a1_OHM_Soil_ts_frac, a2_OHM_Soil_ts_hr, a3_OHM_Soil_ts_W_p_m2;

	//If Saturation_SoilStorage_frac > 0 then take 0.5 power to update OHM coefficients a1, a2, a3
	if (Saturation_SoilStorage_frac > 0) {
		//a1_OHM_Tree_ts_frac = Saturation_SoilStorage_frac^0.5 * a1_OHM_Tree_frac + (1-Saturation_SoilStorage_frac^0.5) * a1_OHM_Urban_frac
		a1_OHM_Tree_ts_frac = pow(Saturation_SoilStorage_frac, 0.5) * a1_OHM_Tree_frac + (1 - pow(Saturation_SoilStorage_frac, 0.5)) * a1_OHM_Urban_frac;
		//a2_OHM_Tree_ts_hr = Saturation_SoilStorage_frac^0.5 * a2_OHM_Tree_ts_hr + (1-Saturation_SoilStorage_frac^0.5) * a2_OHM_Urban_hr
		a2_OHM_Tree_ts_hr = pow(Saturation_SoilStorage_frac, 0.5) * a2_OHM_Tree_hr + (1 - pow(Saturation_SoilStorage_frac, 0.5)) * a2_OHM_Urban_hr;
		//a3_OHM_Tree_ts_W_p_m2 = Saturation_SoilStorage_frac^0.5 * a3_OHM_Tree_W_p_m2 + (1-Saturation_SoilStorage_frac^0.5) * a3_OHM_Urban_W_p_m2
		a3_OHM_Tree_ts_W_p_m2 = pow(Saturation_SoilStorage_frac, 0.5) * a3_OHM_Tree_W_p_m2 + (1 - pow(Saturation_SoilStorage_frac, 0.5)) * a3_OHM_Urban_W_p_m2;

		//a1_OHM_SVeg_ts_frac = Saturation_SoilStorage_frac^0.5 * a1_OHM_SVeg_frac + (1-Saturation_SoilStorage_frac^0.5) * a1_OHM_Urban_frac
		a1_OHM_SVeg_ts_frac = pow(Saturation_SoilStorage_frac, 0.5) * a1_OHM_SVeg_frac + (1 - pow(Saturation_SoilStorage_frac, 0.5)) * a1_OHM_Urban_frac;
		//a2_OHM_SVeg_ts_hr = Saturation_SoilStorage_frac^0.5 * a2_OHM_SVeg_ts_hr + (1-Saturation_SoilStorage_frac^0.5) * a2_OHM_Urban_hr
		a2_OHM_SVeg_ts_hr = pow(Saturation_SoilStorage_frac, 0.5) * a2_OHM_SVeg_hr + (1 - pow(Saturation_SoilStorage_frac, 0.5)) * a2_OHM_Urban_hr;
		//a3_OHM_SVeg_ts_W_p_m2 = Saturation_SoilStorage_frac^0.5 * a3_OHM_SVeg_W_p_m2 + (1-Saturation_SoilStorage_frac^0.5) * a3_OHM_Urban_W_p_m2
		a3_OHM_SVeg_ts_W_p_m2 = pow(Saturation_SoilStorage_frac, 0.5) * a3_OHM_SVeg_W_p_m2 + (1 - pow(Saturation_SoilStorage_frac, 0.5)) * a3_OHM_Urban_W_p_m2;

		//a1_OHM_Soil_ts_frac = Saturation_SoilStorage_frac^0.5 * a1_OHM_Soil_frac + (1-Saturation_SoilStorage_frac^0.5) * a1_OHM_Urban_frac
		a1_OHM_Soil_ts_frac = pow(Saturation_SoilStorage_frac, 0.5) * a1_OHM_Soil_frac + (1 - pow(Saturation_SoilStorage_frac, 0.5)) * a1_OHM_Urban_frac;
		//a2_OHM_Soil_ts_hr = Saturation_SoilStorage_frac^0.5 * a2_OHM_Soil_ts_hr + (1-Saturation_SoilStorage_frac^0.5) * a2_OHM_Urban_hr
		a2_OHM_Soil_ts_hr = pow(Saturation_SoilStorage_frac, 0.5) * a2_OHM_Soil_hr + (1 - pow(Saturation_SoilStorage_frac, 0.5)) * a2_OHM_Urban_hr;
		//a3_OHM_Soil_ts_W_p_m2 = Saturation_SoilStorage_frac^0.5 * a3_OHM_Soil_W_p_m2 + (1-Saturation_SoilStorage_frac^0.5) * a3_OHM_Urban_W_p_m2
		a3_OHM_Soil_ts_W_p_m2 = pow(Saturation_SoilStorage_frac, 0.5) * a3_OHM_Soil_W_p_m2 + (1 - pow(Saturation_SoilStorage_frac, 0.5)) * a3_OHM_Urban_W_p_m2;
	}
	//Else Saturation_SoilStorage_frac = 0 and do not take 0.5 power, but use Saturation_SoilStorage_frac to update OHM coefficients a1, a2, a3
	//Note: This makes the tree, sveg, and soil OHM coefficients a1, a2, and a3 equate to urban OHM coefficients a1, a2, and a3 
	else {
		//a1_OHM_Tree_ts_frac = Saturation_SoilStorage_frac * a1_OHM_Tree_frac + (1-Saturation_SoilStorage_frac) * a1_OHM_Urban_frac
		a1_OHM_Tree_ts_frac = Saturation_SoilStorage_frac * a1_OHM_Tree_frac + (1 - Saturation_SoilStorage_frac) * a1_OHM_Urban_frac;
		//a2_OHM_Tree_ts_hr = Saturation_SoilStorage_frac * a2_OHM_Tree_ts_hr + (1-Saturation_SoilStorage_frac) * a2_OHM_Urban_hr
		a2_OHM_Tree_ts_hr = Saturation_SoilStorage_frac * a2_OHM_Tree_hr + (1 - Saturation_SoilStorage_frac) * a2_OHM_Urban_hr;
		//a3_OHM_Tree_ts_W_p_m2 = Saturation_SoilStorage_frac * a3_OHM_Tree_W_p_m2 + (1-Saturation_SoilStorage_frac) * a3_OHM_Urban_W_p_m2
		a3_OHM_Tree_ts_W_p_m2 = Saturation_SoilStorage_frac * a3_OHM_Tree_W_p_m2 + (1 - Saturation_SoilStorage_frac) * a3_OHM_Urban_W_p_m2;

		//a1_OHM_SVeg_ts_frac = Saturation_SoilStorage_frac * a1_OHM_SVeg_frac + (1-Saturation_SoilStorage_frac) * a1_OHM_Urban_frac
		a1_OHM_SVeg_ts_frac = Saturation_SoilStorage_frac * a1_OHM_SVeg_frac + (1 - Saturation_SoilStorage_frac) * a1_OHM_Urban_frac;
		//a2_OHM_SVeg_ts_hr = Saturation_SoilStorage_frac * a2_OHM_SVeg_ts_hr + (1-Saturation_SoilStorage_frac) * a2_OHM_Urban_hr
		a2_OHM_SVeg_ts_hr = Saturation_SoilStorage_frac * a2_OHM_SVeg_hr + (1 - Saturation_SoilStorage_frac) * a2_OHM_Urban_hr;
		//a3_OHM_SVeg_ts_W_p_m2 = Saturation_SoilStorage_frac * a3_OHM_SVeg_W_p_m2 + (1-Saturation_SoilStorage_frac) * a3_OHM_Urban_W_p_m2
		a3_OHM_SVeg_ts_W_p_m2 = Saturation_SoilStorage_frac * a3_OHM_SVeg_W_p_m2 + (1 - Saturation_SoilStorage_frac) * a3_OHM_Urban_W_p_m2;

		//a1_OHM_Soil_ts_frac = Saturation_SoilStorage_frac * a1_OHM_Soil_frac + (1-Saturation_SoilStorage_frac) * a1_OHM_Urban_frac
		a1_OHM_Soil_ts_frac = Saturation_SoilStorage_frac * a1_OHM_Soil_frac + (1 - Saturation_SoilStorage_frac) * a1_OHM_Urban_frac;
		//a2_OHM_Soil_ts_hr = Saturation_SoilStorage_frac * a2_OHM_Soil_ts_hr + (1-Saturation_SoilStorage_frac) * a2_OHM_Urban_hr
		a2_OHM_Soil_ts_hr = Saturation_SoilStorage_frac * a2_OHM_Soil_hr + (1 - Saturation_SoilStorage_frac) * a2_OHM_Urban_hr;
		//a3_OHM_Soil_ts_W_p_m2 = Saturation_SoilStorage_frac * a3_OHM_Soil_W_p_m2 + (1-Saturation_SoilStorage_frac) * a3_OHM_Urban_W_p_m2
		a3_OHM_Soil_ts_W_p_m2 = Saturation_SoilStorage_frac * a3_OHM_Soil_W_p_m2 + (1 - Saturation_SoilStorage_frac) * a3_OHM_Urban_W_p_m2;
	}

	//cte 2024 Refactor to replace w explanation of Height_Water_m or Height_Avg_WaterCover_m = 0.002 vs 0.001, and less so 
	//Saturation_WaterStorage_frac (frac) is used to regulate energy available for sensible and latent energy fluxes
	//Note: Flag_Water_Diurnal_pattern can adjust Saturation_WaterStorage_frac, but is not incorporated into HydroPlusConfig.xml TestCases or used in projects
	//Note: While water might be assigned Saturation_WaterStorage_frac=1 to represent saturated, this term can vary to better diurnal patterns noted in NOAA buoy data 
	//Note: NOAA buoy data from stations below seem to report effects of offshore and onshore breezes, e.g., land and sea breeze, ....
	//Note: ... with air temperature above water warmer than land around sunrise and sunset, and air temperature above water cooler than land around solar noon
	//Note: NOAA buoy Station WASD2 8594900 data for Washington, DC, Potomac River, Coordinates: 38.873 N 77.021 W; Air temp height: 2.6 m above site elevation, August 28, 2018
	//Note: NOAA buoy Station BLTM2 8574680 data for Baltimore, MD, Patapsco River, Coordinates: 39.267 N 76.579 W; Air temp height: 6.4 m above site elevation, August 29, 2018
	//Note: NOAA buoy Station FSKM2 8574728 data for Baltimore, MD, Baltimore Harbor, Coordinates: 39.219 N 76.528 W; Air temp height: 6.1 m above site elevation, August 29, 2018
	//Note: Water_Diurnal_max_frac=0.2, Water_Diurnal_min_frac=0.01, Saturation_WaterStorage_max_hr=15 for NOAA buoy Station WASD2 
	//Note: Water_Diurnal_max_frac=0.1, Water_Diurnal_min_frac=0.01, Saturation_WaterStorage_max_hr=15 for NOAA buoy Station BLTM2 

	//Saturation_WaterStorage_frac (frac) defined as 1, as the value of the evaporative flux coefficient
	Saturation_WaterStorage_frac = 1;
	//If Flag_Water_Diurnal_pattern equals 1 then modulate Saturation_WaterStorage_frac using a sine wave function
	//Note: Flag_Water_Diurnal_pattern is not incorporated into any HydroPlusConfig.xml TestCases or used in projects
	if (Flag_Water_Diurnal_pattern == 1) {
		//Saturation_WaterStorage_max_hr (hr) is the maximum thickness time from midnight, hr = 0, estimated at 15hr
		//Note: This should be based on solar radiation, sensible heat flux, temperature and windspeed
		double Saturation_WaterStorage_max_hr = 15;
		//SinWave_Coeff_A_m is the amplitude of the wave, defined as A = (Water_Diurnal_max_frac - Water_Diurnal_min_frac)/2
		double SinWave_Coeff_A_frac = (Water_Diurnal_max_frac - Water_Diurnal_min_frac) / 2;
		//SineWave_Coeff_B_hr is the frequency of the wave, defined as B = 2π / 24, based on two pi equals 360 degrees, and 24 hours in day
		double SineWave_Coeff_B_hr = 2.0 * M_PI / Ratio_Hour_to_Day;
		//SineWave_Coeff_C_hr is the horizontal shift to align the peak with Diurnal_Hour_HH, defined as C = Saturation_WaterStorage_max_hr - (π/ (2 * B))
		double SineWave_Coeff_C_hr = Saturation_WaterStorage_max_hr - (M_PI / (2.0 * SineWave_Coeff_B_hr));
		//SineWave_Coeff_D_m is the vertical shift of the wave, defined as D = (height_max + height_min) / 2
		double SineWave_Coeff_D_frac = (Water_Diurnal_max_frac - Water_Diurnal_min_frac) / 2;
		//Saturation_WaterStorage_frac (frac) is the value of the evaporative flux coefficient, defined as = abs[A * sin(B * (Diurnal_Hour_HH - C)) + D + Water_Diurnal_min_frac]
		//Note: Sine wave function to simplify representation of the ABL development, where Diurnal_Hour_HH defined in HeatFluxCal::EnergyFlux_WaterFlux_DefineTerms
		Saturation_WaterStorage_frac = abs(SinWave_Coeff_A_frac * sin(SineWave_Coeff_B_hr * (Diurnal_Hour_HH - SineWave_Coeff_C_hr)) + SineWave_Coeff_D_frac + Water_Diurnal_min_frac);
		//If Saturation_WaterStorage_frac > 1 then set to 1, the maximum value for releasing water for evaporation
		if (Saturation_WaterStorage_frac > 1 || Saturation_WaterStorage_frac <= 0) { Saturation_WaterStorage_frac = 1; }
	}

	//Component (S/Smax) of Eq 19 in Yang et al. (2013)
	//If Storage_Depression_Max_Impervious_m > 0 then enter for division
	if (Storage_Depression_Max_Impervious_m > 0) {
		//Note: Reformulated to reduce overestimates of LE flux when wet, as observed for Karlsruhe, Germany July 7, 2017 at 16:00
		//Note: If Coefficient_ConvertStorageToFluxOnImpArea = 0.02 used, then scenarios where IC is changed should avoid Tair_IC_0% > Tair_IC_2% 
		//Saturation_ImperviousStorage_frac (fraction) is Coefficient_ConvertStorageToFluxOnImpArea * S/Smax of Eq 19 in Yang et al. (2013)
		double Coefficient_ConvertStorageToFluxOnImpArea = 0.02;
		Saturation_ImperviousStorage_frac = Coefficient_ConvertStorageToFluxOnImpArea * (folder->VarDict["Storage_ImperviousPondedWater_m"] / Storage_Depression_Max_Impervious_m);
		//Note: Original Eq used in PASATH and i-Tree Cool Air through June 2023 is archived on the next lines
		//Saturation_ImperviousStorage_frac (fraction) is variable S/Smax of Eq 19 in Yang et al. (2013)
		//Saturation_ImperviousStorage_frac = folder->VarDict["Storage_ImperviousPondedWater_m"] / Storage_Depression_Max_Impervious_m;
	}
	//Else If Storage_Depression_Max_Impervious_m = 0 then there is no storage potential and set Saturation_ImperviousStorage_frac = 0
	else {
		Saturation_ImperviousStorage_frac = 0;
	}

	//If Storage_PerviousPondedWater_m <= Storage_Depression_Max_Pervious_m and Storage_Depression_Max_Pervious_m > 0 then enter for division
	if (folder->VarDict["Storage_PerviousPondedWater_m"] <= Storage_Depression_Max_Pervious_m && Storage_Depression_Max_Pervious_m > 0) {
		//Saturation_PerviousStorage_frac (fraction) is variable S/Smax of Eq 19 in Yang et al. (2013)
		Saturation_PerviousStorage_frac = folder->VarDict["Storage_PerviousPondedWater_m"] / Storage_Depression_Max_Pervious_m;
	}
	//Else If Storage_PerviousPondedWater_m > Storage_Depression_Max_Pervious_m and Storage_Depression_Max_Pervious_m > 0 then Saturation_PerviousStorage_frac = 1
	else if (folder->VarDict["Storage_PerviousPondedWater_m"] > Storage_Depression_Max_Pervious_m && Storage_Depression_Max_Pervious_m > 0) {
		//Saturation_PerviousStorage_frac (fraction) is variable S/Smax of Eq 19 in Yang et al. (2013)
		Saturation_PerviousStorage_frac = 1;
	}
	//Else Storage_Depression_Max_Pervious_m = 0 then there is no storage potential and set Saturation_PerviousStorage_frac = 0
	else {
		Saturation_PerviousStorage_frac = 0;
	}

	//AerodynamicResistance_OpenArea function calculate rural canopy flux resistance
	//Note: resistanceVar is the ResistanceCal class and new instance of this class: Resistance_Aerodynamic_Tree_s_p_m, Resistance_Aerodynamic_SVeg_s_p_m, Resistance_Aerodynamic_Impervious_s_p_m, Resistance_Aerodynamic_Soil_s_p_m, Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m, Resistance_Surface_Soil_s_p_m, Resistance_Surface_Tree_s_p_m, Resistance_Surface_SVeg_s_p_m
	resistanceVar->AerodynamicResistance_OpenArea(input, folder, MapPixel_ID, WindSpeed_Reference_m_p_s, LAI_Tree_m2pm2, LAI_SVeg_m2pm2, Height_LandCover_Average_m, timeStep);

	//SurfaceResistance_LandCover function calculate flux resistance that depends on water content
	//Note: resistanceVar is the ResistanceCal class and new instance of this class: Resistance_Aerodynamic_Tree_s_p_m, Resistance_Aerodynamic_SVeg_s_p_m, Resistance_Aerodynamic_Impervious_s_p_m, Resistance_Aerodynamic_Soil_s_p_m, Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m, Resistance_Surface_Soil_s_p_m, Resistance_Surface_Tree_s_p_m, Resistance_Surface_SVeg_s_p_m
	resistanceVar->SurfaceResistance_LandCover(folder, MapPixel_ID, Saturation_SoilStorage_frac, LAI_Tree_m2pm2, LAI_SVeg_m2pm2);

	//solarCalculator->SolarCalculator_Inputs computes Cos_IncidenceAngle_Solar, ZenithAngle_Solar_rad, AzimuthAngle_Solar_N_0_rad 
	solarCalculator->SolarCalculator_Inputs(input, folder, Weatherpre, StationID_string, MapPixel_ID, timeStep, Flag_simulateReferenceStation);
	//Define Cos_IncidenceAngle_Solar, ZenithAngle_Solar_rad, AzimuthAngle_Solar_N_0_rad using folder-> terms from SolarCalculator_Inputs
	//Note: Terms are specific to MapPixel_ID when Flag_LatitudeLongitude_Computed is true
	Cos_IncidenceAngle_Solar = folder->VarDict["Cos_IncidenceAngle_Solar"];
	ZenithAngle_Solar_rad = folder->VarDict["ZenithAngle_Solar_rad"];
	AzimuthAngle_Solar_N_0_rad = folder->VarDict["AzimuthAngle_Solar_N_0_rad"];


	//If Flag_MultipleStation is true and Flag_simulateReferenceStation is true then read in Weatherpre-> reference station meteorological variables for flux calculations
	if (input->SimulationStringParams["Flag_MultipleStation"] == "1" && Flag_simulateReferenceStation == 1) {
		keynamepart1 = StationID_string;//station ID
		keyname_Radiation_ShortWave_Direct_W_p_m2 = keynamepart1 + "_" + "Radiation_Shortwave_Direct_Wpm2";
		keyname_Radiation_Shortwave_Diffuse_W_p_m2 = keynamepart1 + "_" + "Radiation_Shortwave_Diffuse_Wpm2";
		//keyname_ImpNR_priorTS_W_p_m2 created at each loop of StationID_string (Imp and associated land cover types)
		keyname_ImpNR_priorTS_W_p_m2 = keynamepart1 + "_" + "ImpNR_priorTS_W_p_m2";
		keyname_TreeNR_priorTS_W_p_m2 = keynamepart1 + "_" + "TreeNR_priorTS_W_p_m2";
		keyname_SVegNR_priorTS_W_p_m2 = keynamepart1 + "_" + "SVegNR_priorTS_W_p_m2";
		keyname_SoilNR_priorTS_W_p_m2 = keynamepart1 + "_" + "SoilNR_priorTS_W_p_m2";
		keyname_WaterNR_priorTS_W_p_m2 = keynamepart1 + "_" + "WaterNR_priorTS_W_p_m2";
		keyname_RoofNR_priorTS_W_p_m2 = keynamepart1 + "_" + "RoofNR_priorTS_W_p_m2";

		//Radiation_Shortwave_W_p_m2 (W/m2) from Eq 25 in Yang et al. (2013), where direct SW is reduced by cosine solar incidence angle, referencing Kumar et al. (1997)
		Radiation_Shortwave_W_p_m2 = Weatherpre->RadiationMap[keyname_Radiation_ShortWave_Direct_W_p_m2][timeStep] * Cos_IncidenceAngle_Solar + Weatherpre->RadiationMap[keyname_Radiation_Shortwave_Diffuse_W_p_m2][timeStep];
		Radiation_Shortwave_Direct_W_p_m2 = Weatherpre->RadiationMap[keyname_Radiation_ShortWave_Direct_W_p_m2][timeStep] * Cos_IncidenceAngle_Solar;
		Radiation_Shortwave_Diffuse_W_p_m2 = Weatherpre->RadiationMap[keyname_Radiation_Shortwave_Diffuse_W_p_m2][timeStep];

		//NR_vec_size is the net radiation vector size to store prior NR values used in computing an average
		int NR_vec_size = 6;
		//ImpNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, ImpNR_priorTS_W_p_m2_vec, folder->VarDict["ImpNR_W_p_m2"]);
		//Note: NetRadiation_Prior_Calc function will return prior NR value based on average of vector length 
		ImpNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, ImpNR_priorTS_W_p_m2_vec, NR_priorTS_W_p_m2_Map[keyname_ImpNR_priorTS_W_p_m2]);
		TreeNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, TreeNR_priorTS_W_p_m2_vec, NR_priorTS_W_p_m2_Map[keyname_TreeNR_priorTS_W_p_m2]);
		SVegNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, SVegNR_priorTS_W_p_m2_vec, NR_priorTS_W_p_m2_Map[keyname_SVegNR_priorTS_W_p_m2]);
		SoilNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, SoilNR_priorTS_W_p_m2_vec, NR_priorTS_W_p_m2_Map[keyname_SoilNR_priorTS_W_p_m2]);
		WaterNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, WaterNR_priorTS_W_p_m2_vec, NR_priorTS_W_p_m2_Map[keyname_WaterNR_priorTS_W_p_m2]);
		RoofNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, RoofNR_priorTS_W_p_m2_vec, NR_priorTS_W_p_m2_Map[keyname_RoofNR_priorTS_W_p_m2]);


		//If timeStep > 0 then prior values of ImpNR_priorTS_W_p_m2 (W/m2) for Imp and associated land cover types exist
		//Note: Otherwise the variables are initalized to zero in HeatFluxCal.h
		if (timeStep > 0) {
			//ImpNR_priorTS_W_p_m2 (W/m2) for key keyname_ImpNR_priorTS_W_p_m2 is assigned NR_priorTS_W_p_m2_Map value for the prior time step (Imp and associated land cover types)
			ImpNR_priorTS_W_p_m2 = NR_priorTS_W_p_m2_Map[keyname_ImpNR_priorTS_W_p_m2];
			TreeNR_priorTS_W_p_m2 = NR_priorTS_W_p_m2_Map[keyname_TreeNR_priorTS_W_p_m2];
			SVegNR_priorTS_W_p_m2 = NR_priorTS_W_p_m2_Map[keyname_SVegNR_priorTS_W_p_m2];
			SoilNR_priorTS_W_p_m2 = NR_priorTS_W_p_m2_Map[keyname_SoilNR_priorTS_W_p_m2];
			WaterNR_priorTS_W_p_m2 = NR_priorTS_W_p_m2_Map[keyname_WaterNR_priorTS_W_p_m2];
			RoofNR_priorTS_W_p_m2 = NR_priorTS_W_p_m2_Map[keyname_RoofNR_priorTS_W_p_m2];
		}
	}
	//Else If Flag_MultipleStation and Flag_simulateReferenceStation are false then read in in input-> reference station meteorological variables for flux calculations
	else {
		//Radiation_Shortwave_W_p_m2 (W/m2) from Eq 25 in Yang et al. (2013), where direct SW is reduced by cosine solar incidence angle, referencing Kumar et al. (1997)
		Radiation_Shortwave_W_p_m2 = input->Radiation_Shortwave_Direct_Wpm2[timeStep] * Cos_IncidenceAngle_Solar + input->Radiation_Shortwave_Diffuse_Wpm2[timeStep];
		Radiation_Shortwave_Direct_W_p_m2 = input->Radiation_Shortwave_Direct_Wpm2[timeStep] * Cos_IncidenceAngle_Solar;
		Radiation_Shortwave_Diffuse_W_p_m2 = input->Radiation_Shortwave_Diffuse_Wpm2[timeStep];

		//NR_vec_size is the net radiation vector size to store prior NR values used in computing an average
		int NR_vec_size = 6;
		//ImpNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, ImpNR_priorTS_W_p_m2_vec, folder->VarDict["ImpNR_W_p_m2"]);
		//Note: NetRadiation_Prior_Calc function will return prior NR value based on average of vector length 
		ImpNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, ImpNR_priorTS_W_p_m2_vec, folder->VarDict["ImpNR_W_p_m2"]);
		TreeNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, TreeNR_priorTS_W_p_m2_vec, folder->VarDict["TreeNR_W_p_m2"]);
		SVegNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, SVegNR_priorTS_W_p_m2_vec, folder->VarDict["SVegNR_W_p_m2"]);
		SoilNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, SoilNR_priorTS_W_p_m2_vec, folder->VarDict["SoilNR_W_p_m2"]);
		WaterNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, WaterNR_priorTS_W_p_m2_vec, folder->VarDict["WaterNR_W_p_m2"]);
		RoofNR_priorTS_W_p_m2 = NetRadiation_Prior_Calc(timeStep, NR_vec_size, RoofNR_priorTS_W_p_m2_vec, folder->VarDict["RoofNR_W_p_m2"]);

			/*
			//ImpNR_priorTS_W_p_m2 (W/m2) assigned VarDict["ImpNR_W_p_m2"] (or Tree, SVeg, Soil, Water, Roof) value for prior time step 
			ImpNR_priorTS_W_p_m2 = folder->VarDict["ImpNR_W_p_m2"];
			TreeNR_priorTS_W_p_m2 = folder->VarDict["TreeNR_W_p_m2"];
			SVegNR_priorTS_W_p_m2 = folder->VarDict["SVegNR_W_p_m2"];
			SoilNR_priorTS_W_p_m2 = folder->VarDict["SoilNR_W_p_m2"];
			WaterNR_priorTS_W_p_m2 = folder->VarDict["WaterNR_W_p_m2"];
			RoofNR_priorTS_W_p_m2 = folder->VarDict["RoofNR_W_p_m2"];
			*/
	}

	//Control for negative values
	if (Radiation_Shortwave_W_p_m2 < 0) { Radiation_Shortwave_W_p_m2 = 0; }
	if (Radiation_Shortwave_Direct_W_p_m2 < 0) { Radiation_Shortwave_Direct_W_p_m2 = 0; }
	if (Radiation_Shortwave_Diffuse_W_p_m2 < 0) { Radiation_Shortwave_Diffuse_W_p_m2 = 0; }

	//If NLCD Class > 20 or < 25 then urban land cover classes with parameters for urban canyon geometry
	//Note: Urban class 21 condition when Flag_simulateReferenceStation > 0 addressed below
	if ((LandCover_Class_NLCD > 20) && (LandCover_Class_NLCD < 25)) {
		//Count_CanyonWalls defined as two for urban canyon
		Count_CanyonWalls = 2;
		//AspectRatio_Canyon_frac is urban height to width ratio of urban canyon, affecting energy balance
		AspectRatio_Canyon_frac = Height_UrbanBuilding_m / Width_UrbanCanyon_m;

		//If AspectRatio_Canyon_frac > 0 then divide by term
		if (AspectRatio_Canyon_frac > 0) {
			//SkyViewFactor_Road_frac or SkyViewFactor_Garden_frac from Eq 9 of Masson (2000), Eq 30b Lee and Park (2008)
			//Note: AspectRatio_Canyon_frac and SkyViewFactor_Road_frac pairs: 0.1->0.90, 0.5->0.62, 0.8->0.48, 1.2->0.36
			SkyViewFactor_Road_frac = sqrt(AspectRatio_Canyon_frac * AspectRatio_Canyon_frac + 1) - AspectRatio_Canyon_frac;
			SkyViewFactor_Garden_frac = SkyViewFactor_Road_frac;
			//SkyViewFactor_Wall_frac from Eq 10 of Masson (2000), Eq 30a Lee and Park (2008)
			//Note: AspectRatio_Canyon_frac and SkyViewFactor_Wall_frac pairs: 0.1->0.47, 0.5->0.38, 0.8->0.32, 1.2->0.27
			SkyViewFactor_Wall_frac = 0.5 * (AspectRatio_Canyon_frac + 1 - sqrt(AspectRatio_Canyon_frac * AspectRatio_Canyon_frac + 1)) / AspectRatio_Canyon_frac;
		}
		//Else If AspectRatio_Canyon_frac <= 0 then define Sky View Factors by open area
		else {
			//SkyViewFactor_Wall_frac equals SkyViewFactor_Ground_Wall_frac
			SkyViewFactor_Wall_frac = SkyViewFactor_Ground_Wall_frac;
			//SkyViewFactor_Road_frac equals SkyViewFactor_Ground_Open_frac
			SkyViewFactor_Road_frac = SkyViewFactor_Ground_Open_frac;
			//SkyViewFactor_Road_frac equals SkyViewFactor_Ground_Open_frac
			SkyViewFactor_Garden_frac = SkyViewFactor_Ground_Open_frac;
		}

		//Call HeatFluxCal::UrbanCanyon_RadiationShortwave to compute urban canyon effects on direct and diffuse shortwave radiation balance
		HeatFluxCal::UrbanCanyon_RadiationShortwave(input, folder, MapPixel_ID, Flag_UrbanCanyonResistance, timeStep);
		//Call HeatFluxCal::UrbanCanyon_RadiationLongwave to compute urban canyon effects on longwave radiation balance
		HeatFluxCal::UrbanCanyon_RadiationLongwave(input, folder, MapPixel_ID, Flag_UrbanCanyonResistance, timeStep);

		//cte 2024 Refactor Radiation_Longwave_Up_W_p_m2 as function of tree cover and impervious cover
		//Note: Could potentially use Diurnal_Hour_HH to turn function on and off
		//Note: This should also be called for cases when NLCD is not 21 to 24
		bool Flag_NightTime_fix = 0;
		double RadiationTrapped_frac = 0.8;
		if (Flag_NightTime_fix == 1 && Flag_simulateReferenceStation != 1 && Radiation_Shortwave_W_p_m2 == 0) {
			//Radiation_Longwave_Up_W_p_m2 = Radiation_Longwave_Up_W_p_m2 * (1 - (0.5 * TreeCover_frac))
			//Note: Reduce Radiation_Longwave_Up_W_p_m2 due to trapping by tree canopy
			if (timeStep > 17 && TreeCover_frac > 0.2 && LandCover_Class_NLCD == 23) {
				cout << "A HFCal Radiation_Longwave_Net_Tree_W_p_m2 = " << Radiation_Longwave_Net_Tree_W_p_m2 << endl;
			}
			Radiation_Longwave_Up_W_p_m2 = Radiation_Longwave_Up_W_p_m2 * (1 - (RadiationTrapped_frac * TreeCover_frac));
			Radiation_Longwave_Net_Tree_W_p_m2 = Radiation_Longwave_Net_Tree_W_p_m2 * (1 - (RadiationTrapped_frac * TreeCover_frac));
			if (timeStep > 17 && TreeCover_frac > 0.2 && LandCover_Class_NLCD == 23) {
				cout << "B HFCal Radiation_Longwave_Net_Tree_W_p_m2 = " << Radiation_Longwave_Net_Tree_W_p_m2 << endl;
				cout << "B HFCal TreeCover_frac = " << TreeCover_frac << " fix = " << (1 - (RadiationTrapped_frac * TreeCover_frac)) << endl;
			}
		}

		//If Flag_UrbanCanyonResistance equals 1 then define resistances using AerodynamicResistance_UrbanCanyon function
		//Note: This is not completely developed function, and may erroneously constrain range of air temperature across tree cover and impervious cover gradients
		//Note: Consider refactor to change Flag_UrbanCanyonResistance to Threshold_AspectRatio_Canyon_frac to enter this calculation, as aspect ratio controls the resistances
		if (Flag_UrbanCanyonResistance == 1) {
			//AerodynamicResistance_UrbanCanyon function calculate urban canopy flux resistance
			//Note: resistanceVar is the ResistanceCal class and new instance of this class: Resistance_Aerodynamic_Tree_s_p_m, Resistance_Aerodynamic_SVeg_s_p_m, Resistance_Aerodynamic_Impervious_s_p_m, Resistance_Aerodynamic_Soil_s_p_m, Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m, Resistance_Surface_Soil_s_p_m, Resistance_Surface_Tree_s_p_m, Resistance_Surface_SVeg_s_p_m
			resistanceVar->AerodynamicResistance_UrbanCanyon(input, folder, MapPixel_ID, WindSpeed_Reference_m_p_s, LAI_Tree_m2pm2, LAI_SVeg_m2pm2, AspectRatio_Canyon_frac, Height_LandCover_Average_m);
		}

		//ImpNR_W_p_m2 (W/m2) modified form of Eq 24 from Yang et al (2013) to use urban canyon estimates of radiation, with net longwave radiation
		ImpNR_W_p_m2 = (Radiation_Shortwave_Direct_Diffuse_Road_W_p_m2 + Count_CanyonWalls * Radiation_Shortwave_Direct_Diffuse_Wall_W_p_m2) * (1 - Albedo_Urban_frac) + Radiation_Longwave_Net_Road_W_p_m2 + Radiation_Longwave_Net_Wall_W_p_m2;
		//Note: Alternative algorithm to adjust ImpNR_W_p_m2 based on Oke et al. (2017) Table 5.4 based on day vs night conditions, Radiation_Shortwave_W_p_m2 is proxy for day and night
		//Note: ... Refactor to use ratio of wall and floor to roof for direct, longwave down and up from Oke et al. (2017) Fig 5.13 and 5.14 w H:W = 1 
		//Note: ... ImpNR_W_p_m2 increases as function of urban canyon aspect ratio and orientation, as demonstrated in Figure 5.14 and Table 5.4 in Oke et al. (2017) 
		//Note: ... Daytime relation between increase in net radiation (NR, fraction) and aspect ratio (AR=H:W): AR=0.5 NR=0.11, AR=2.0 NR=0.20, AR=2.0 NR=0.24, AR=4.0 NR=0.28
		//Note: ... Daytime trendline function NR_frac = 0.076 * ln(AR) + 0.182, has R^2=0.98, derived with additional, estimated, data point of AR=0.1 NR=0.01
		//Note: ... Nighttime relation between increase in net longwave radiation (NLW, fraction) and aspect ratio (AR=H:W): AR=0.5 NLW=0.25, AR=1.0 NLW=0.31, AR=2.0 NLW=0.31, AR=4.0 NLW=0.38		
		//Note: ... Nighttime trendline function NLW = 0.097 * ln(AR) + 0.27, has R^2=0.92, derived with additional, estimated, data point of AR=0.1 NLW=0.01
	}
	//Else If Land Cover NLCD Class is not urban, 21 to 24, then then set parameters for impervious without buildings or urban canyons
	else {
		//ImpNR_W_p_m2 (W/m2) defined in Eq 24 in Yang, Endreny, Nowak (2013), modifying Radiation_Longwave_Down_W_p_m2 and Radiation_Longwave_Up_W_p_m2 by emissivity
		//Note: Radiation is positive downward, w/ Radiation_Shortwave_W_p_m2 and Radiation_Longwave_Down_W_p_m2 added, Radiation_Longwave_Up_W_p_m2 subtracted
		ImpNR_W_p_m2 = Radiation_Shortwave_W_p_m2 * (1 - Albedo_Urban_frac) + Emissivity_Urban_frac * Radiation_Longwave_Down_W_p_m2 -
			Emissivity_Urban_frac * Radiation_Longwave_Up_W_p_m2;
	}
	//If Flag_simulateReferenceStation > 0 then even if NLCD Class is urban then set parameters for impervious without buildings or urban canyons
	//Note: Reference station is considered area without significant urban canyon or buildings, as prescribed when establishing airport meteorological station
	if (Flag_simulateReferenceStation > 0) {
		//ImpNR_W_p_m2 (W/m2) defined in Eq 24 in Yang, Endreny, Nowak (2013), modifying Radiation_Longwave_Down_W_p_m2 and Radiation_Longwave_Up_W_p_m2 by emissivity
		//Note: Radiation is positive downward, w/ Radiation_Shortwave_W_p_m2 and Radiation_Longwave_Down_W_p_m2 added, Radiation_Longwave_Up_W_p_m2 subtracted
		ImpNR_W_p_m2 = Radiation_Shortwave_W_p_m2 * (1 - Albedo_Urban_frac) + Emissivity_Urban_frac * Radiation_Longwave_Down_W_p_m2 -
			Emissivity_Urban_frac * Radiation_Longwave_Up_W_p_m2;
	}

	//Imp_AH_W_p_m2 (W/m2) is impervious cover term for AnthropogenicHeat_Flux_Total_Wpm2, which is uniform across on pixel
	//Note: Anthropogenic heat is not summed directly into net radiation in order to track each term separately
	Imp_AH_W_p_m2 = AnthropogenicHeat_Flux_Total_Wpm2;

	//ImpDeltaQ_W_p_m2 (W/m2) defined in Eq 29 in Yang, Endreny, Nowak (2013), modifying Radiation_Longwave_Down_W_p_m2 and Radiation_Longwave_Up_W_p_m2 by emissivity
	//Parameters a1, a2, a3 originally from concrete in Table 4 of Grimmond, C., and T. R. Oke (1999a), Heat storage in urban areas, J. Appl. Meteorol., 38(7), 922–940.
	//Note: folder->VarDict["ImpNR_W_p_m2"] is ImpNR_W_p_m2 from the prior time step, and (ImpNR_W_p_m2 - ImpNR_priorTS_W_p_m2) is d(ImpNR)/d(t)
	ImpDeltaQ_W_p_m2 = a1_OHM_Urban_frac * ImpNR_W_p_m2 + a2_OHM_Urban_hr * (ImpNR_W_p_m2 - ImpNR_priorTS_W_p_m2) + a3_OHM_Urban_W_p_m2;

	//ImpC (frac / s/m) optionally defined to simplify combination of Eq 9 and 19 in Yang et al. (2013)
	//Note: ImpC = pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) / resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m; there is no surface resistance, different from soil
	ImpC = pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) / resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m;

	//If (ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) (fraction) < 0.0001 then set terms to zero
	if ((ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) < Constant_1E_negative4) {
		//All energy balance variables set to zero for this land cover type
		ImpNR_W_p_m2 = 0; ImpDeltaQ_W_p_m2 = 0; ImpC = 0;
	}

	//If TreeCover_frac (fraction) greater than 0 then proceed with tree calculations
	if (TreeCover_frac > Constant_1E_negative4) {
		//TreeNR_W_p_m2 (W/m2) defined in Eq 24 in Yang, Endreny, Nowak (2013), modifying Radiation_Longwave_Down_W_p_m2 and Radiation_Longwave_Up_W_p_m2 by emissivity
		//Note: Radiation is positive downward, w/ Radiation_Shortwave_W_p_m2 and Radiation_Longwave_Down_W_p_m2 added, Radiation_Longwave_Up_W_p_m2 subtracted
		TreeNR_W_p_m2 = Radiation_Shortwave_W_p_m2 * (1 - Albedo_Tree_frac) + Emissivity_Tree_frac * Radiation_Longwave_Down_W_p_m2 -
			Emissivity_Tree_frac * Radiation_Longwave_Up_W_p_m2;
		//If LandCover_Class_NLCD between 20 and 25 then it is urban canyon and uses Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2
		//If Flag_simulateReferenceStation < 1 then it is not the airport, and can assume urban canyon
		//Note: Weather reference stations are presumed without urban canyon, but if this is not true then change condition
		if ((LandCover_Class_NLCD > 20) && (LandCover_Class_NLCD < 25) && Flag_simulateReferenceStation < 1) {
			//TreeNR_W_p_m2 (W/m2) modified form of Eq 24 from Yang et al (2013) to use urban canyon estimates of radiation, with net longwave radiation
			TreeNR_W_p_m2 = Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2 * (1 - Albedo_Tree_frac) + Radiation_Longwave_Net_Tree_W_p_m2;
		}

		//Tree_AH_W_p_m2 (W/m2) is tree cover term for AnthropogenicHeat_Flux_Total_Wpm2, which is uniform across on pixel
		//Note: Anthropogenic heat is not summed directly into net radiation in order to track each term separately
		Tree_AH_W_p_m2 = AnthropogenicHeat_Flux_Total_Wpm2;

		//TreeDeltaQ_W_p_m2 (W/m2) defined in Eq 29 in Yang, Endreny, Nowak (2013) 
		//Parameters a1, a2, a3 originally modified from mixed forest in Table 4 of Grimmond, C., and T. R. Oke (1999a), Heat storage in urban areas, J. Appl. Meteorol., 38(7), 922–940.
		//Note: folder->VarDict["TreeNR_W_p_m2"] is TreeNR_W_p_m2 from the prior time step, and (TreeNR_W_p_m2 - TreeNR_priorTS_W_p_m2) is d(ImpNR)/d(t)
		//cte 202410 Refactor to explore adjustment in OHM coefficients a1, a2, a3 based on soil moisture stres increasing ground heat flux
		//TreeDeltaQ_W_p_m2 = a1_OHM_Tree_frac * TreeNR_W_p_m2 + a2_OHM_Tree_hr * (TreeNR_W_p_m2 - TreeNR_priorTS_W_p_m2) + a3_OHM_Tree_W_p_m2;
		TreeDeltaQ_W_p_m2 = a1_OHM_Tree_ts_frac * TreeNR_W_p_m2 + a2_OHM_Tree_ts_hr * (TreeNR_W_p_m2 - TreeNR_priorTS_W_p_m2) + a3_OHM_Tree_ts_W_p_m2;

		//TreeCE (frac / s/m) optionally defined to simplify combination of Eq 9 and 22 in Yang et al. (2013)
		//Note: TreeCE = (S/Smax)^(2/3) / (Resistance_Aerodynamic_Tree_s_p_m)
		TreeCE = pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) / resistanceVar->Resistance_Aerodynamic_Tree_s_p_m;
		//TreeCT (frac / s/m) optionally defined to simplify combination of Eq 9 and 23 in Yang et al. (2013)
		//Note: TreeCT = (S/Smax)^(2/3) / (Resistance_Aerodynamic_Tree_s_p_m + Resistance_Surface_Tree_s_p_m)
		TreeCT = (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m);
		TreeC = TreeCT + TreeCE;
	}
	//Else TreeCover_frac (fraction) < 0.0001 and proceed without tree calculations
	else {
		//All energy balance variables set to zero for this land cover type
		TreeNR_W_p_m2 = 0; TreeDeltaQ_W_p_m2 = 0; TreeCE = 0; TreeCT = 0; TreeC = 0;
	}

	//If ShortVegCover_noTreeCanopy_frac (fraction) greater than 0 then proceed with short vegetation calculations
	if (ShortVegCover_noTreeCanopy_frac > Constant_1E_negative4) {
		//SVegNR_W_p_m2 (W/m2) defined in Eq 24 in Yang, Endreny, Nowak (2013), modifying Radiation_Longwave_Down_W_p_m2 and Radiation_Longwave_Up_W_p_m2 by emissivity
		//Note: Radiation is positive downward, w/ Radiation_Shortwave_W_p_m2 and Radiation_Longwave_Down_W_p_m2 added, Radiation_Longwave_Up_W_p_m2 subtracted
		SVegNR_W_p_m2 = Radiation_Shortwave_W_p_m2 * (1 - Albedo_SVeg_frac) + Emissivity_SVeg_frac * Radiation_Longwave_Down_W_p_m2 -
			Emissivity_SVeg_frac * Radiation_Longwave_Up_W_p_m2;
		//If LandCover_Class_NLCD between 20 and 25 then it is urban canyon and uses Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2
		//If Flag_simulateReferenceStation < 1 then it is not the airport, and can assume urban canyon
		//Note: Weather reference stations are presumed without urban canyon, but if this is not true then change condition
		if ((LandCover_Class_NLCD > 20) && (LandCover_Class_NLCD < 25) && Flag_simulateReferenceStation < 1) {
			//SVegNR_W_p_m2 (W/m2) modified form of Eq 24 from Yang et al (2013) to use urban canyon estimates of radiation, with net longwave radiation
			SVegNR_W_p_m2 = Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2 * (1 - Albedo_SVeg_frac) + Radiation_Longwave_Net_SVeg_W_p_m2;
		}

		//SVeg_AH_W_p_m2 (W/m2) is short vegetation cover term for AnthropogenicHeat_Flux_Total_Wpm2, which is uniform across on pixel
		//Note: Anthropogenic heat is not summed directly into net radiation in order to track each term separately
		SVeg_AH_W_p_m2 = AnthropogenicHeat_Flux_Total_Wpm2;

		//SVegDeltaQ_W_p_m2 (W/m2) defined in Eq 29 in Yang et al. (2013) 
		//Parameters a1, a2, a3 originally from short grass in Table 4 of Grimmond, C., and T. R. Oke (1999a), Heat storage in urban areas, J. Appl. Meteorol., 38(7), 922–940.
		//Note: folder->VarDict["SVegNR_W_p_m2"] is SVegNR_W_p_m2 from the prior time step, and (SVegNR_W_p_m2 - SVegNR_priorTS_W_p_m2) is d(ImpNR)/d(t)
		//cte 202410 Refactor to explore adjustment in OHM coefficients a1, a2, a3 based on soil moisture stres increasing ground heat flux
		//SVegDeltaQ_W_p_m2 = a1_OHM_SVeg_frac * SVegNR_W_p_m2 + a2_OHM_SVeg_hr * (SVegNR_W_p_m2 - SVegNR_priorTS_W_p_m2) + a3_OHM_SVeg_W_p_m2;
		SVegDeltaQ_W_p_m2 = a1_OHM_SVeg_ts_frac * SVegNR_W_p_m2 + a2_OHM_SVeg_ts_hr * (SVegNR_W_p_m2 - SVegNR_priorTS_W_p_m2) + a3_OHM_SVeg_ts_W_p_m2;

		//SVegCE (frac / s/m) optionally defined to simplify combination of Eq 9 and 22 in Yang et al. (2013)
		//Note: SVegCE = (S/Smax)^(2/3) / (Resistance_Aerodynamic_SVeg_s_p_m)
		SVegCE = pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) / resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m;
		//SVegCT (frac / s/m) optionally defined to simplify combination of Eq 9 and 23 in Yang et al. (2013)
		//Note: SVegCT = (S/Smax)^(2/3) / (Resistance_Aerodynamic_SVeg_s_p_m + Resistance_Surface_SVeg_s_p_m)
		SVegCT = (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m);
		SVegC = SVegCT + SVegCE;
	}
	//Else ShortVegCover_noTreeCanopy_frac (fraction) < 0.0001 and proceed without short vegetation calculations
	else {
		//All energy balance variables set to zero for this land cover type
		SVegNR_W_p_m2 = 0; SVegDeltaQ_W_p_m2 = 0; SVegCE = 0; SVegCT = 0; SVegC = 0;
	}

	//If SoilCover_noTreeCanopy_frac (fraction) greater than 0 then proceed with soil calculations
	if (SoilCover_noTreeCanopy_frac > Constant_1E_negative4) {
		//SoilNR_W_p_m2 (W/m2) defined in Eq 24 in Yang, Endreny, Nowak (2013), modifying Radiation_Longwave_Down_W_p_m2 and Radiation_Longwave_Up_W_p_m2 by emissivity
		//Note: Radiation is positive downward, w/ Radiation_Shortwave_W_p_m2 and Radiation_Longwave_Down_W_p_m2 added, Radiation_Longwave_Up_W_p_m2 subtracted
		SoilNR_W_p_m2 = Radiation_Shortwave_W_p_m2 * (1 - Albedo_Soil_frac) + Emissivity_Soil_frac * Radiation_Longwave_Down_W_p_m2 -
			Emissivity_Soil_frac * Radiation_Longwave_Up_W_p_m2;
		//If LandCover_Class_NLCD between 20 and 25 then it is urban canyon and uses Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2
		//If Flag_simulateReferenceStation < 1 then it is not the airport, and can assume urban canyon
		//Note: Weather reference stations are presumed without urban canyon, but if this is not true then change condition
		if ((LandCover_Class_NLCD > 20) && (LandCover_Class_NLCD < 25) && Flag_simulateReferenceStation < 1) {
			//SoilNR_W_p_m2 (W/m2) modified form of Eq 24 from Yang et al (2013) to use urban canyon estimates of radiation, with net longwave radiation
			SoilNR_W_p_m2 = Radiation_Shortwave_Direct_Diffuse_Road_W_p_m2 * (1 - Albedo_Soil_frac) + Radiation_Longwave_Net_Soil_W_p_m2;
		}

		//Soil_AH_W_p_m2 (W/m2) is soil cover term for AnthropogenicHeat_Flux_Total_Wpm2, which is uniform across on pixel
		//Note: Anthropogenic heat is not summed directly into net radiation in order to track each term separately
		Soil_AH_W_p_m2 = AnthropogenicHeat_Flux_Total_Wpm2;

		//SoilDeltaQ_W_p_m2 (W/m2) defined in Eq 29 in Yang, Endreny, Nowak (2013) 
		//Parameters a1, a2, a3 originally from bare soil in Table 4 of Grimmond, C., and T. R. Oke (1999a), Heat storage in urban areas, J. Appl. Meteorol., 38(7), 922–940.
		//Note: folder->VarDict["SoilNR_W_p_m2"] is SoilNR_W_p_m2 from the prior time step, and (SoilNR_W_p_m2 - SoilNR_priorTS_W_p_m2) is d(ImpNR)/d(t)
		//cte 202410 Refactor to explore adjustment in OHM coefficients a1, a2, a3 based on soil moisture stres increasing ground heat flux
		//SoilDeltaQ_W_p_m2 = a1_OHM_Soil_frac * SoilNR_W_p_m2 + a2_OHM_Soil_hr * (SoilNR_W_p_m2 - SoilNR_priorTS_W_p_m2) + a3_OHM_Soil_W_p_m2;
		SoilDeltaQ_W_p_m2 = a1_OHM_Soil_ts_frac * SoilNR_W_p_m2 + a2_OHM_Soil_ts_hr * (SoilNR_W_p_m2 - SoilNR_priorTS_W_p_m2) + a3_OHM_Soil_ts_W_p_m2;

		//SoilC (frac / s/m) optionally defined to simplify combination of Eq 9 and 20 in Yang et al. (2013)
		//Note: SoilC = (1 - D/Dmax) * 1/(Resistance_Aerodynamic_Soil_s_p_m + Resistance_Surface_Soil_s_p_m) = Saturation_SoilStorage_frac / (Resistance_Aerodynamic_Soil_s_p_m + Resistance_Surface_Soil_s_p_m)
		SoilC = Saturation_SoilStorage_frac / (resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m);
	}
	//Else SoilCover_noTreeCanopy_frac (fraction) < 0.0001 and proceed without soil calculations
	else {
		//All energy balance variables set to zero for this land cover type
		SoilNR_W_p_m2 = 0; SoilDeltaQ_W_p_m2 = 0; SoilC = 0;
	}

	//If WaterCover_noTreeCanopy_frac (fraction) greater than 0 then proceed with water calculations
	if (WaterCover_noTreeCanopy_frac > Constant_1E_negative4) {
		//WaterNR_W_p_m2 (W/m2)  defined in Eq 24 in Yang, Endreny, Nowak (2013), modifying Radiation_Longwave_Down_W_p_m2 and Radiation_Longwave_Up_W_p_m2 by emissivity
		//Note: Radiation is positive downward, w/ Radiation_Shortwave_W_p_m2 and Radiation_Longwave_Down_W_p_m2 added, Radiation_Longwave_Up_W_p_m2 subtracted
		WaterNR_W_p_m2 = Radiation_Shortwave_W_p_m2 * (1 - Albedo_Water_frac) + Emissivity_Water_frac * Radiation_Longwave_Down_W_p_m2 -
			Emissivity_Water_frac * Radiation_Longwave_Up_W_p_m2;
		//If LandCover_Class_NLCD between 20 and 25 then it is urban canyon and uses Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2
		//If Flag_simulateReferenceStation < 1 then it is not the airport, and can assume urban canyon
		//Note: Weather reference stations are presumed without urban canyon, but if this is not true then change condition
		if ((LandCover_Class_NLCD > 20) && (LandCover_Class_NLCD < 25) && Flag_simulateReferenceStation < 1) {
			//WaterNR_W_p_m2 (W/m2) modified form of Eq 24 from Yang et al (2013) to use urban canyon estimates of radiation, with net longwave radiation
			WaterNR_W_p_m2 = Radiation_Shortwave_Direct_Diffuse_Road_W_p_m2 * (1 - Albedo_Water_frac) + Radiation_Longwave_Net_Water_W_p_m2;
		}

		//Water_AH_W_p_m2 (W/m2) is water cover term for AnthropogenicHeat_Flux_Total_Wpm2, which is uniform across on pixel
		//Note: Anthropogenic heat is not summed directly into net radiation in order to track each term separately
		Water_AH_W_p_m2 = AnthropogenicHeat_Flux_Total_Wpm2;

		//SoilDeltaQ_W_p_m2 (W/m2) defined in Eq 29 in Yang, Endreny, Nowak (2013) 
		//Parameters a1, a2, a3 originally from water in Table 4 of Grimmond, C., and T. R. Oke (1999a), Heat storage in urban areas, J. Appl. Meteorol., 38(7), 922–940.
		//Note: folder->VarDict["WaterNR_W_p_m2"] is WaterNR_W_p_m2 from the prior time step, and (WaterNR_W_p_m2 - WaterNR_priorTS_W_p_m2) is d(ImpNR)/d(t)
		WaterDeltaQ_W_p_m2 = a1_OHM_Water_frac * WaterNR_W_p_m2 + a2_OHM_Water_hr * (WaterNR_W_p_m2 - WaterNR_priorTS_W_p_m2) + a3_OHM_Water_W_p_m2;

		//WaterC (frac / s/m) optionally defined to simplify combination of Eq 9 and 20 in Yang et al. (2013), where Eq 20 modified from soil to water by dropping ground resistance
		//Note: WaterC = (1 - D/Dmax) * 1/Resistance_Aerodynamic_Water_s_p_m = Saturation_WaterStorage_frac / Resistance_Aerodynamic_Water_s_p_m
		//Note: WaterC is resistance term within Eq 14 in Yang et al. (2013), which is best estimate of evaporation from free water surface on the ground
		WaterC = Saturation_WaterStorage_frac / resistanceVar->Resistance_Aerodynamic_Soil_s_p_m;
	}
	//Else WaterCover_noTreeCanopy_frac (fraction) < 0.0001 and proceed without water calculations
	else {
		//All energy balance variables set to zero for this land cover type
		WaterNR_W_p_m2 = 0; WaterDeltaQ_W_p_m2 = 0; WaterC = 0;
	}

	//If Building_Area_frac is > 0 then define roof parameters
	//Note: Roof conditions depend on whether it is black, high albedo white, or vegetated green, and could be prescribed in HydroPlusConfig.xml
	if (Building_Area_frac > 0) {
		//RoofNR_W_p_m2 (W/m2) modified form of Eq 24 from Yang et al (2013) to use urban canyon estimates of radiation, with net longwave radiation
		RoofNR_W_p_m2 = Radiation_Shortwave_Direct_Diffuse_Roof_W_p_m2 * (1 - Albedo_Urban_frac) + Emissivity_Roof_frac * Radiation_Longwave_Down_W_p_m2 - Emissivity_Roof_frac * Radiation_Longwave_Up_W_p_m2;
		//RoofDeltaQ_W_p_m2 could be set equal to SVegDeltaQ_W_p_m2 or ImpDeltaQ_W_p_m2
		RoofDeltaQ_W_p_m2 = ImpDeltaQ_W_p_m2; //SVegDeltaQ_W_p_m2;
		//RoofC could be set equal to ImpC or SVegC
		RoofC = ImpC; // SVegC;
	}
	//Else NLCD Class for roof not present and proceed without roof calculations
	else {
		//All energy balance variables set to zero for this land cover type
		RoofNR_W_p_m2 = 0; RoofDeltaQ_W_p_m2 = 0; RoofC = 0;
	}
	//If Flag_MultipleStation is true and Flag_simulateReferenceStation is true then read in Weatherpre-> reference station meteorological variables for flux calculations
	//Note: Step is required at end of function to write current NR value as prior time step value for DeltQ inputs for each weather station specific and NR land cover
	if (input->SimulationStringParams["Flag_MultipleStation"] == "1" && Flag_simulateReferenceStation == 1) {
		//NR_priorTS_W_p_m2_Map udpated so that keyname_ImpNR_priorTS_W_p_m2 contains data value ImpNR_W_p_m2 (Imp and associated land cover types)
		NR_priorTS_W_p_m2_Map[keyname_ImpNR_priorTS_W_p_m2] = ImpNR_W_p_m2;
		NR_priorTS_W_p_m2_Map[keyname_TreeNR_priorTS_W_p_m2] = TreeNR_W_p_m2;
		NR_priorTS_W_p_m2_Map[keyname_SVegNR_priorTS_W_p_m2] = SVegNR_W_p_m2;
		NR_priorTS_W_p_m2_Map[keyname_SoilNR_priorTS_W_p_m2] = SoilNR_W_p_m2;
		NR_priorTS_W_p_m2_Map[keyname_WaterNR_priorTS_W_p_m2] = WaterNR_W_p_m2;
		NR_priorTS_W_p_m2_Map[keyname_RoofNR_priorTS_W_p_m2] = RoofNR_W_p_m2;
	}
}

//UrbanCanyon_RadiationLongwave function calculates urban canyon longwave energy balance once for each folder at each timeStep
void HeatFluxCal::UrbanCanyon_RadiationLongwave(Inputs* input, DataFolder* folder, int MapPixel_ID, bool Flag_UrbanCanyonResistance, int timeStep)
{
	//Coefficient_w_Eq09_Offerle_2003 from below Eq 9 of Offerle et al. (2003), where VaporPressure_Actual_kPa (kPa) gives w values ranging from 0 to 0.62
	double Coefficient_w_Eq09_Offerle_2003 = 46.5 * VaporPressure_Actual_kPa / Tair_localCell_K;

	//Emissivity_ClearSky_frac (fraction) from Eq 9 of Offerle et al. (2003) 
	double Emissivity_ClearSky_frac = 1 - (1 + Coefficient_w_Eq09_Offerle_2003) * exp(-1 * pow(1.2 + 3.0 * Coefficient_w_Eq09_Offerle_2003, 0.5));
	//CloudCover_frac (fraction) computed to replace Eq 11 of Offerle et al. (2003) using difference in Tdew_localCell_K and Tair_localCell_K
	double CloudCover_frac = 0;
	//If (Tair_localCell_K - Tdew_localCell_K) <= 1) then moisture content is relatively high and clouds are likely
	if ((Tair_localCell_K - Tdew_localCell_K) <= 1) {
		CloudCover_frac = (Tair_localCell_K - Tdew_localCell_K);
	}
	//Emissivity_Sky_frac (frac) from Eq 12 of Offerle et al. (2003) using new form of CloudCover_frac based on dew point
	//Caution: Emissivity_Sky_frac calculation is not proven to work, and seems to generate sky temperatures that are too large
	//Note: Temperature_Atmosphere_K_Power04 computed from mesoScale temperature, not from Emissivity_Sky_frac
	Emissivity_Sky_frac = Emissivity_ClearSky_frac + (1.0 - Emissivity_ClearSky_frac) * pow(CloudCover_frac, 2);

	//Prevent zero value emissivity to avoid division by zero
	if (Emissivity_Sky_frac <= 0) { Emissivity_Sky_frac = 0.01; }
	if (Emissivity_Wall_frac <= 0) { Emissivity_Wall_frac = 0.01; }
	if (Emissivity_Road_frac <= 0) { Emissivity_Road_frac = 0.01; }
	if (Emissivity_Tree_frac <= 0) { Emissivity_Tree_frac = 0.01; }
	if (Emissivity_SVeg_frac <= 0) { Emissivity_SVeg_frac = 0.01; }
	if (Emissivity_Soil_frac <= 0) { Emissivity_Soil_frac = 0.01; }
	if (Emissivity_SVeg_frac <= 0) { Emissivity_SVeg_frac = 0.01; }

	//Temperature_Sky_K estimated as Tair_localCell_K
	double Temperature_Sky_K = Tair_localCell_K;
	//If Tair_mesoScale_K defined then use to update estimate of Temperature_Sky_K
	if (folder->VarDict["Tair_mesoScale_K"] > 0) {
		Temperature_Sky_K = folder->VarDict["Tair_mesoScale_K"];
	};
	//Temperature_Atmosphere_K_Power04 (K^4) estimated based on Tair_localCell_K (K), and used in a function taking temperature to the 4th power
	double Temperature_Atmosphere_K_Power04 = pow(Temperature_Sky_K, 4);
	//Alternatively, Temperature_Atmosphere_K_Power04 (K^4) rearranged from Eq 26 of Yang et al. (2013), and from Eq 8 of Offerle et al. (2003)
	//Note: This alternative equation not used due to it overestimating sky temperature by 20 C; need better value for Emissivity_Sky_frac
	//double Temperature_Atmosphere_K_Power04 = Radiation_Longwave_Down_W_p_m2 / (Emissivity_Sky_frac * Sigma_Stefan_Boltzmann);

	//Temperature_UrbanCanyonWall_K_Power04 (K^4) from Eq 28 of Yang et al. (2013), based on from Eq 14 to 16 of Offerle et al. (2003)
	//Note: Offerle et al. (2003) explains the assumption of Tsurface = Tair_K at night holds well for urban area
	//Note: Coefficient_c_Eq28_Yang_etal_2013 = c = 0.08 parameter in Eq 28 of Yang et al. (2013), but also given w/ Eq 15 of Offerle et al. (2003), and attributed to Holtslag and van Ulden (1983) https://doi.org/10.1175/1520-0450(1983)022<0517:ASSFDE>2.0.CO;2
	double Temperature_UrbanCanyonWall_K_Power04 = Temperature_Atmosphere_K_Power04 + (Coefficient_c_Eq28_Yang_etal_2013 * Radiation_Shortwave_Direct_Diffuse_Wall_W_p_m2 * (1 - Albedo_Wall_frac)) / (Emissivity_Wall_frac * Sigma_Stefan_Boltzmann);
	//Temperature_UrbanCanyonWall_K (K) is Temperature_UrbanCanyonWall_K_Power04 ^ 0.25
	Temperature_UrbanCanyonWall_K = pow(Temperature_UrbanCanyonWall_K_Power04, 0.25);

	//Temperature_UrbanCanyonRoad_K_Power04 (K^4) from Eq 28 of Yang et al. (2013), based on from Eq 14 to 16 of Offerle et al. (2003)
	//Note: Offerle et al. (2003) explains the assumption of Tsurface = Tair_K at night holds well for urban area
	//Note: Coefficient_c_Eq28_Yang_etal_2013 = c = 0.08 parameter in Eq 28 of Yang et al. (2013), but also given w/ Eq 15 of Offerle et al. (2003), and attributed to Holtslag and van Ulden (1983) https://doi.org/10.1175/1520-0450(1983)022<0517:ASSFDE>2.0.CO;2
	double Temperature_UrbanCanyonRoad_K_Power04 = Temperature_Atmosphere_K_Power04 + (Coefficient_c_Eq28_Yang_etal_2013 * Radiation_Shortwave_Direct_Diffuse_Road_W_p_m2 * (1 - Albedo_Road_frac)) / (Emissivity_Road_frac * Sigma_Stefan_Boltzmann);
	//Temperature_UrbanCanyonWall_K (K) is Temperature_UrbanCanyonRoad_K_Power04 ^ 0.25
	Temperature_UrbanCanyonRoad_K = pow(Temperature_UrbanCanyonRoad_K_Power04, 0.25);

	//Temperature_UrbanCanyonTree_K_Power04 (K^4) from Eq 28 of Yang et al. (2013), based on from Eq 14 to 16 of Offerle et al. (2003)
	//Note: Offerle et al. (2003) explains the assumption of Tsurface = Tair_K at night holds well for urban area
	//Note: Coefficient_c_Eq28_Yang_etal_2013 = c = 0.08 parameter in Eq 28 of Yang et al. (2013), but also given w/ Eq 15 of Offerle et al. (2003), and attributed to Holtslag and van Ulden (1983) https://doi.org/10.1175/1520-0450(1983)022<0517:ASSFDE>2.0.CO;2
	double Temperature_UrbanCanyonTree_K_Power04 = Temperature_Atmosphere_K_Power04 + (Coefficient_c_Eq28_Yang_etal_2013 * Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2 * (1 - Albedo_Tree_frac)) / (Emissivity_Tree_frac * Sigma_Stefan_Boltzmann);
	//Temperature_UrbanCanyonTree_K (K) is Temperature_UrbanCanyonGarden_K_Power04 ^ 0.25
	Temperature_UrbanCanyonTree_K = pow(Temperature_UrbanCanyonTree_K_Power04, 0.25);

	//Temperature_UrbanCanyonSVeg_K_Power04 (K^4) from Eq 28 of Yang et al. (2013), based on from Eq 14 to 16 of Offerle et al. (2003)
	//Note: Offerle et al. (2003) explains the assumption of Tsurface = Tair_K at night holds well for urban area
	//Note: Coefficient_c_Eq28_Yang_etal_2013 = c = 0.08 parameter in Eq 28 of Yang et al. (2013), but also given w/ Eq 15 of Offerle et al. (2003), and attributed to Holtslag and van Ulden (1983) https://doi.org/10.1175/1520-0450(1983)022<0517:ASSFDE>2.0.CO;2
	double Temperature_UrbanCanyonSVeg_K_Power04 = Temperature_Atmosphere_K_Power04 + (Coefficient_c_Eq28_Yang_etal_2013 * Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2 * (1 - Albedo_SVeg_frac)) / (Emissivity_SVeg_frac * Sigma_Stefan_Boltzmann);
	//Temperature_UrbanCanyonSVeg_K (K) is Temperature_UrbanCanyonSVeg_K_Power04 ^ 0.25
	Temperature_UrbanCanyonSVeg_K = pow(Temperature_UrbanCanyonSVeg_K_Power04, 0.25);

	//Temperature_UrbanCanyon_Garden_K (K) is weighted average of Temperature_UrbanCanyonTree_K + Temperature_UrbanCanyonSVeg_K
	double Temperature_UrbanCanyon_Garden_K = TreeCover_frac * Temperature_UrbanCanyonTree_K + ShortVegCover_noTreeCanopy_frac * Temperature_UrbanCanyonSVeg_K;

	//Temperature_UrbanCanyonSoil_K_Power04 (K^4) from Eq 28 of Yang et al. (2013), based on from Eq 14 to 16 of Offerle et al. (2003)
	//Note: Offerle et al. (2003) explains the assumption of Tsurface = Tair_K at night holds well for urban area
	//Note: Coefficient_c_Eq28_Yang_etal_2013 = c = 0.08 parameter in Eq 28 of Yang et al. (2013), but also given w/ Eq 15 of Offerle et al. (2003), and attributed to Holtslag and van Ulden (1983) https://doi.org/10.1175/1520-0450(1983)022<0517:ASSFDE>2.0.CO;2
	double Temperature_UrbanCanyonSoil_K_Power04 = Temperature_Atmosphere_K_Power04 + (Coefficient_c_Eq28_Yang_etal_2013 * Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2 * (1 - Albedo_Soil_frac)) / (Emissivity_Soil_frac * Sigma_Stefan_Boltzmann);
	//Temperature_UrbanCanyonSoil_K (K) is Temperature_UrbanCanyonSoil_K_Power04 ^ 0.25
	Temperature_UrbanCanyonSoil_K = pow(Temperature_UrbanCanyonSoil_K_Power04, 0.25);

	//Temperature_UrbanCanyonWater_K (K) is estimated as Tdew_localCell_K (k), dew point temperature
	Temperature_UrbanCanyonWater_K = Tdew_localCell_K;

	//Radiation_Longwave_from_Wall_W_p_m2 (W/m2) from Eq 5.1 of Oke et al. (2017), Emittance (W/m2) = Emissivity * Sigma_Stefan_Boltzmann * Temperature_Surface_K^4 
	double Radiation_Longwave_from_Wall_W_p_m2 = Emissivity_Wall_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWall_K, 4);
	//Radiation_Longwave_from_Ground_W_p_m2  (W/m2) from Eq 5.1 of Oke et al. (2017), Emittance (W/m2) = Emissivity * Sigma_Stefan_Boltzmann * Temperature_Surface_K^4 
	double Radiation_Longwave_from_Ground_W_p_m2 = (Emissivity_Road_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonRoad_K, 4)) * Ratio_Road_to_Ground + (Emissivity_Garden_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyon_Garden_K, 4)) * Ratio_Garden_to_Ground;

	//Radiation_Longwave_Down_to_Ground_W_p_m2 (W/m2) is weighted average of Radiation_Longwave_from_Wall_W_p_m2 from wall and Radiation_Longwave_Down_W_p_m2 from sky
	//Note: SkyViewFactor_Road_frac determines amount of radiation from sky and (1-SkyViewFactor_Road_frac) determines radiation from wall
	Radiation_Longwave_Down_to_Ground_W_p_m2 = (1 - SkyViewFactor_Road_frac) * Radiation_Longwave_from_Wall_W_p_m2 + SkyViewFactor_Road_frac * Radiation_Longwave_Down_W_p_m2;
	//Radiation_Longwave_Down_to_Wall_W_p_m2 (W/m2) is weighted average of Radiation_Longwave_from_Ground_W_p_m2 from ground and Radiation_Longwave_Down_W_p_m2 from sky
	//Note: Radiation_Longwave_Net_Wall_W_p_m2 will add the radiation from the urban canyon walls; if added to Radiation_Longwave_Down_to_Wall_W_p_m2 then double counting
	Radiation_Longwave_Down_to_Wall_W_p_m2 = (1 - SkyViewFactor_Road_frac) * Radiation_Longwave_from_Ground_W_p_m2 + Count_CanyonWalls * SkyViewFactor_Wall_frac * Radiation_Longwave_Down_W_p_m2;

	//Radiation_Longwave_Net_Wall_W_p_m2 (W/m2) from Eq 12 of Masson (2000), and Eq 39 of Lee and Park (2008)
	//Note: Town Energy Budget (TEB) model https://github.com/TEB-model/teb may not use this approach, and may explicitly compute surface longwave fluxes and temperature
	Radiation_Longwave_Net_Wall_W_p_m2 = Emissivity_Urban_frac * SkyViewFactor_Wall_frac * Radiation_Longwave_Down_to_Wall_W_p_m2 - Emissivity_Urban_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWall_K, 4) + Emissivity_Urban_frac * SkyViewFactor_Wall_frac * Emissivity_Urban_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWall_K, 4) + pow(Emissivity_Urban_frac, 2) * (1 - 2 * SkyViewFactor_Wall_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWall_K, 4) + Emissivity_Urban_frac * (1 - Emissivity_Urban_frac) * SkyViewFactor_Road_frac * SkyViewFactor_Wall_frac * Radiation_Longwave_Down_to_Wall_W_p_m2 + Emissivity_Urban_frac * (1 - Emissivity_Urban_frac) * SkyViewFactor_Wall_frac * (1 - 2 * SkyViewFactor_Wall_frac) * Radiation_Longwave_Down_to_Wall_W_p_m2 + pow(Emissivity_Urban_frac, 2) * (1 - Emissivity_Urban_frac) * (1 - 2 * SkyViewFactor_Wall_frac) * (1 - 2 * SkyViewFactor_Wall_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWall_K, 4) + pow(Emissivity_Urban_frac, 2) * (1 - Emissivity_Urban_frac) * SkyViewFactor_Wall_frac * (1 - SkyViewFactor_Road_frac) *	Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWall_K, 4) + Emissivity_Urban_frac * (1 - Emissivity_Urban_frac) * SkyViewFactor_Wall_frac * (1 - 2 * SkyViewFactor_Wall_frac) * Emissivity_Urban_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWall_K, 4);

	//Radiation_Longwave_Net_Road_W_p_m2 (W/m2) absorbed by snow-free road, from Eq 11 of Masson (2000), and Eq 40 of Lee and Park (2008)
	//Note: Town Energy Budget (TEB) model https://github.com/TEB-model/teb may not use this approach, and may explicitly compute surface longwave fluxes and temperature
	Radiation_Longwave_Net_Road_W_p_m2 = Emissivity_Urban_frac * SkyViewFactor_Road_frac * Radiation_Longwave_Down_to_Ground_W_p_m2 -Emissivity_Urban_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonRoad_K, 4) + pow(Emissivity_Urban_frac, 2) * (1 - SkyViewFactor_Road_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonRoad_K, 4) + Emissivity_Urban_frac * (1 - Emissivity_Urban_frac) * (1 - SkyViewFactor_Road_frac) * SkyViewFactor_Wall_frac * Radiation_Longwave_Down_to_Ground_W_p_m2 + pow(Emissivity_Urban_frac, 2) * (1 - Emissivity_Urban_frac) * (1 - SkyViewFactor_Road_frac) * (1 - 2 * SkyViewFactor_Wall_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonRoad_K, 4) +	Emissivity_Urban_frac * (1 - Emissivity_Urban_frac) * (1 - SkyViewFactor_Road_frac) * SkyViewFactor_Wall_frac * Emissivity_Urban_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonRoad_K, 4);

	//Radiation_Longwave_Net_Tree_W_p_m2 (W/m2) absorbed by snow-free road, modified from Eq 11 of Masson (2000), and Eq 40 of Lee and Park (2008)
	Radiation_Longwave_Net_Tree_W_p_m2 = Emissivity_Tree_frac * SkyViewFactor_Garden_frac * Radiation_Longwave_Down_to_Ground_W_p_m2 -Emissivity_Tree_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonTree_K, 4) +	pow(Emissivity_Tree_frac, 2) * (1 - SkyViewFactor_Garden_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonTree_K, 4) + Emissivity_Tree_frac * (1 - Emissivity_Tree_frac) * (1 - SkyViewFactor_Garden_frac) * SkyViewFactor_Wall_frac * Radiation_Longwave_Down_to_Ground_W_p_m2 +	pow(Emissivity_Tree_frac, 2) * (1 - Emissivity_Tree_frac) * (1 - SkyViewFactor_Garden_frac) * (1 - 2 * SkyViewFactor_Wall_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonTree_K, 4) + Emissivity_Tree_frac * (1 - Emissivity_Tree_frac) * (1 - SkyViewFactor_Garden_frac) * SkyViewFactor_Wall_frac * Emissivity_Tree_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonTree_K, 4);

	//Radiation_Longwave_Net_SVeg_W_p_m2 (W/m2) absorbed by snow-free road, modified from Eq 11 of Masson (2000), and Eq 40 of Lee and Park (2008)
	Radiation_Longwave_Net_SVeg_W_p_m2 = Emissivity_SVeg_frac * SkyViewFactor_Garden_frac * Radiation_Longwave_Down_to_Ground_W_p_m2 -Emissivity_SVeg_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonSVeg_K, 4) +	pow(Emissivity_SVeg_frac, 2) * (1 - SkyViewFactor_Garden_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonSVeg_K, 4) + Emissivity_SVeg_frac * (1 - Emissivity_SVeg_frac) * (1 - SkyViewFactor_Garden_frac) * SkyViewFactor_Wall_frac * Radiation_Longwave_Down_to_Ground_W_p_m2 + pow(Emissivity_SVeg_frac, 2) * (1 - Emissivity_SVeg_frac) * (1 - SkyViewFactor_Garden_frac) * (1 - 2 * SkyViewFactor_Wall_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonSVeg_K, 4) + Emissivity_SVeg_frac * (1 - Emissivity_SVeg_frac) * (1 - SkyViewFactor_Garden_frac) * SkyViewFactor_Wall_frac * Emissivity_SVeg_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonSVeg_K, 4);

	//Radiation_Longwave_Net_Soil_W_p_m2 (W/m2) absorbed by snow-free road, modified from Eq 11 of Masson (2000), and Eq 40 of Lee and Park (2008)
	//Note: SkyViewFactor_Road_frac is used for Radiation_Longwave_Net_Soil_W_p_m2; think rural
	Radiation_Longwave_Net_Soil_W_p_m2 = Emissivity_Soil_frac * SkyViewFactor_Road_frac * Radiation_Longwave_Down_to_Ground_W_p_m2 -Emissivity_Soil_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonSoil_K, 4) +	pow(Emissivity_Soil_frac, 2) * (1 - SkyViewFactor_Road_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonSoil_K, 4) +	Emissivity_Soil_frac * (1 - Emissivity_Soil_frac) * (1 - SkyViewFactor_Road_frac) * SkyViewFactor_Wall_frac * Radiation_Longwave_Down_to_Ground_W_p_m2 +	pow(Emissivity_Soil_frac, 2) * (1 - Emissivity_Soil_frac) * (1 - SkyViewFactor_Road_frac) * (1 - 2 * SkyViewFactor_Wall_frac) *	Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonSoil_K, 4) + Emissivity_Soil_frac * (1 - Emissivity_Soil_frac) * (1 - SkyViewFactor_Road_frac) * SkyViewFactor_Wall_frac * Emissivity_Soil_frac *	Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonSoil_K, 4);

	//Radiation_Longwave_Down_to_Ground_W_p_m2 (W/m2) from Eq 5.1 of Oke et al. (2017), Emittance (W/m2) = Emissivity * Sigma_Stefan_Boltzmann * Tair_localCell_K^4 
	//Note: Tair_localCell_K used for Radiation_Longwave_Down_to_Ground_W_p_m2 over water to represent the negative net radiation 
	Radiation_Longwave_Down_to_Ground_W_p_m2 = Emissivity_Water_frac * Sigma_Stefan_Boltzmann * pow(Temperature_Sky_K, 4);

	//Radiation_Longwave_Net_Water_W_p_m2 (W/m2) absorbed by snow-free road, modified from Eq 11 of Masson (2000), and Eq 40 of Lee and Park (2008)
	//Note: SkyViewFactor_Road_frac is used for Radiation_Longwave_Net_Water_W_p_m2; think Venice
	Radiation_Longwave_Net_Water_W_p_m2 = Emissivity_Water_frac * SkyViewFactor_Road_frac * Radiation_Longwave_Down_to_Ground_W_p_m2 -Emissivity_Water_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWater_K, 4) + pow(Emissivity_Water_frac, 2) * (1 - SkyViewFactor_Road_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWater_K, 4) + Emissivity_Water_frac * (1 - Emissivity_Water_frac) * (1 - SkyViewFactor_Road_frac) * SkyViewFactor_Wall_frac * Radiation_Longwave_Down_to_Ground_W_p_m2 + pow(Emissivity_Water_frac, 2) * (1 - Emissivity_Water_frac) * (1 - SkyViewFactor_Road_frac) * (1 - 2 * SkyViewFactor_Wall_frac) * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWater_K, 4) + Emissivity_Water_frac * (1 - Emissivity_Water_frac) * (1 - SkyViewFactor_Road_frac) * SkyViewFactor_Wall_frac * Emissivity_Water_frac * Sigma_Stefan_Boltzmann * pow(Temperature_UrbanCanyonWater_K, 4);
}

//UrbanCanyon_RadiationShortwave function calculates urban canyon direct and diffuse shortwave energy balance once for each folder at each timeStep
void HeatFluxCal::UrbanCanyon_RadiationShortwave(Inputs* input, DataFolder* folder, int MapPixel_ID, bool Flag_UrbanCanyonResistance, int timeStep)
{
	double Denominator_Reflection = 0;
	double Reflection_Road_to_Wall_frac = 0;
	double Reflection_Garden_to_Wall_frac = 0;
	double Tangent_Angle_Zenith_Solar = 0;
	double Angle_SolarZenith_to_BuildingHeight_rad = 0;
	double GardenArea_frac = 0;

	//Radiation_Shortwave_Direct_Roof_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: Consider refactor for fraction of solar panel area: ZABS_DIR_SW_RF   (JJ) = ZDIR_SW(JJ) * (1. - T%XALB_ROOF     (JJ)) * (1.-PFRAC_PANEL(JJ))
	Radiation_Shortwave_Direct_Roof_W_p_m2 = Radiation_Shortwave_Direct_W_p_m2 * (1 - Albedo_Roof_frac);
	//Radiation_Shortwave_Diffuse_Garden_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: Consider refactor for fraction of solar panel area: ZABS_SCA_SW_RF   (JJ) = ZSCA_SW(JJ) * (1. - T%XALB_ROOF     (JJ)) * (1.-PFRAC_PANEL(JJ))
	Radiation_Shortwave_Diffuse_Roof_W_p_m2 = Radiation_Shortwave_Diffuse_W_p_m2 * (1 - Albedo_Roof_frac);

	//Direction_Road_rad when < 0 is uniform, no specific direction, using compass direction (0 = North, increases clockwise)
	Direction_Road_rad = -1;
	//Symmetry_Wall_int is 1 when symmetrical, 0 when not symmetrical
	Symmetry_Wall_int = 1;
	Glazing_Window = 1;
	double Albedo_WindowWall_frac = Glazing_Window * Albedo_Window_frac + (1.0 - Glazing_Window) * Albedo_Wall_frac;
	//Note: ZAALB_WL(:) =  B%XGR(:) * B%XALB_WIN(:) + (1.-B%XGR(:)) * T%XALB_WALL(:)

	//Start Algorithm for Roads and Walls ---------------------------------------------------------------------------------------------------------------------------------------
	//If Pi/2 - ZenithAngle_Solar_rad < Constant_1E_negative6 then
	if (abs(0.5 * M_PI - ZenithAngle_Solar_rad) < Constant_1E_negative6) {
		//If Pi/2 - ZenithAngle_Solar_rad > 0 then
		if (abs(0.5 * M_PI - ZenithAngle_Solar_rad) > 0.0) {
			//Tangent_Angle_Zenith_Solar is tan(0.5 * M_PI - Constant_1E_negative6)
			//Note: ZTANZEN(JJ)=TAN(0.5*XPI-1.E-6)
			Tangent_Angle_Zenith_Solar = tan(0.5 * M_PI - Constant_1E_negative6);
		}
		//If Pi/2 - ZenithAngle_Solar_rad <= 0 then
		if (abs(0.5 * M_PI - ZenithAngle_Solar_rad) > 0.0) {
			//Tangent_Angle_Zenith_Solar is tan(0.5 * M_PI + Constant_1E_negative6)
			//Note: ZTANZEN(JJ)=TAN(0.5*XPI+1.E-6)
			Tangent_Angle_Zenith_Solar = tan(0.5 * M_PI + Constant_1E_negative6);
		}
	}
	//Else If abs(ZenithAngle_Solar_rad < Constant_1E_negative6 then
	//Note: ZTANZEN(JJ)=SIGN(1.,PZENITH(JJ))*TAN(1.E-6)
	else if (abs(ZenithAngle_Solar_rad < Constant_1E_negative6)) {
		//if ZenithAngle_Solar_rad > 0  
		if (ZenithAngle_Solar_rad > 0) {
			//Tangent_Angle_Zenith_Solar is positive tan(Constant_1E_negative6)
			Tangent_Angle_Zenith_Solar = tan(Constant_1E_negative6);
		}
		else if (ZenithAngle_Solar_rad < 0) {
			//Tangent_Angle_Zenith_Solar is negative tan(Constant_1E_negative6)
			Tangent_Angle_Zenith_Solar = -1 * tan(Constant_1E_negative6);
		}
		else {
			Tangent_Angle_Zenith_Solar = 0;
		}
	}
	else {
		//Tangent_Angle_Zenith_Solar is tan(ZenithAngle_Solar_rad)
		Tangent_Angle_Zenith_Solar = tan(ZenithAngle_Solar_rad);
		//ZTANZEN(JJ) = TAN(PZENITH(JJ))
	}

	//Algorithm for radiation coefficients
	//If Building_Area_frac > 0, and AspectRatio_Canyon_frac  and Tangent_Angle_Zenith_Solar > 0 then proceed and divide by those terms
	if (Building_Area_frac > 0 && AspectRatio_Canyon_frac > 0 && Tangent_Angle_Zenith_Solar > 0) {
		//Algorithm for direct solar radiation on road
		//If Direction_Road_rad < 0 then no specific orientation, equivalent to IF (TOP%CROAD_DIR=='UNIF'), then
		//Note: TEB uses UNIF or ORIE, and ORIE allows for 1 direction per TEB patch
		if (Direction_Road_rad < 0) {
			//Angle_SolarZenith_to_BuildingHeight_rad (rad) function from TEB code SUBROUTINE urban_solar_abs.F90
			//Note: ZTHETA0(JJ) = ASIN( MIN(ABS( 1./ZTANZEN(JJ))/T%XCAN_HW_RATIO(JJ), 1. ) )
			Angle_SolarZenith_to_BuildingHeight_rad = asin(MIN(abs(1.0 / Tangent_Angle_Zenith_Solar) * 1 / AspectRatio_Canyon_frac, 1));

			//Radiation_Shortwave_Direct_Road_W_p_m2 (rad) function from TEB code SUBROUTINE urban_solar_abs.F90
			//Note: ZDIR_SW_RD (JJ) = (ZDIR_SW(JJ) * 2. * ZTHETA0(JJ) / XPI - ZDIR_SW(JJ) * 2. * ZTANZEN(JJ) / XPI * T%XCAN_HW_RATIO(JJ) * (1.-COS(ZTHETA0(JJ))))
			Radiation_Shortwave_Direct_Road_W_p_m2 = (Radiation_Shortwave_W_p_m2 * 2.0 * Angle_SolarZenith_to_BuildingHeight_rad / M_PI- Radiation_Shortwave_W_p_m2 * 2.0 * Tangent_Angle_Zenith_Solar / M_PI * AspectRatio_Canyon_frac * (1 - cos(Angle_SolarZenith_to_BuildingHeight_rad)));
		}
		//Else If Direction_Road_rad >= 0 then specific orientation then
		else {
			//Radiation_Shortwave_Direct_Road_W_p_m2 (rad) function from TEB code SUBROUTINE urban_solar_abs.F90
			//Note: ZDIR_SW_RD (JJ) = ZDIR_SW(JJ) * MAX(0.,1.-T%XCAN_HW_RATIO(JJ)*ZTANZEN(JJ)*ABS(SIN(PAZIM(JJ)-ZRD_DIR(JJ))))
			Radiation_Shortwave_Direct_Road_W_p_m2 = Radiation_Shortwave_W_p_m2 * max(0.0, 1.0 - AspectRatio_Canyon_frac * Tangent_Angle_Zenith_Solar * abs(sin(AzimuthAngle_Solar_N_0_rad - Direction_Road_rad)));

		}
		//Radiation_Shortwave_Direct_Garden_W_p_m2 equals Radiation_Shortwave_Direct_Road_W_p_m2 according to TEB
		Radiation_Shortwave_Direct_Garden_W_p_m2 = Radiation_Shortwave_Direct_Road_W_p_m2;

		//Algorithm for direct solar radiation on walls
		//Radiation_Shortwave_Direct_Wall_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
		//Note: ZDIR_SW_WL(JJ) = (ZDIR_SW(JJ) - (ZDIR_SW_RD(JJ)*ZRD(JJ)+ZDIR_SW_GD(JJ)*ZGD(JJ))) * 0.5 / T%XCAN_HW_RATIO(JJ)
		Radiation_Shortwave_Direct_Wall_W_p_m2 = (Radiation_Shortwave_W_p_m2 - (Radiation_Shortwave_Direct_Road_W_p_m2 * Ratio_Road_to_Ground + Radiation_Shortwave_Direct_Garden_W_p_m2 * Ratio_Garden_to_Ground)) * 0.5 * AspectRatio_Canyon_frac;
	}
	//Else if Building_Area_frac <= 0 then
	else {
		//Set radiation to standard values for no urban canyon
		Radiation_Shortwave_Direct_Road_W_p_m2 = Radiation_Shortwave_W_p_m2;
		Radiation_Shortwave_Direct_Garden_W_p_m2 = Radiation_Shortwave_W_p_m2;
		Radiation_Shortwave_Direct_Wall_W_p_m2 = 0;
	}

	//If Direction_Road_rad < 0 then road has no specified direction and If Symmetry_Wall_int > 0 then walls symmetrical
	if (Direction_Road_rad < 0 || Symmetry_Wall_int > 0) {
		//Radiation_Shortwave_Direct_Wall_A_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
		Radiation_Shortwave_Direct_Wall_A_W_p_m2 = Radiation_Shortwave_Direct_Wall_W_p_m2;
		Radiation_Shortwave_Direct_Wall_B_W_p_m2 = Radiation_Shortwave_Direct_Wall_W_p_m2;
	}
	//Else If Direction_Road_rad >= 0 then road has specified direction and If Symmetry_Wall_int < 0 then walls not symmetrical
	//Note: For N-S road Wall_A is west wall and east facing, Wall_B is west facing
	//Note: For E-W road Wall_A is north wall and south facing, Wall_B is north facing
	else {
		if (sin(AzimuthAngle_Solar_N_0_rad - Direction_Road_rad) > 0) {
			//Radiation_Shortwave_Direct_Wall_A_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
			Radiation_Shortwave_Direct_Wall_A_W_p_m2 = 2.0 * Radiation_Shortwave_Direct_Wall_W_p_m2;
			//Radiation_Shortwave_Direct_Wall_B_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
			Radiation_Shortwave_Direct_Wall_B_W_p_m2 = 0;
		}
		else {
			//Radiation_Shortwave_Direct_Wall_A_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
			Radiation_Shortwave_Direct_Wall_A_W_p_m2 = 0;
			//Radiation_Shortwave_Direct_Wall_B_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
			Radiation_Shortwave_Direct_Wall_B_W_p_m2 = 2.0 * Radiation_Shortwave_Direct_Wall_W_p_m2;
		}
	}

	//Diffuse radiation
	//Radiation_Shortwave_Diffuse_Road_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
	Radiation_Shortwave_Diffuse_Road_W_p_m2 = Radiation_Shortwave_Diffuse_W_p_m2 * SkyViewFactor_Road_frac;
	//Radiation_Shortwave_Diffuse_Garden_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
	Radiation_Shortwave_Diffuse_Garden_W_p_m2 = Radiation_Shortwave_Diffuse_W_p_m2 * SkyViewFactor_Garden_frac;
	//Radiation_Shortwave_Diffuse_Wall_W_p_m2 (W/m2) function from TEB code SUBROUTINE urban_solar_abs.F90
	Radiation_Shortwave_Diffuse_Wall_W_p_m2 = Radiation_Shortwave_Diffuse_W_p_m2 * SkyViewFactor_Wall_frac;

	//Solar Reflections for Direct _____________________________________________________________________________________________
	//First Reflection
	double Radiation_Shortwave_Direct_ReflectionFirst_Road_W_p_m2 = Albedo_Road_frac * Radiation_Shortwave_Direct_Road_W_p_m2;
	double Radiation_Shortwave_Direct_ReflectionFirst_Garden_W_p_m2 = Albedo_Road_frac * Radiation_Shortwave_Direct_Garden_W_p_m2;
	double Radiation_Shortwave_Direct_ReflectionFirst_Wall_W_p_m2 = Albedo_Road_frac * Radiation_Shortwave_Direct_Wall_W_p_m2;
	//Sum of Solar Reflections
	//Denominator_Reflection function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZDENOM(JJ) = 1. - (1.-2.*T%XSVF_WALL(JJ)) * T%XALB_WALL(JJ) - (1. - T%XSVF_ROAD(JJ))* T%XSVF_WALL(JJ)*T%XALB_WALL(JJ)*ZAALB_RD(JJ)*ZRD(JJ) - (1. - PSVF_GD(JJ))* T%XSVF_WALL(JJ)*T%XALB_WALL(JJ)*PALB_GD(JJ)*ZGD(JJ)
	Denominator_Reflection = 1.0 - (1.0 - 2 * SkyViewFactor_Wall_frac) * Albedo_Wall_frac -	(1.0 - SkyViewFactor_Road_frac) * SkyViewFactor_Wall_frac * Albedo_Wall_frac * Albedo_Road_frac * Ratio_Road_to_Ground - (1.0 - SkyViewFactor_Garden_frac) * SkyViewFactor_Wall_frac * Albedo_Wall_frac * Albedo_Garden_frac * Ratio_Garden_to_Ground;
	//Reflection_Road_to_Wall_frac function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZWORK1(JJ) = T%XSVF_WALL(JJ) * T%XALB_WALL(JJ) * ZRD(JJ)
	Reflection_Road_to_Wall_frac = SkyViewFactor_Wall_frac * Albedo_Wall_frac * Ratio_Road_to_Ground;
	//Reflection_Garden_to_Wall_frac function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZWORK2(JJ) = T%XSVF_WALL(JJ) * T%XALB_WALL(JJ) * ZGD(JJ)
	Reflection_Garden_to_Wall_frac = SkyViewFactor_Wall_frac * Albedo_Wall_frac * Ratio_Garden_to_Ground;
	//Radiation_Shortwave_Direct_ReflectionSum_Wall_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZSREF_SW_WL(JJ) = (  ZREF0_SW_WL(JJ) + ZWORK1(JJ) *ZREF0_SW_RD(JJ)+ ZWORK2(JJ) *ZREF0_SW_GD(JJ)) / ZDENOM(JJ)
	double Radiation_Shortwave_Direct_ReflectionSum_Wall_W_p_m2 = (Radiation_Shortwave_Direct_ReflectionFirst_Wall_W_p_m2 + Reflection_Road_to_Wall_frac * Radiation_Shortwave_Direct_ReflectionFirst_Road_W_p_m2 + Reflection_Garden_to_Wall_frac * Radiation_Shortwave_Direct_ReflectionFirst_Garden_W_p_m2) / Denominator_Reflection;
	//Radiation_Shortwave_Direct_ReflectionSum_Road_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZSREF_SW_RD(JJ) = ((1. - T % XSVF_ROAD(JJ)) * ZAALB_RD(JJ) * ZREF0_SW_WL(JJ) + (1. - T % XSVF_ROAD(JJ)) * ZAALB_RD(JJ) * ZWORK1(JJ) * ZREF0_SW_RD(JJ) + (1. - T % XSVF_ROAD(JJ)) * ZAALB_RD(JJ) * ZWORK2(JJ) * ZREF0_SW_GD(JJ)) / ZDENOM(JJ) + ZREF0_SW_RD(JJ)
	double Radiation_Shortwave_Direct_ReflectionSum_Road_W_p_m2 = ((1.0 - SkyViewFactor_Road_frac) * Albedo_Road_frac * Radiation_Shortwave_Direct_ReflectionFirst_Wall_W_p_m2 + (1.0 - SkyViewFactor_Road_frac) * Albedo_Road_frac * Reflection_Road_to_Wall_frac * Radiation_Shortwave_Direct_ReflectionFirst_Road_W_p_m2 + (1.0 - SkyViewFactor_Road_frac) * Albedo_Road_frac * Reflection_Garden_to_Wall_frac * Radiation_Shortwave_Direct_ReflectionFirst_Garden_W_p_m2) / Denominator_Reflection + Radiation_Shortwave_Direct_ReflectionFirst_Road_W_p_m2;
	//Radiation_Shortwave_Direct_ReflectionSum_Garden_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZSREF_SW_GD(JJ) = ((1.- PSVF_GD(JJ)) * PALB_GD(JJ) * ZREF0_SW_WL(JJ)+(1.- PSVF_GD(JJ)) * PALB_GD(JJ) * ZWORK1(JJ) * ZREF0_SW_RD(JJ)+(1.- PSVF_GD(JJ)) * PALB_GD(JJ) * ZWORK2(JJ) * ZREF0_SW_GD(JJ) )/ ZDENOM(JJ) + ZREF0_SW_GD(JJ)
	double Radiation_Shortwave_Direct_ReflectionSum_Garden_W_p_m2 = ((1.0 - SkyViewFactor_Garden_frac) * Albedo_Garden_frac * Radiation_Shortwave_Direct_ReflectionFirst_Wall_W_p_m2 + (1.0 - SkyViewFactor_Garden_frac) * Albedo_Garden_frac * Reflection_Road_to_Wall_frac * Radiation_Shortwave_Direct_ReflectionFirst_Road_W_p_m2 + (1.0 - SkyViewFactor_Garden_frac) * Albedo_Garden_frac * Reflection_Garden_to_Wall_frac * Radiation_Shortwave_Direct_ReflectionFirst_Garden_W_p_m2) / Denominator_Reflection + Radiation_Shortwave_Direct_ReflectionFirst_Garden_W_p_m2;
	//Total Radiation Received
	//Note: Snow will change Albedo_Road_frac to Albedo_Road_w_Snow_frac
	//Radiation_Shortwave_Direct_w_Reflected_Road_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZABS_SW_RD(JJ) = (1.-T%XALB_ROAD(JJ)) * (ZSW_RD(JJ) + ZSREF_SW_WL(JJ) * (1.- T%XSVF_ROAD(JJ)))
	double Radiation_Shortwave_Direct_w_Reflected_Road_W_p_m2 = (1.0 - Albedo_Road_frac) * Radiation_Shortwave_Direct_Road_W_p_m2 + Radiation_Shortwave_Direct_ReflectionSum_Wall_W_p_m2 * (1.0 - SkyViewFactor_Road_frac);
	//Radiation_Shortwave_Direct_w_Reflected_Garden_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZABS_SW_GD(JJ) = (1# - PALB_GD(JJ)) * (ZSW_GD(JJ) + ZSREF_SW_WL(JJ) * (1# - PSVF_GD(JJ)))
	double Radiation_Shortwave_Direct_w_Reflected_Garden_W_p_m2 = (1.0 - Albedo_Garden_frac) * Radiation_Shortwave_Direct_Garden_W_p_m2+ Radiation_Shortwave_Direct_ReflectionSum_Wall_W_p_m2 * (1.0 - SkyViewFactor_Garden_frac);
	//Radiation_Shortwave_Direct_w_Reflected_Wall_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZABS_SW_WL(JJ) = (1.-T%XALB_WALL(JJ))* (ZSW_WL(JJ)+ ZSREF_SW_RD(JJ) * T%XSVF_WALL(JJ)*ZRD(JJ) + ZSREF_SW_GD(JJ) * T%XSVF_WALL(JJ)*ZGD(JJ) + ZSREF_SW_WL(JJ) * (1.-2.*T%XSVF_WALL(JJ)))
	double Radiation_Shortwave_Direct_w_Reflected_Wall_W_p_m2 = (1.0 - Albedo_Wall_frac) * Radiation_Shortwave_Direct_Wall_W_p_m2 + Radiation_Shortwave_Direct_ReflectionSum_Road_W_p_m2 * SkyViewFactor_Wall_frac * Ratio_Road_to_Ground + Radiation_Shortwave_Direct_ReflectionSum_Garden_W_p_m2 * SkyViewFactor_Wall_frac * Ratio_Garden_to_Ground + Radiation_Shortwave_Direct_ReflectionSum_Wall_W_p_m2 * (1.0 - 2.0 * SkyViewFactor_Wall_frac);
	//Radiation_Shortwave_Direct_w_Reflected_Wall_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZABS_SW_WIN(JJ) = (1.-T%XALB_WIN(JJ))* (ZSW_WL(JJ)+ ZSREF_SW_RD(JJ) * T%XSVF_WALL(JJ)*ZRD(JJ) + ZSREF_SW_GD(JJ) * T%XSVF_WALL(JJ)*ZGD(JJ) + ZSREF_SW_WL(JJ) * (1.-2.*T%XSVF_WALL(JJ)))
	double Radiation_Shortwave_Direct_w_Reflected_Window_W_p_m2 = (1.0 - Albedo_Window_frac) * Radiation_Shortwave_Direct_Wall_W_p_m2+ Radiation_Shortwave_Direct_ReflectionSum_Road_W_p_m2 * SkyViewFactor_Wall_frac * Ratio_Road_to_Ground + Radiation_Shortwave_Direct_ReflectionSum_Garden_W_p_m2 * SkyViewFactor_Wall_frac * Ratio_Garden_to_Ground + Radiation_Shortwave_Direct_ReflectionSum_Wall_W_p_m2 * (1.0 - 2.0 * SkyViewFactor_Wall_frac);
	//End Solar Reflections for Direct _____________________________________________________________________________________________


	//Solar Reflections for Diffuse _____________________________________________________________________________________________
	//First Reflection
	double Radiation_Shortwave_Diffuse_ReflectionFirst_Road_W_p_m2 = Albedo_Road_frac * Radiation_Shortwave_Diffuse_Road_W_p_m2;
	double Radiation_Shortwave_Diffuse_ReflectionFirst_Garden_W_p_m2 = Albedo_Road_frac * Radiation_Shortwave_Diffuse_Garden_W_p_m2;
	double Radiation_Shortwave_Diffuse_ReflectionFirst_Wall_W_p_m2 = Albedo_Road_frac * Radiation_Shortwave_Diffuse_Wall_W_p_m2;
	//Sum of Solar Reflections
	//Denominator_Reflection function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZDENOM(JJ) = 1. - (1.-2.*T%XSVF_WALL(JJ)) * T%XALB_WALL(JJ) - (1. - T%XSVF_ROAD(JJ))* T%XSVF_WALL(JJ)*T%XALB_WALL(JJ)*ZAALB_RD(JJ)*ZRD(JJ) - (1. - PSVF_GD(JJ))* T%XSVF_WALL(JJ)*T%XALB_WALL(JJ)*PALB_GD(JJ)*ZGD(JJ)
	Denominator_Reflection = 1.0 - (1.0 - 2 * SkyViewFactor_Wall_frac) * Albedo_Wall_frac - (1.0 - SkyViewFactor_Road_frac) * SkyViewFactor_Wall_frac * Albedo_Wall_frac * Albedo_Road_frac * Ratio_Road_to_Ground - (1.0 - SkyViewFactor_Garden_frac) * SkyViewFactor_Wall_frac * Albedo_Wall_frac * Albedo_Garden_frac * Ratio_Garden_to_Ground;
	//Reflection_Road_to_Wall_frac function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZWORK1(JJ) = T%XSVF_WALL(JJ) * T%XALB_WALL(JJ) * ZRD(JJ)
	Reflection_Road_to_Wall_frac = SkyViewFactor_Wall_frac * Albedo_Wall_frac * Ratio_Road_to_Ground;
	//Reflection_Garden_to_Wall_frac function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZWORK2(JJ) = T%XSVF_WALL(JJ) * T%XALB_WALL(JJ) * ZGD(JJ)
	Reflection_Garden_to_Wall_frac = SkyViewFactor_Wall_frac * Albedo_Wall_frac * Ratio_Garden_to_Ground;
	//Radiation_Shortwave_Diffuse_ReflectionSum_Wall_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZSREF_SW_WL(JJ) = (  ZREF0_SW_WL(JJ) + ZWORK1(JJ) *ZREF0_SW_RD(JJ)+ ZWORK2(JJ) *ZREF0_SW_GD(JJ)) / ZDENOM(JJ)
	double Radiation_Shortwave_Diffuse_ReflectionSum_Wall_W_p_m2 = (Radiation_Shortwave_Diffuse_ReflectionFirst_Wall_W_p_m2	+ Reflection_Road_to_Wall_frac * Radiation_Shortwave_Diffuse_ReflectionFirst_Road_W_p_m2 + Reflection_Garden_to_Wall_frac * Radiation_Shortwave_Diffuse_ReflectionFirst_Garden_W_p_m2) / Denominator_Reflection;
	//Radiation_Shortwave_Diffuse_ReflectionSum_Road_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZSREF_SW_RD(JJ) = ((1. - T % XSVF_ROAD(JJ)) * ZAALB_RD(JJ) * ZREF0_SW_WL(JJ) + (1. - T % XSVF_ROAD(JJ)) * ZAALB_RD(JJ) * ZWORK1(JJ) * ZREF0_SW_RD(JJ) + (1. - T % XSVF_ROAD(JJ)) * ZAALB_RD(JJ) * ZWORK2(JJ) * ZREF0_SW_GD(JJ)) / ZDENOM(JJ) + ZREF0_SW_RD(JJ)
	double Radiation_Shortwave_Diffuse_ReflectionSum_Road_W_p_m2 = ((1.0 - SkyViewFactor_Road_frac) * Albedo_Road_frac * Radiation_Shortwave_Diffuse_ReflectionFirst_Wall_W_p_m2	+ (1.0 - SkyViewFactor_Road_frac) * Albedo_Road_frac * Reflection_Road_to_Wall_frac * Radiation_Shortwave_Diffuse_ReflectionFirst_Road_W_p_m2 + (1.0 - SkyViewFactor_Road_frac) * Albedo_Road_frac * Reflection_Garden_to_Wall_frac * Radiation_Shortwave_Diffuse_ReflectionFirst_Garden_W_p_m2) / Denominator_Reflection + Radiation_Shortwave_Diffuse_ReflectionFirst_Road_W_p_m2;
	//Radiation_Shortwave_Diffuse_ReflectionSum_Garden_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZSREF_SW_GD(JJ) = ((1.- PSVF_GD(JJ)) * PALB_GD(JJ) * ZREF0_SW_WL(JJ)+(1.- PSVF_GD(JJ)) * PALB_GD(JJ) * ZWORK1(JJ) * ZREF0_SW_RD(JJ)+(1.- PSVF_GD(JJ)) * PALB_GD(JJ) * ZWORK2(JJ) * ZREF0_SW_GD(JJ) )/ ZDENOM(JJ) + ZREF0_SW_GD(JJ)
	double Radiation_Shortwave_Diffuse_ReflectionSum_Garden_W_p_m2 = ((1.0 - SkyViewFactor_Garden_frac) * Albedo_Garden_frac * Radiation_Shortwave_Diffuse_ReflectionFirst_Wall_W_p_m2	+ (1.0 - SkyViewFactor_Garden_frac) * Albedo_Garden_frac * Reflection_Road_to_Wall_frac * Radiation_Shortwave_Diffuse_ReflectionFirst_Road_W_p_m2 + (1.0 - SkyViewFactor_Garden_frac) * Albedo_Garden_frac * Reflection_Garden_to_Wall_frac * Radiation_Shortwave_Diffuse_ReflectionFirst_Garden_W_p_m2) / Denominator_Reflection + Radiation_Shortwave_Diffuse_ReflectionFirst_Garden_W_p_m2;
	//Total Radiation Received
	//Note: Snow will change Albedo_Road_frac to Albedo_Road_w_Snow_frac
	//Radiation_Shortwave_Diffuse_w_Reflected_Road_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZABS_SW_RD(JJ) = (1.-T%XALB_ROAD(JJ)) * (ZSW_RD(JJ) + ZSREF_SW_WL(JJ) * (1.- T%XSVF_ROAD(JJ)))
	double Radiation_Shortwave_Diffuse_w_Reflected_Road_W_p_m2 = (1.0 - Albedo_Road_frac) * Radiation_Shortwave_Diffuse_Road_W_p_m2	+ Radiation_Shortwave_Diffuse_ReflectionSum_Wall_W_p_m2 * (1.0 - SkyViewFactor_Road_frac);
	//Radiation_Shortwave_Diffuse_w_Reflected_Garden_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZABS_SW_GD(JJ) = (1# - PALB_GD(JJ)) * (ZSW_GD(JJ) + ZSREF_SW_WL(JJ) * (1# - PSVF_GD(JJ)))
	double Radiation_Shortwave_Diffuse_w_Reflected_Garden_W_p_m2 = (1.0 - Albedo_Garden_frac) * Radiation_Shortwave_Diffuse_Garden_W_p_m2 + Radiation_Shortwave_Diffuse_ReflectionSum_Wall_W_p_m2 * (1.0 - SkyViewFactor_Garden_frac);
	//Radiation_Shortwave_Diffuse_w_Reflected_Wall_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZABS_SW_WL(JJ) = (1.-T%XALB_WALL(JJ))* (ZSW_WL(JJ)+ ZSREF_SW_RD(JJ) * T%XSVF_WALL(JJ)*ZRD(JJ) + ZSREF_SW_GD(JJ) * T%XSVF_WALL(JJ)*ZGD(JJ) + ZSREF_SW_WL(JJ) * (1.-2.*T%XSVF_WALL(JJ)))
	double Radiation_Shortwave_Diffuse_w_Reflected_Wall_W_p_m2 = (1.0 - Albedo_Wall_frac) * Radiation_Shortwave_Diffuse_Wall_W_p_m2	+ Radiation_Shortwave_Diffuse_ReflectionSum_Road_W_p_m2 * SkyViewFactor_Wall_frac * Ratio_Road_to_Ground + Radiation_Shortwave_Diffuse_ReflectionSum_Garden_W_p_m2 * SkyViewFactor_Wall_frac * Ratio_Garden_to_Ground + Radiation_Shortwave_Diffuse_ReflectionSum_Wall_W_p_m2 * (1.0 - 2.0 * SkyViewFactor_Wall_frac);
	//Radiation_Shortwave_Diffuse_w_Reflected_Wall_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
	//Note: ZABS_SW_WIN(JJ) = (1.-T%XALB_WIN(JJ))* (ZSW_WL(JJ)+ ZSREF_SW_RD(JJ) * T%XSVF_WALL(JJ)*ZRD(JJ) + ZSREF_SW_GD(JJ) * T%XSVF_WALL(JJ)*ZGD(JJ) + ZSREF_SW_WL(JJ) * (1.-2.*T%XSVF_WALL(JJ)))
	double Radiation_Shortwave_Diffuse_w_Reflected_Window_W_p_m2 = (1.0 - Albedo_Window_frac) * Radiation_Shortwave_Diffuse_Wall_W_p_m2+ Radiation_Shortwave_Diffuse_ReflectionSum_Road_W_p_m2 * SkyViewFactor_Wall_frac * Ratio_Road_to_Ground + Radiation_Shortwave_Diffuse_ReflectionSum_Garden_W_p_m2 * SkyViewFactor_Wall_frac * Ratio_Garden_to_Ground + Radiation_Shortwave_Diffuse_ReflectionSum_Wall_W_p_m2 * (1.0 - 2.0 * SkyViewFactor_Wall_frac);
	//End Solar Reflections for Diffuse _____________________________________________________________________________________________

	//Adjustment for Direct Radiation (not Diffuse) _________________________________________________________________________________
	double Radiation_Shortwave_Direct_w_Reflected_Wall_A_W_p_m2 = 0;
	double Radiation_Shortwave_Direct_w_Reflected_Wall_B_W_p_m2 = 0;
	//If Direction_Road_rad < 0 then road has no specified direction and If Symmetry_Wall_int > 0 then walls symmetrical
	if (Direction_Road_rad < 0 || Symmetry_Wall_int > 0) {
		Radiation_Shortwave_Direct_w_Reflected_Wall_A_W_p_m2 = Radiation_Shortwave_Direct_w_Reflected_Wall_W_p_m2;
		Radiation_Shortwave_Direct_w_Reflected_Wall_B_W_p_m2 = Radiation_Shortwave_Direct_w_Reflected_Wall_W_p_m2;
	}
	//Else If Direction_Road_rad >= 0 then road has specified direction or If Symmetry_Wall_int < 0 then walls are not symmetrical
	//Note: For N-S road Wall_A is west wall and east facing, Wall_B is west facing
	//Note: For E-W road Wall_A is north wall and south facing, Wall_B is north facing
	else {
		//Radiation_Shortwave_Direct_w_Reflected_Wall_Extra_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
		//Note: ZDW = (1.-T%XALB_WALL(:)) * ZAALB_WL(:) * (1.-2.*T%XSVF_WALL(:)) / (1.+ZAALB_WL(:)*(1.-2.*T%XSVF_WALL(:)))* 0.5 * (ZDIR_SW_WL_A(:)-ZDIR_SW_WL_B(:))+ 0.5 * (1.-T%XALB_WALL(:)) * (ZDIR_SW_WL_A-ZDIR_SW_WL_B)
		double Radiation_Shortwave_Direct_w_Reflected_Wall_Extra_W_p_m2 = (1.0 - Albedo_Wall_frac) * Albedo_WindowWall_frac * (1.0 - 2.0 * SkyViewFactor_Wall_frac) / (1.0 + Albedo_WindowWall_frac * (1.0 - 2.0 * SkyViewFactor_Wall_frac))	* 0.5 * (Radiation_Shortwave_Direct_Wall_A_W_p_m2 - Radiation_Shortwave_Direct_Wall_B_W_p_m2) + 0.5 * (1.0 - Albedo_Wall_frac) * (Radiation_Shortwave_Direct_Wall_A_W_p_m2 - Radiation_Shortwave_Direct_Wall_B_W_p_m2);
		//Radiation_Shortwave_Direct_w_Reflected_Wall_A_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
		//Note: ZABS_DIR_SW_WL_A = ZABS_DIR_SW_WL + ZDW
		Radiation_Shortwave_Direct_w_Reflected_Wall_A_W_p_m2 = Radiation_Shortwave_Direct_w_Reflected_Wall_W_p_m2 + Radiation_Shortwave_Direct_w_Reflected_Wall_Extra_W_p_m2;
		//Radiation_Shortwave_Direct_w_Reflected_Wall_B_W_p_m2 function from TEB code SUBROUTINE urban_solar_abs.F90
		//Note: ZABS_DIR_SW_WL_B = ZABS_DIR_SW_WL - ZDW
		Radiation_Shortwave_Direct_w_Reflected_Wall_B_W_p_m2 = Radiation_Shortwave_Direct_w_Reflected_Wall_W_p_m2 - Radiation_Shortwave_Direct_w_Reflected_Wall_Extra_W_p_m2;
	}
	//End Adjustment for Direct Radiation (not Diffuse) _________________________________________________________________________________
	//End Algorithm for Roads and Walls ---------------------------------------------------------------------------------------------------------------------------------------

	//Limit canyon facet direct radiation to no larger than direct radiation
	if (Radiation_Shortwave_Direct_Road_W_p_m2 > Radiation_Shortwave_Direct_W_p_m2) { Radiation_Shortwave_Direct_Road_W_p_m2 = Radiation_Shortwave_Direct_W_p_m2; }
	if (Radiation_Shortwave_Direct_Garden_W_p_m2 > Radiation_Shortwave_Direct_W_p_m2) { Radiation_Shortwave_Direct_Garden_W_p_m2 = Radiation_Shortwave_Direct_W_p_m2; }
	if (Radiation_Shortwave_Direct_Wall_W_p_m2 > Radiation_Shortwave_Direct_W_p_m2) { Radiation_Shortwave_Direct_Wall_W_p_m2 = Radiation_Shortwave_Direct_W_p_m2; }
	if (Radiation_Shortwave_Direct_Wall_A_W_p_m2 > Radiation_Shortwave_Direct_W_p_m2) { Radiation_Shortwave_Direct_Wall_A_W_p_m2 = Radiation_Shortwave_Direct_W_p_m2; }
	if (Radiation_Shortwave_Direct_Wall_B_W_p_m2 > Radiation_Shortwave_Direct_W_p_m2) { Radiation_Shortwave_Direct_Wall_B_W_p_m2 = Radiation_Shortwave_Direct_W_p_m2; }

	//Total of direct and diffuse radiation
	Radiation_Shortwave_Direct_Diffuse_Road_W_p_m2 = Radiation_Shortwave_Direct_w_Reflected_Road_W_p_m2 + Radiation_Shortwave_Diffuse_w_Reflected_Road_W_p_m2;
	Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2 = Radiation_Shortwave_Direct_w_Reflected_Garden_W_p_m2 + Radiation_Shortwave_Diffuse_w_Reflected_Garden_W_p_m2;
	Radiation_Shortwave_Direct_Diffuse_Wall_W_p_m2 = Radiation_Shortwave_Direct_w_Reflected_Wall_W_p_m2 + Radiation_Shortwave_Diffuse_w_Reflected_Wall_W_p_m2;
	Radiation_Shortwave_Direct_Diffuse_Roof_W_p_m2 = Radiation_Shortwave_Direct_Roof_W_p_m2 + Radiation_Shortwave_Diffuse_Roof_W_p_m2;

	//Radiation_Shortwave_Direct_Diffuse_TotalCanyon_W_p_m2 is weighted sum of Radiation_Shortwave_Direct_Diffuse_Road_W_p_m2 _Garden_W_p_m2 and _Wall_W_p_m2
	Radiation_Shortwave_Direct_Diffuse_TotalCanyon_W_p_m2 = Ratio_Road_to_Ground * Radiation_Shortwave_Direct_Diffuse_Road_W_p_m2 + Ratio_Garden_to_Ground * Radiation_Shortwave_Direct_Diffuse_Garden_W_p_m2	+ Radiation_Shortwave_Direct_Diffuse_Wall_W_p_m2;
}


//Consider refactor to include roof in temperature calculations if at height where appropriate for urban canopy
//Tair_AbsHumidity_LayerBalance function computes mesoscale air temperature and absolute humidity based on urban canopy air temperature, humidity and resistances
//Note: If reference station, then called from SimulationCoordinator::RunTemperatureSpatialModel and iteration will find mesoscale air and humidity without numerical method
//Note: If local station, then called from HeatFluxCal::Tair_AbsHumidity_LayerBalance_NumericalMethod and iteration will find local grid canopy air and humidity using Ta_est
//Note: Based on Yang et al. (2013) there are 10 equations, (1), (2), (9), (10), (11), (12), (13), (19), (20), and (21) 
//Note: Based on Yang et al. (2013) there are 10 unknowns, H_total_W_p_m2, LE_total_W_p_m2, H1, H2, H3, LE1, LE2, LE3, Tair_localCell_K, Tdew_localCell_K.
//Note: All Energy Flux Values of H and LE computed below are adjusted in RescaleVariables_CoolAir function
void HeatFluxCal::Tair_AbsHumidity_LayerBalance(Inputs* input, DataFolder* folder, DataFolder* reffolder, int timeStep)
{
	//Tair_mesoScale_K (K), air temperature of shared upper mesoscale layer initialized to Tair_localCell_K (K), air temperature at urban canopy layer
	//Note: Tair_mesoScale_K (K) is updated in Tair_AbsHumidity_LayerBalance function using Eq 1 from Yang et al. (2013)
	//Note: If reference station, then Tair_localCell_K (K) defined by input time series | If local station, then Tair_localCell_K defined by Ta_est (K) in Tair_AbsHumidity_LayerBalance_NumericalMethod
	Tair_mesoScale_K = Tair_localCell_K;

	//Tair_localCell_C (C) is converted from Tair_localCell_K (K) to degrees C by subtracting 273.15
	double Tair_localCell_C = Tair_localCell_K - 273.15;
	//Tdew_localCell_C (C) is converted from Tdew_localCell_K (K) to degrees C by subtracting 273.15
	double Tdew_localCell_C = Tdew_localCell_K - 273.15;
	//VaporPressure_Saturated_kPa (kPa) as Tetens' formula in Eq 4.2.2 Shuttleworth (1993), e_kPa=0.6108*exp[(17.27*T_C)/(237.3+T_C)]
	double VaporPressure_Saturated_kPa = 0.6108 * exp((17.27 * Tair_localCell_C) / (237.3 + Tair_localCell_C));
	//VaporPressure_Actual_kPa (kPa) as Tetens' formula in Eq 4.2.2 Shuttleworth (1993), e_kPa=0.6108*exp[(17.27*T_C)/(237.3+T_C)]
	double VaporPressure_Actual_kPa = 0.6108 * exp((17.27 * Tdew_localCell_C) / (237.3 + Tdew_localCell_C));

	//AbsHumidity_mesoScale_kg_p_m3 (kg/m3) is absolute humidity actual of mesoscale layer from Eq 4.10 of Stull (2017), AH = e/(Rv*T_K)
	//Note: Initialized to the absolute humidity at urban canopy layer and updated in Tair_AbsHumidity_LayerBalance function using Eq 2 from Yang et al. (2013)
	//Note: If reference station, then AbsHumidity_mesoScale_kg_p_m3 (kg/m3) defined by input time series or 
	//Note: If local station, then AbsHumidity_mesoScale_kg_p_m3 defined by Td_est (K) in Tair_AbsHumidity_LayerBalance_NumericalMethod
	//Note: Absolute humidity Eq 4.10 of Stull (2017) explicitly uses vapor pressure, e, and is equivalent to Eq 18 of Yang et al. (2013) as follows ...
	//Note: ... e in Eq 4.2.2 Shuttleworth (1992) and Eq 4.2 Stull (2017) equivalent: Tair_K - 35.85 = 237.3 + Tair_C | 17.27 * (Tair_K - 273.15) = 17.27 * Tair_C
	//Note: ... Coefficient 1.324 in Eq 18 is derived as 1.324 (kg/m3) = e0 / Rv = 0.6108 kPa / 4.61x10–1 kPa·K–1·m3·kg–1
	AbsHumidity_mesoScale_kg_p_m3 = VaporPressure_Actual_kPa / (Gas_constant_water_vapor_kPa_p_K_m3_kg * Tdew_localCell_K);
	//AerodynamicResistance_CanopyToMesoLayer function called to calculate the aerodynamic resistance factors
	resistanceVar->AerodynamicResistance_CanopyToMesoLayer(input, folder, reffolder, WindSpeed_Reference_m_p_s, Height_LandCover_Average_m, timeStep);

	//AbsHumiditySat_localCell_kg_p_m3 (kg/m3) is absolute humidity saturated of local cell from Eq 4.10 of Stull (2017), AH = e/(Rv*T_K)
	AbsHumiditySat_localCell_kg_p_m3 = VaporPressure_Saturated_kPa / (Gas_constant_water_vapor_kPa_p_K_m3_kg * Tair_localCell_K);
	//AbsHumidityAct_localCell_kg_p_m3 (kg/m3) is absolute humidity actual of local cell from Eq 4.10 of Stull (2017), AH = e/(Rv*T_K)
	AbsHumidityAct_localCell_kg_p_m3 = VaporPressure_Actual_kPa / (Gas_constant_water_vapor_kPa_p_K_m3_kg * Tdew_localCell_K);

	//Gradient of saturated absolute humidity, given above Eq 18 in Yang et al (2013); attributed by Yang et al. (2013) to Lawrence, 2005.
	//Note: Tair_K - 35.85 = 237.3 + Tair_C
	AbsHumidityGradient = -AbsHumiditySat_localCell_kg_p_m3 * (-4169.56 + Tair_localCell_K) * (-0.308 + Tair_localCell_K) / Tair_localCell_K /
		(-35.85 + Tair_localCell_K) / (-35.85 + Tair_localCell_K);

	//If ImperviousCover_noTreeCanopy_frac > Constant_1E_negative4 then calculate ImpH_W_p_m2 and ImpLE_W_p_m2 for use in areas with ImperviousCover_noTreeCanopy_frac 
	if (ImperviousCover_noTreeCanopy_frac > Constant_1E_negative4) {
		//Note: Derivation combines Eq 9 and 19 from Yang, Endreny, Nowak (2013), expand, combine ImpH_W_p_m2 terms on LHS, and isolate ImpH_W_p_m2 
		//Note: Eq 19 rImpH/rImpLE = 1 when rImpH = rImpLE; Eq 19 ImpC = 1 = (S/S_max)^(2/3).
		//1. ImpH_W_p_m2 = ImpNR_W_p_m2 + Imp_AH_W_p_m2 - ImpDeltaQ_W_p_m2 - ImpLE_W_p_m2 = ImpNR_W_p_m2 + Imp_AH_W_p_m2 - ImpDeltaQ_W_p_m2 - [(LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m + (LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * ImpH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m) / (resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)] * pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0)
		//2. ImpH_W_p_m2 = ImpNR_W_p_m2 + Imp_AH_W_p_m2 - ImpDeltaQ_W_p_m2 - pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m - pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * ImpH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m / (resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)
		//3. ImpH_W_p_m2 + (pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * ImpH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m) / (resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) = ImpNR_W_p_m2 + Imp_AH_W_p_m2 - ImpDeltaQ_W_p_m2 - pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m 
		//4. ImpH_W_p_m2 * ((pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m) / (resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1) = ImpNR_W_p_m2 + Imp_AH_W_p_m2 - ImpDeltaQ_W_p_m2 - pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m
		//5. ImpH_W_p_m2 = (ImpNR_W_p_m2 + Imp_AH_W_p_m2 - ImpDeltaQ_W_p_m2 - pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m) / ((pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m) / (resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1)

		//ImpH_W_p_m2 (W/m2) as impervious sensible heat derived above from Eq 9 and 20 of Yang et al. (2013) 
		//Note: H is function of terms comprising LE, and H must be computed before LE can be computed as function of H
		//Note: H can become a large negative value when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and ...
		//Note: ... Resistance_Aerodynamic_Impervious_s_p_m is small
		ImpH_W_p_m2 = (ImpNR_W_p_m2 + Imp_AH_W_p_m2 - ImpDeltaQ_W_p_m2 - pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m) /	((pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m) / (resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1);
		//Note: Below is ImpH_W_p_m2 (W/m2) as impervious sensible heat in optional simplified equation w/ ImpC:
		//Note: If ImpC = pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0) / resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m then simplify above to:
		//ImpH_W_p_m2 = (ImpNR_W_p_m2 + Imp_AH_W_p_m2 - ImpDeltaQ_W_p_m2 - ImpC * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3)) / (ImpC * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m / HeatCapacity_Air_J_p_kg_p_K / Density_Air_kg_p_m3 + 1);

		//ImpLE_W_p_m2 (W/m2) is impervious latent heat in full equation based on Eq 19 of Yang et al. (2013)
		//Note: LE is function of H, so H must be computed prior to LE
		//Note: LE can become large when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and Resistance_Aerodynamic_Impervious_s_p_m is small
		ImpLE_W_p_m2 = (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * ImpH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m / (resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * pow(Saturation_ImperviousStorage_frac, 2.0 / 3.0);
		//Note: Below is ImpLE_W_p_m2 (W/m2) in simplified energy balance Eq 9 of Yang et al. (2013)
		//ImpLE_W_p_m2 = ImpNR_W_p_m2 + Imp_AH_W_p_m2 - ImpDeltaQ_W_p_m2 - ImpH_W_p_m2;
		//Note: Below is ImpLE_W_p_m2 (W/m2) as impervious latent heat in optional simplified equation w/ ImpC:
		//ImpLE_W_p_m2 = (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * ImpH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Impervious_s_p_m / Density_Air_kg_p_m3 / HeatCapacity_Air_J_p_kg_p_K) * ImpC;
	}
	//Else If there is no impervious cover
	else {
		//Imp_AH_W_p_m2 (W/m2) is impervious fraction of AnthropogenicHeat_Flux_Total_Wpm2 on pixel
		Imp_AH_W_p_m2 = 0;
		//Set values to zero if there is no cover
		ImpH_W_p_m2 = 0.0; ImpLE_W_p_m2 = 0.0;
	}

	//If TreeCover_frac >  Constant_1E_negative4 cover threshold
	if (TreeCover_frac > Constant_1E_negative4) {
		//Note: Derivation combines Eq 9, 22 and 23 from Yang et al. (2013), expand, combine TreeH_W_p_m2 terms on LHS, and isolate TreeH_W_p_m2 
		//Note: Eq 22 & 23 rTreeH/rTreeLE = 1 when rTreeH = rTreeLE; Eq 22 (S/Smax)^(2/3)/Resistance_Aerodynamic_Tree_s_p_m = TreeCE; Eq 23 [1-(S/Smax)^(2/3)]/(resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) = TreeCT
		//1. TreeH_W_p_m2 = TreeNR_W_p_m2 + Tree_AH_W_p_m2 - TreeDeltaQ_W_p_m2 - TreeLE_W_p_m2 = TreeNR_W_p_m2 + Tree_AH_W_p_m2 - TreeDeltaQ_W_p_m2 - (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * TreeH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m  / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) - (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * TreeH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m  / ((resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0))
		//2. TreeH_W_p_m2 = TreeNR_W_p_m2 + Tree_AH_W_p_m2 - TreeDeltaQ_W_p_m2 - pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Tree_s_p_m - (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) - pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * TreeH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) - (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * TreeH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / ((resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)
		//3. TreeH_W_p_m2 + pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * TreeH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * TreeH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / ((resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) = (TreeNR_W_p_m2 + Tree_AH_W_p_m2 - TreeDeltaQ_W_p_m2 - ((pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Tree_s_p_m) + (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m)))
		//4. TreeH_W_p_m2 * (pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / ((resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1) = (TreeNR_W_p_m2 + Tree_AH_W_p_m2 - TreeDeltaQ_W_p_m2 - ((pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Tree_s_p_m) + (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m)))
		//5. TreeH_W_p_m2 = (TreeNR_W_p_m2 + Tree_AH_W_p_m2 - TreeDeltaQ_W_p_m2 - ((pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Tree_s_p_m) + (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m))) / (pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / ((resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1)

		//TreeH_W_p_m2 (W/m2) as tree sensible heat derived above from Eq 9, 22, and 23 of Yang et al. (2013); note LE embedded with RHS radiation terms
		//Note: H is function of terms comprising LE, and H must be computed before LE can be computed as function of H
		//Note: H can become a large negative value when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and ...
		//Note: ... Resistance_Aerodynamic_Impervious_s_p_m is small
		TreeH_W_p_m2 = (TreeNR_W_p_m2 + Tree_AH_W_p_m2 - TreeDeltaQ_W_p_m2 - ((pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg *	(AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Tree_s_p_m) + (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m))) / (pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m /	(resistanceVar->Resistance_Aerodynamic_Tree_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient *	resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / ((resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1);
		//Note: Below is TreeH_W_p_m2 (W/m2) as tree sensible heat in optional simplified equation w/ TreeC:
		//Note: If TreeC = TreeCE + TreeCT = pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) / resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + 
		//Note: ... (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) then simplify above to:
		//TreeH_W_p_m2 = (TreeNR_W_p_m2 + Tree_AH_W_p_m2 - TreeDeltaQ_W_p_m2 - TreeC * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3)) / (TreeC * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient / (Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1);

		//TreeLEE_W_p_m2 (W/m2) is tree evaporation latent heat in full equation based on Eq 22 of Yang et al. (2013)
		//Note: LE is function of H, so H must be computed prior to LE
		//Note: LE can become large when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and Resistance_Aerodynamic_Impervious_s_p_m is small
		TreeLEE_W_p_m2 = LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) /resistanceVar->Resistance_Aerodynamic_Tree_s_p_m * pow(Saturation_TreeStorage_frac, (2.0 / 3.0)) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * TreeH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / (resistanceVar->Resistance_Aerodynamic_Tree_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) * pow(Saturation_TreeStorage_frac, (2.0 / 3.0));
		//Note: Below is TreeLEE_W_p_m2 (W/m2) as tree evaporation latent heat in optional simplified equation w/ TreeCE:
		//TreeLEE_W_p_m2 = (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient *	TreeH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / (Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * TreeCE;


		//TreeLET_W_p_m2 (W/m2) is tree transpiration latent heat in full equation based on Eq 23 of Yang et al. (2013)
		//Note: LE is function of H, so H must be computed prior to LE
		//Note: LE can become large when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and Resistance_Aerodynamic_Impervious_s_p_m is small
		//Note: Resistance_Surface_Tree_s_p_m (s/m) is TreeMinimumResistance_s_p_m for no impervious cover, and is increased linearly with impervious cover
		TreeLET_W_p_m2 = LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) /(resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) * (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0)) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * TreeH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / ((resistanceVar->Resistance_Aerodynamic_Tree_s_p_m + resistanceVar->Resistance_Surface_Tree_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) * (1 - pow(Saturation_TreeStorage_frac, 2.0 / 3.0));
		//Note: Below is TreeLET_W_p_m2 (W/m2) as tree transpiration latent heat in optional simplified equation w/ TreeCT:
		//TreeLET_W_p_m2 = (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * TreeH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Tree_s_p_m / (Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * TreeCT;

		//TreeLE_W_p_m2 (W/m2) Tree latent energy total as Eq 21 of Yang et al. (2013)
		TreeLE_W_p_m2 = TreeLEE_W_p_m2 + TreeLET_W_p_m2;
	}
	//Else If there is no tree cover
	else {
		//Tree_AH_W_p_m2 (W/m2) is tree fraction of AnthropogenicHeat_Flux_Total_Wpm2 on pixel
		Tree_AH_W_p_m2 = 0;
		//Set values to zero if there is no cover
		TreeH_W_p_m2 = 0.0; TreeLEE_W_p_m2 = 0.0; TreeLET_W_p_m2 = 0.0; TreeLE_W_p_m2 = 0.0;
	}

	//If ShortVegCover_noTreeCanopy_frac >  Constant_1E_negative4 cover threshold
	if (ShortVegCover_noTreeCanopy_frac > Constant_1E_negative4) {
		//Note: Derivation combines Eq 9, 22 and 23 from Yang et al. (2013), expand, combine SVegH_W_p_m2 terms on LHS, and isolate SVegH_W_p_m2 
		//Note: Eq 22 & 23 rSVegH/rSVegLE = 1 when rSVegH = rSVegLE; Eq 22 (S/Smax)^(2/3)/Resistance_Aerodynamic_SVeg_s_p_m = SVegCE; Eq 23 [1-(S/Smax)^(2/3)]/(resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) = SVegCT
		//1. SVegH_W_p_m2 = SVegNR_W_p_m2 + SVeg_AH_W_p_m2 - SVegDeltaQ_W_p_m2 - SVegLE_W_p_m2 = SVegNR_W_p_m2 + SVeg_AH_W_p_m2 - SVegDeltaQ_W_p_m2 - (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SVegH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m  / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) - (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SVegH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m  / ((resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0))
		//2. SVegH_W_p_m2 = SVegNR_W_p_m2 + SVeg_AH_W_p_m2 - SVegDeltaQ_W_p_m2 - pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m - (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) - pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SVegH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) - (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SVegH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / ((resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)
		//3. SVegH_W_p_m2 + pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SVegH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SVegH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / ((resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) = (SVegNR_W_p_m2 + SVeg_AH_W_p_m2 - SVegDeltaQ_W_p_m2 - ((pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m) + (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m)))
		//4. SVegH_W_p_m2 * (pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / ((resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1) = (SVegNR_W_p_m2 + SVeg_AH_W_p_m2 - SVegDeltaQ_W_p_m2 - ((pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m) + (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m)))
		//5. SVegH_W_p_m2 = (SVegNR_W_p_m2 + SVeg_AH_W_p_m2 - SVegDeltaQ_W_p_m2 - ((pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m) + (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m))) / (pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / ((resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1)

		//SVegH_W_p_m2 (W/m2) as SVeg sensible heat derived above from Eq 9, 22, and 23 of Yang et al. (2013); note LE embedded with RHS radiation terms
		//Note: H is function of terms comprising LE, and H must be computed before LE can be computed as function of H
		//Note: H can become a large negative value when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and ...
		//Note: ... Resistance_Aerodynamic_Impervious_s_p_m is small
		SVegH_W_p_m2 = (SVegNR_W_p_m2 + SVeg_AH_W_p_m2 - SVegDeltaQ_W_p_m2 - ((pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m) + (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m))) / (pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m /	(resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / ((resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1);
		//Note: Below is SVegH_W_p_m2 (W/m2) as SVeg sensible heat in optional simplified equation w/ SVegC:
		//Note: If SVegC = SVegCE + SVegCT = pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) / resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + 
		//Note: ... (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) then simplify above to:
		//SVegH_W_p_m2 = (SVegNR_W_p_m2 + SVeg_AH_W_p_m2 - SVegDeltaQ_W_p_m2 - SVegC * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3)) / (SVegC * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient / (Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1);

		//SVegLEE_W_p_m2 (W/m2) is SVeg evaporation latent heat in full equation based on Eq 22 of Yang et al. (2013)
		//Note: LE is function of H, so H must be computed prior to LE
		//Note: LE can become large when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and Resistance_Aerodynamic_Impervious_s_p_m is small
		SVegLEE_W_p_m2 = LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m *	pow(Saturation_SVegStorage_frac, (2.0 / 3.0)) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SVegH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) * pow(Saturation_SVegStorage_frac, (2.0 / 3.0));
		//Note: Below is SVegLEE_W_p_m2 (W/m2) as SVeg evaporation latent heat in optional simplified equation w/ SVegCE:
		//SVegLEE_W_p_m2 = (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient *	SVegH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / (Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * SVegCE;

		//SVegLET_W_p_m2 (W/m2) is SVeg transpiration latent heat in full equation based on Eq 23 of Yang et al. (2013)
		//Note: LE is function of H, so H must be computed prior to LE
		//Note: LE can become large when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and Resistance_Aerodynamic_Impervious_s_p_m is small
		SVegLET_W_p_m2 = LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) * (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0)) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SVegH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / ((resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m + resistanceVar->Resistance_Surface_SVeg_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) * (1 - pow(Saturation_SVegStorage_frac, 2.0 / 3.0));
		//Note: Below is SVegLET_W_p_m2 (W/m2) as SVeg transpiration latent heat in optional simplified equation w/ SVegCT:
		//SVegLET_W_p_m2 = (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SVegH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_SVeg_s_p_m / (Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * SVegCT;

		//SVegLE_W_p_m2 (W/m2) SVeg latent energy total as Eq 21 of Yang et al. (2013)
		SVegLE_W_p_m2 = SVegLEE_W_p_m2 + SVegLET_W_p_m2;
	}
	//Else If there is no short vegetation cover
	else {
		//SVeg_AH_W_p_m2 (W/m2) is short vegetation fraction of AnthropogenicHeat_Flux_Total_Wpm2 on pixel
		SVeg_AH_W_p_m2 = 0;
		//Set values to zero if there is no cover
		SVegH_W_p_m2 = 0.0; SVegLEE_W_p_m2 = 0.0; SVegLET_W_p_m2 = 0.0; SVegLE_W_p_m2 = 0.0;
	}

	//If SoilCover_noTreeCanopy_frac >  Constant_1E_negative4 cover threshold
	//Consider Refactor to allow SoilH and SoilLE to represent surface layer when ponded water is present
	if (SoilCover_noTreeCanopy_frac > Constant_1E_negative4) {
		//Note: Derivation combines Eq 9 and 20 from Yang, Endreny, Nowak (2013), expand, combine SoilH_W_p_m2 terms on LHS, and isolate SoilH_W_p_m2 
		//Note: Eq 20 rSoilH/rSoilLE = 1 when rSoilH = rSoilLE; Eq 20 (1-D/Dmax) = Saturation_SoilStorage_frac
		//1. SoilH_W_p_m2 = SoilNR_W_p_m2 + Soil_AH_W_p_m2 - SoilDeltaQ_W_p_m2 - SoilLE_W_p_m2 = SoilNR_W_p_m2 + Soil_AH_W_p_m2 - SoilDeltaQ_W_p_m2 - [(LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) + (LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SoilH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Soil_s_p_m) / ((resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)] * Saturation_SoilStorage_frac
		//2. SoilH_W_p_m2 = SoilNR_W_p_m2 + Soil_AH_W_p_m2 - SoilDeltaQ_W_p_m2 - Saturation_SoilStorage_frac * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) - Saturation_SoilStorage_frac * (LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SoilH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Soil_s_p_m) / ((resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)
		//3. SoilH_W_p_m2 + (LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SoilH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Soil_s_p_m) / ((resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) = SoilNR_W_p_m2 + Soil_AH_W_p_m2 - SoilDeltaQ_W_p_m2 - Saturation_SoilStorage_frac * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) 
		//4. SoilH_W_p_m2 * ((LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Soil_s_p_m) / ((resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1) = SoilNR_W_p_m2 + Soil_AH_W_p_m2 - SoilDeltaQ_W_p_m2 - Saturation_SoilStorage_frac * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m)
		//5. SoilH_W_p_m2 = (SoilNR_W_p_m2 + Soil_AH_W_p_m2 - SoilDeltaQ_W_p_m2 - Saturation_SoilStorage_frac * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m)) / ((LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Soil_s_p_m) / ((resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1)

		//SoilH_W_p_m2 (W/m2) as soil sensible heat derived above from Eq 9 and 20 of Yang et al. (2013); note LE embedded with RHS radiation terms
		//Note: H is function of terms comprising LE, and H must be computed before LE can be computed as function of H
		//Note: H can become a large negative value when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and Resistance_Aerodynamic_Soil_s_p_m is small

		SoilH_W_p_m2 = (SoilNR_W_p_m2 + Soil_AH_W_p_m2 - SoilDeltaQ_W_p_m2 - Saturation_SoilStorage_frac * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m)) / ((Saturation_SoilStorage_frac * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Soil_s_p_m) / ((resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1);
		//Note: Below is SoilH_W_p_m2 (W/m2) as soil sensible heat in optional simplified equation w/ SoilC:
		//Note: If SoilC = Saturation_SoilStorage_frac / (resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) then simplify above to:
		//SoilH_W_p_m2 = (SoilNR_W_p_m2 + Soil_AH_W_p_m2 - SoilDeltaQ_W_p_m2 - SoilC * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3)) / (SoilC * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Soil_s_p_m / (HeatCapacity_Air_J_p_kg_p_K * Density_Air_kg_p_m3) + 1);

		//SoilLE_W_p_m2 (W/m2) is soil latent heat in full equation based on Eq 20 of Yang et al. (2013)
		//Note: LE is function of H, so H must be computed prior to LE
		//Note: LE can become large when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and Resistance_Aerodynamic_Soil_s_p_m is small
		SoilLE_W_p_m2 = (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / (resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * SoilH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Soil_s_p_m / ((resistanceVar->Resistance_Aerodynamic_Soil_s_p_m + resistanceVar->Resistance_Surface_Soil_s_p_m) * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * Saturation_SoilStorage_frac;
		//Note: Below is SoilLE_W_p_m2 (W/m2) in simplified energy balance Eq 9 of Yang et al. (2013)
		//SoilLE_W_p_m2 = SoilNR_W_p_m2 + Soil_AH_W_p_m2 - SoilDeltaQ_W_p_m2 - SoilH_W_p_m2;
		//Note: Below is SoilLE_W_p_m2 (W/m2) as soil latent heat in optional simplified equation w/ SoilC:
		//SoilLE_W_p_m2 = (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient*SoilH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Soil_s_p_m / Density_Air_kg_p_m3 / HeatCapacity_Air_J_p_kg_p_K) * SoilC;
	}
	//Else If there is no soil cover
	else {
		//Soil_AH_W_p_m2 (W/m2) is soil fraction of AnthropogenicHeat_Flux_Total_Wpm2 on pixel
		Soil_AH_W_p_m2 = 0;
		//Set values to zero if there is no cover
		SoilH_W_p_m2 = 0.0; SoilLE_W_p_m2 = 0.0;
	}

	//If WaterCover_noTreeCanopy_frac >  Constant_1E_negative4 cover threshold
	if (WaterCover_noTreeCanopy_frac > Constant_1E_negative4) {
		//Note: Derivation combines Eq 9 and 20 (modified for water by removing rSoilLE from 1st RHS term) from Yang, Endreny, Nowak (2013), expand, combine WaterH_W_p_m2 terms on LHS, and isolate WaterH_W_p_m2 
		//Note: Eq 20 rWaterH/rWaterLE = 1 when rWaterH = rWaterLE; Eq 20 WaterC = 1 = (1 - D/D_max) = (1 - 0/D_max); D = deficit = 0 for water.
		//1. WaterH_W_p_m2 = WaterNR_W_p_m2 + Water_AH_W_p_m2 - WaterDeltaQ_W_p_m2 - WaterLE_W_p_m2 = WaterNR_W_p_m2 + Water_AH_W_p_m2 - WaterDeltaQ_W_p_m2 - [(LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Water_s_p_m + (LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * WaterH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Water_s_p_m) / (resistanceVar->Resistance_Aerodynamic_Water_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)] * Saturation_WaterStorage_frac
		//2. WaterH_W_p_m2 = WaterNR_W_p_m2 + Water_AH_W_p_m2 - WaterDeltaQ_W_p_m2 - Saturation_WaterStorage_frac * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Water_s_p_m - Saturation_WaterStorage_frac * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * WaterH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Water_s_p_m / (resistanceVar->Resistance_Aerodynamic_Water_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)
		//3. WaterH_W_p_m2 + (Saturation_WaterStorage_frac * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * WaterH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Water_s_p_m) / (resistanceVar->Resistance_Aerodynamic_Water_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) = WaterNR_W_p_m2 + Water_AH_W_p_m2 - WaterDeltaQ_W_p_m2 - Saturation_WaterStorage_frac * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Water_s_p_m 
		//4. WaterH_W_p_m2 * ((Saturation_WaterStorage_frac * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Water_s_p_m) / (resistanceVar->Resistance_Aerodynamic_Water_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1) = WaterNR_W_p_m2 + Water_AH_W_p_m2 - WaterDeltaQ_W_p_m2 - Saturation_WaterStorage_frac * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Water_s_p_m
		//5. WaterH_W_p_m2 = (WaterNR_W_p_m2 + Water_AH_W_p_m2 - WaterDeltaQ_W_p_m2 - Saturation_WaterStorage_frac * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Water_s_p_m) / ((Saturation_WaterStorage_frac * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Water_s_p_m) / (resistanceVar->Resistance_Aerodynamic_Water_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1)

		//WaterH_W_p_m2 (W/m2) as water sensible heat derived above from Eq 9 and 20 of Yang et al. (2013); note LE embedded with RHS radiation terms
		WaterH_W_p_m2 = (WaterNR_W_p_m2 + Water_AH_W_p_m2 - WaterDeltaQ_W_p_m2 - Saturation_WaterStorage_frac * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Water_s_p_m) / ((Saturation_WaterStorage_frac * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Water_s_p_m) /	(resistanceVar->Resistance_Aerodynamic_Water_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) + 1);
		//Note: Below is WaterH_W_p_m2 (W/m2) as water sensible heat in optional simplified equation w/ WaterC:
		//Note: If WaterC = Saturation_WaterStorage_frac / resistanceVar->Resistance_Aerodynamic_Water_s_p_m then simplify above to:
		//WaterH_W_p_m2 = (WaterNR_W_p_m2 + Water_AH_W_p_m2 - WaterDeltaQ_W_p_m2 - WaterC * LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3)) / (WaterC * LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * resistanceVar->Resistance_Aerodynamic_Water_s_p_m / HeatCapacity_Air_J_p_kg_p_K / Density_Air_kg_p_m3 + 1);

		//WaterLE_W_p_m2 (W/m2) is water latent heat in full equation based on Eq 19 of Yang et al. (2013)
		//Note: LE is function of H, so H must be computed prior to LE
		//Note: LE can become large when AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3 is large and Resistance_Aerodynamic_Impervious_s_p_m is small
		WaterLE_W_p_m2 = (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) / resistanceVar->Resistance_Aerodynamic_Water_s_p_m + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * WaterH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Water_s_p_m / (resistanceVar->Resistance_Aerodynamic_Water_s_p_m * Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K)) * Saturation_WaterStorage_frac;
		//Note: Below is WaterLE_W_p_m2 (W/m2) in simplified energy balance Eq 9 of Yang et al. (2013)
		//WaterLE_W_p_m2 = WaterNR_W_p_m2 + Water_AH_W_p_m2 - WaterDeltaQ_W_p_m2 - WaterH_W_p_m2;
		//Note: Below is WaterLE_W_p_m2 (W/m2) as water latent heat in optional simplified equation w/ WaterC:
		//WaterLE_W_p_m2 = (LatentHeatVaporization_Water_J_p_kg * (AbsHumiditySat_localCell_kg_p_m3 - AbsHumidityAct_localCell_kg_p_m3) + LatentHeatVaporization_Water_J_p_kg * AbsHumidityGradient * WaterH_W_p_m2 * resistanceVar->Resistance_Aerodynamic_Water_s_p_m / Density_Air_kg_p_m3 / HeatCapacity_Air_J_p_kg_p_K) * WaterC;

	}
	//Else If there is no water cover
	else {
		//Water_AH_W_p_m2 (W/m2) is water fraction of AnthropogenicHeat_Flux_Total_Wpm2 on pixel
		Water_AH_W_p_m2 = 0;
		//Set values to zero if there is no cover
		WaterH_W_p_m2 = 0.0; WaterLE_W_p_m2 = 0.0;
	}

	//H_total_W_p_m2 (W/m2) is Eq 12 of Yang et al. (2013), total sensible heat flux (W/m^2), sum of fractional components from each cover type
	//Note: Theory of Yang et al. (2013) above Eq 12, H_localAir_to_mesoAir = H_ground_to_localAir in steady state to maintain energy balance
	H_total_W_p_m2 = (ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) * ImpH_W_p_m2 + TreeCover_frac * TreeH_W_p_m2 + ShortVegCover_noTreeCanopy_frac * SVegH_W_p_m2 + SoilCover_noTreeCanopy_frac * SoilH_W_p_m2 + WaterCover_noTreeCanopy_frac * WaterH_W_p_m2;
	//LE_total_W_p_m2 (W/m2) is Eq 13 of Yang et al. (2013), total latent heat flux (W/m^2), sum of fractional components from each cover type
	//Note: Theory of Yang et al. (2013) above Eq 12, LE_localAir_to_mesoAir = LE_ground_to_localAir in steady state to maintain energy balance
	LE_total_W_p_m2 = (ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) * ImpLE_W_p_m2 + TreeCover_frac * TreeLE_W_p_m2 + ShortVegCover_noTreeCanopy_frac * SVegLE_W_p_m2 + SoilCover_noTreeCanopy_frac * SoilLE_W_p_m2 + WaterCover_noTreeCanopy_frac * WaterLE_W_p_m2;

	//NR_total_W_p_m2 (W/m2) is total net radiation (W/m^2), sum of fractional components from each cover type net radiation
	NR_total_W_p_m2 = (ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) * ImpNR_W_p_m2 + TreeCover_frac * TreeNR_W_p_m2 + ShortVegCover_noTreeCanopy_frac * SVegNR_W_p_m2 + SoilCover_noTreeCanopy_frac * SoilNR_W_p_m2 + WaterCover_noTreeCanopy_frac * WaterNR_W_p_m2;
	//DeltaQ_W_p_m2 (W/m2) is total ground heat flux (W/m^2), sum of fractional components from each cover type ground heat flux
	DeltaQ_W_p_m2 = (ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) * ImpDeltaQ_W_p_m2 + TreeCover_frac * TreeDeltaQ_W_p_m2 + ShortVegCover_noTreeCanopy_frac * SVegDeltaQ_W_p_m2 + SoilCover_noTreeCanopy_frac * SoilDeltaQ_W_p_m2 + WaterCover_noTreeCanopy_frac * WaterDeltaQ_W_p_m2;
	//AH_total_W_p_m2 (W/m2) is total anthropogenic radiation (W/m^2), sum of fractional components from each cover type anthropogenic radiation
	AH_total_W_p_m2 = (ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) * Imp_AH_W_p_m2 + TreeCover_frac * Tree_AH_W_p_m2 + ShortVegCover_noTreeCanopy_frac * SVeg_AH_W_p_m2 + SoilCover_noTreeCanopy_frac * Soil_AH_W_p_m2 + WaterCover_noTreeCanopy_frac * Water_AH_W_p_m2;

	//Tair_mesoScale_K (K) is based on rearranged form of Eq 1 from Yang et al. (2013), where Tb = Ta - (H*ra)/(rho*Cp), ...
	//Note: ... Tb = Tair_mesoScale_K, Ta = Tair_localCell_K, ra = Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m, ...
	//Note: ... H = H_total_W_p_m2 (W/m2), rho = Density_Air_kg_p_m3, Cp = HeatCapacity_Air_J_p_kg_p_K  
	//Note: Unit balance right hand side = (W/m2) * (s/m) / [(kg/m3) * (J/kg/K)] = (J/s/m2) * (s/m) / (J/m3/K) = (J/m3) / (J/m3/K) = K
	Tair_mesoScale_K = Tair_localCell_K - (H_total_W_p_m2 * resistanceVar->Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m) /	(Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K);
	//AbsHumidity_mesoScale_kg_p_m3 (kg/m^3) is based on rearranged form of Eq 2 from Yang et al. (2013), where AHb = AHa - (LE*ra)/Lambda, ...
	//Note: ... AHb = AbsHumidity_mesoScale_kg_p_m3, AHa = AbsHumidityAct_localCell_kg_p_m3, LE = LE_total_W_p_m2, ...
	//Note: ... Lambda = LatentHeatVaporization_Water_J_p_kg, ra = Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m
	//Note: Unit balance right hand side = (W/m2) * (s/m) / (J/kg) = (J/s/m2) * (s/m) / (J/kg) = (J/m3) / (J/kg) = kg/m3
	AbsHumidity_mesoScale_kg_p_m3 = AbsHumidityAct_localCell_kg_p_m3 - (LE_total_W_p_m2 * resistanceVar->Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m) / LatentHeatVaporization_Water_J_p_kg;

	//Note: All Energy Flux Values of H and LE are adjusted in RescaleVariables_CoolAir function
}

//Tair_AbsHumidity_LayerBalance_NumericalMethod function calculates local grid canopy air temperature and humidity using numerical method and calls to Tair_AbsHumidity_LayerBalance function
//Note: Based on Levenberg–Marquardt algorithm (LMA or LM) minimizes error in least squares curve fitting, which mixes Gauss–Newton algorithm and the method of gradient descent
//Note: Called from SimulationCoordinator::RunTemperatureSpatialModel function for non-reference station grids
//Note: LMA for loop is set to default value of Iteration_Maximum, typically set to 40, but will break from for loop to save computational time if criteria are satisified
void HeatFluxCal::Tair_AbsHumidity_LayerBalance_NumericalMethod(Inputs* input, DataFolder* folder, DataFolder* reffolder, WeatherPreprocessor* Weatherpre,
	int MapPixel_ID, int timeStep, int Iteration_Maximum) {
	//Tb_obs (K) and eb_obs (kg/m3) are mesoscale air temperature and absolute humidity from reffolder at start of time step
	double Tb_obs, eb_obs;
	//Ta_est (K) and Td_est (K) are initial estimates of local air and dew point temperatures, initially set to ref station
	double Ta_est, Td_est;
	//Tair_mesoScale_weighted_K will contain a weighted value from multiple stations 
	double Tair_mesoScale_weighted_K = 0;
	//AbsHumidity_mesoScale_weighted_kg_p_m3 will contain a weighted value from multiple stations 
	double AbsHumidity_mesoScale_weighted_kg_p_m3 = 0;
	//Tair_weighted_K will contain a weighted value from multiple stations 
	double Tair_weighted_K = 0;
	//Tdew_weighted_K will contain a weighted value from multiple stations 
	double Tdew_weighted_K = 0;
	//keyname_Tair_F and keyname_Tdew_F initialized
	string keyname_Tair_F, keyname_Tdew_F;

	//If Flag_MultipleStation equals 1 then create Weatherpre-> weighted averages for mesoscale and canopy layer temperatures and humidity
	//Note: WeatherPreprocessor was used to lapse rate adjust the following variables in this contion so they work from the same relative elevation: ...
	//Note: ... Tair_mesoScale_weighted_K (K), AbsHumidity_mesoScale_weighted_kg_p_m3 (kg/m3), Tair_weighted_K (K) and Tdew_weighted_K (K)
	if (input->SimulationStringParams["Flag_MultipleStation"] == "1") {
		//Terms are defined by weather station weighted averages at folder
		//Tb_obs (K) is the weighted mesoscale air temperature,Tair_mesoScale_weighted_K (K)
		Tb_obs = Weatherpre->Tair_mesoScale_weighted_K;
		//eb_obs (kg/m3) is the weighted mesoscale air absolute humidity, AbsHumidity_mesoScale_weighted_kg_p_m3 (kg/m3)
		eb_obs = Weatherpre->AbsHumidity_mesoScale_weighted_kg_p_m3;
		//Ta_est (K) is the weighted canopy air temperature, Tair_weighted_K (K)
		Ta_est = Weatherpre->Tair_weighted_K;
		//Td_est (K) is weighted canopy dew point temperature, Tdew_weighted_K (K)
		Td_est = Weatherpre->Tdew_weighted_K;
	}
	//Else If Flag_MultipleStation not equal to 1 then create reffolder-> weighted averages for mesoscale and canopy layer temperatures and humidity
	else {
		//Terms are defined by weather station values at reffolder
		//Tb_obs (K) is the calculated mesoscale air temperature, from CollectVariables_CoolAir function
		Tb_obs = reffolder->VarDict["Tair_mesoScale_K"];
		//eb_obs (kg/m3) is the calculated mesoscale air absolute humidity, from CollectVariables_CoolAir function
		eb_obs = reffolder->VarDict["AbsHumidity_mesoScale_kg_p_m3"];
		//Ta_est (K) is the initial value of the estimated air temperature of a folder
		Ta_est = reffolder->VarDict["Tair_K"];
		//Td_est (K) is the initial value of the estimated dew point temperature of a folder
		Td_est = reffolder->VarDict["Tdew_K"];
	}

	//alamda is the lambda term in LM algorithm
	double alamda = 0.1;
	//w1 is the weight for eb air absolute humidity
	double w1 = 10000;
	//W is the weighting matrix
	double W[2][2] = { 0 };
	double J[2][2] = { 0 };
	double H[2][2] = { 0 };
	double H_lm[2][2] = { 0 };

	//Epsilon_ErrorThreshold is initialized to zero
	double Epsilon_ErrorThreshold = 0.0;
	double EstimateError_mesoScale_Tair_K = 0.0;
	double EstimateError_mesoScale_AbsHumidity_kg_p_m3 = 0.0;

	//Weighting matrix is assigned values of 1, 0, 0, and w
	W[0][0] = 1;
	W[0][1] = 0;
	W[1][0] = 0;
	W[1][1] = w1;

	int updateJ = 1;
	//dTa is incremental change in air temperature
	double dTa = 0.01;
	//dTd is incremental change in dew point temperature
	double dTd = 0.01;
	//Iteration_Counter initialized to zero
	int Iteration_Counter = 0;
	//Stability_Counter initialized to zero
	int Stability_Counter = 0;

	//cte 202410 Refactor
	double e_lm_first, d_lm1_first, d_lm2_first, e_lm_prior, d_lm1_prior, d_lm2_prior, e_lm_delta, d_lm1_delta, d_lm2_delta;
	double d_lm1, d_lm2, e_lm, Tb_est_lm, eb_est_lm;


	//For Loop through Iteration_Maximum, which is HydroPlusConfig.xml parameter IterationCount
	//Note: Break from for loop is in place below if stability and temperature closure criteria are satisified
	for (Iteration_Counter; Iteration_Counter < Iteration_Maximum; Iteration_Counter++) {
		//If updateJ flag equals 1 then enter calculations, considered LMA conditional statement
		//Note: Make 3 calls to Tair_AbsHumidity_LayerBalance function with different sets of Tair and Tdew 
		if (updateJ == 1) {

			//Tair_localCell_K (K) redefined by Ta_est (K), air temperature estimated at start of LM algorithm
			//Note: For Flag_MultipleStation = 1, this is not a redefinition
			Tair_localCell_K = Ta_est;
			//Tdew_localCell_K (K) redefined by Td_est (K), dew point temperature estimated at start of LM algorithm
			//Note: For Flag_MultipleStation = 1, this is not a redefinition
			Tdew_localCell_K = Td_est;

			//Tair_AbsHumidity_LayerBalance function computes Tair_mesoScale_K (K) & AbsHumidity_mesoScale_kg_p_m3 (kg/m3) 
			//Note: The Tair_AbsHumidity_LayerBalance_NumericalMethod function calls this Tair_AbsHumidity_LayerBalance function ...
			//Note: ... until there is closure on the error term or the interation maximum is exceeded
			Tair_AbsHumidity_LayerBalance(input, folder, reffolder, timeStep);

			//Tb0 (K) is mesoScale air temperature estimate updated after each call to Tair_AbsHumidity_LayerBalance
			double Tb0 = Tair_mesoScale_K;
			//eb0 (kg/m3) is updated mesoScale absolute humidity estimate updated after each call to Tair_AbsHumidity_LayerBalance
			double eb0 = AbsHumidity_mesoScale_kg_p_m3;

			//Tair_localCell_K (K) redefined as sum of Ta_est + dTa
			Tair_localCell_K = Ta_est + dTa;

			//Tair_AbsHumidity_LayerBalance function computes Tair_mesoScale_K (K) & AbsHumidity_mesoScale_kg_p_m3 (kg/m3) 
			//Note: The Tair_AbsHumidity_LayerBalance_NumericalMethod function calls this Tair_AbsHumidity_LayerBalance function ...
			//Note: ... until there is closure on the error term or the interation maximum is exceeded
			Tair_AbsHumidity_LayerBalance(input, folder, reffolder, timeStep);

			//Tb1 (K) is mesoScale air temperature estimate updated after each call to Tair_AbsHumidity_LayerBalance
			double Tb1 = Tair_mesoScale_K;
			//eb1 (kg/m3) is updated mesoScale absolute humidity estimate updated after each call to Tair_AbsHumidity_LayerBalance
			double eb1 = AbsHumidity_mesoScale_kg_p_m3;

			//Tair_localCell_K (K) redefined as sum of Ta_est
			Tair_localCell_K = Ta_est;
			Tdew_localCell_K = Td_est + dTd;

			//Tair_AbsHumidity_LayerBalance function computes Tair_mesoScale_K (K) & AbsHumidity_mesoScale_kg_p_m3 (kg/m3) 
			//Note: The Tair_AbsHumidity_LayerBalance_NumericalMethod function calls this Tair_AbsHumidity_LayerBalance function ...
			//Note: ... until there is closure on the error term or the interation maximum is exceeded
			Tair_AbsHumidity_LayerBalance(input, folder, reffolder, timeStep);

			//Tb2 (K) is mesoScale air temperature estimate updated after each call to Tair_AbsHumidity_LayerBalance
			double Tb2 = Tair_mesoScale_K;
			//eb2 (kg/m3) is updated mesoScale absolute humidity estimate updated after each call to Tair_AbsHumidity_LayerBalance
			double eb2 = AbsHumidity_mesoScale_kg_p_m3;

			//Compute Jacobian matrix with three sets of mesoscale air temperature and absolute humidity actual values
			//J[0][0] is gradient of (Tb1 - Tb0) / dTa 
			J[0][0] = (Tb1 - Tb0) / dTa;
			//J[0][0] is gradient of (Tb2 - Tb0) / dTa 
			J[0][1] = (Tb2 - Tb0) / dTa;
			//J[0][0] is gradient of (eb1 - eb0) / dTd 
			J[1][0] = (eb1 - eb0) / dTd;
			//J[1][1] is gradient of (eb2 - eb0) / dTd 
			J[1][1] = (eb2 - eb0) / dTd;

			//EstimateError_mesoScale_Tair_K is computed as difference of mesoscale air temperatures Tb_obs - Tb0
			EstimateError_mesoScale_Tair_K = Tb_obs - Tb0;
			//EstimateError_mesoScale_AbsHumidity_kg_p_m3 is computed as difference of mesoscale absolute humidities (eb_obs - eb0) weighted by w1
			EstimateError_mesoScale_AbsHumidity_kg_p_m3 = (eb_obs - eb0) * w1;

			//Combine Jacobian matrices
			H[0][0] = J[0][0] * J[0][0] + J[1][0] * J[1][0] * w1;
			H[0][1] = J[0][0] * J[0][1] + J[1][0] * J[1][1] * w1;
			H[1][0] = J[0][1] * J[0][0] + J[1][1] * J[1][0] * w1;
			H[1][1] = J[0][1] * J[0][1] + J[1][1] * J[1][1] * w1;

			//If Iteration_Counter equals zero then compute initial Epsilon_ErrorThreshold 
			//Note: Epsilon_ErrorThreshold is re-computed below when e_lm < Epsilon_ErrorThreshold
			if (Iteration_Counter == 0) {
				//Epsilon_ErrorThreshold is sum of squares of EstimateError_mesoScale_Tair_K and EstimateError_mesoScale_AbsHumidity_kg_p_m3, ensuring it is positive
				Epsilon_ErrorThreshold = EstimateError_mesoScale_Tair_K * EstimateError_mesoScale_Tair_K +					EstimateError_mesoScale_AbsHumidity_kg_p_m3 * EstimateError_mesoScale_AbsHumidity_kg_p_m3;
			}
		}

		//H_lm[0][0] increased by alamda
		H_lm[0][0] = H[0][0] + alamda;
		H_lm[0][1] = H[0][1];
		H_lm[1][0] = H[1][0];
		//H_lm[1][1] increased by alamda
		H_lm[1][1] = H[1][1] + alamda;

		double bb = 1 / (H_lm[0][0] * H_lm[1][1] - H_lm[0][1] * H_lm[1][0]);
		//dp1 (K) is incremental update in air temperature based on LM algorithm 
		double dp1 = bb * (H_lm[1][1] * (J[0][0] * EstimateError_mesoScale_Tair_K + J[1][0] * EstimateError_mesoScale_AbsHumidity_kg_p_m3) -
			H_lm[0][1] * (J[0][1] * EstimateError_mesoScale_Tair_K + J[1][1] * EstimateError_mesoScale_AbsHumidity_kg_p_m3));
		//dp2 (K) is incremental update in dew point temperature based on LM algorithm 
		double dp2 = bb * (-H_lm[1][0] * (J[0][0] * EstimateError_mesoScale_Tair_K + J[1][0] * EstimateError_mesoScale_AbsHumidity_kg_p_m3) + H_lm[0][0] * (J[0][1] * EstimateError_mesoScale_Tair_K + J[1][1] * EstimateError_mesoScale_AbsHumidity_kg_p_m3));

		//Ta_lm (K) is updated estimate of air temperature based on LM algorithm, summing Ta_est (K) and dp1
		double Ta_lm = Ta_est + dp1;
		//Td_lm (K) is updated estimate of dew point temperature based on LM algorithm, summing Td_est (K) and dp2
		double Td_lm = Td_est + dp2;

		//Ta_est_Prior and Td_est_Prior archived for comparison
		double Ta_est_Prior = Ta_est;
		double Td_est_Prior = Td_est;

		//Tair_localCell_K (K) redefined by Ta_lm (K), air temperature estimated with LM algorithm
		Tair_localCell_K = Ta_lm;
		//Tdew_localCell_K (K) redefined by Ta_lm (K), dew point temperature estimated with LM algorithm
		Tdew_localCell_K = Td_lm;

		//Tair_AbsHumidity_LayerBalance function computes Tair_mesoScale_K (K) & AbsHumidity_mesoScale_kg_p_m3 (kg/m3) 
		//Note: The Tair_AbsHumidity_LayerBalance_NumericalMethod function calls this Tair_AbsHumidity_LayerBalance function ...
		//Note: ... until there is closure on the error term or the interation maximum is exceeded
		Tair_AbsHumidity_LayerBalance(input, folder, reffolder, timeStep);

		//Tb_est_lm (K) defined as Tair_mesoScale_K (K)
		Tb_est_lm = Tair_mesoScale_K;
		//eb_est_lm (K) defined as AbsHumidity_mesoScale_kg_p_m3 (K)
		eb_est_lm = AbsHumidity_mesoScale_kg_p_m3;

		//d_lm1 (K) is estimation error for mesoscale layer Tb_obs based on LM algorithm
		d_lm1 = Tb_obs - Tb_est_lm;
		//d_lm2 (K) is estimation error for mesoscale layer eb_obs based on LM algorithm
		d_lm2 = (eb_obs - eb_est_lm) * w1;
		//e_lm is total error term used below in LM algorithm
		e_lm = d_lm1 * d_lm1 + d_lm2 * d_lm2;

		//If e_lm less than Epsilon_ErrorThreshold then decrease alamda and prepare for entry into LMA if conditional above
		//Note: Conditional to find the local minimum by decreasing alamda
		if (e_lm < Epsilon_ErrorThreshold) {
			//alamda decreased by factor of 10
			alamda = alamda / 10;
			//Ta_est (K) redefined to Ta_lm (K)
			Ta_est = Ta_lm;
			//Td_est (K) redefined to Td_lm (K)
			Td_est = Td_lm;
			//Epsilon_ErrorThreshold redefined to e_lm
			Epsilon_ErrorThreshold = e_lm;
			//updateJ set to 1
			updateJ = 1;
			//Stability_Counter reset to 0 when algorithm re-enters updateJ = 1 condition
			Stability_Counter = 0;
		}
		//cte 202410 Refactor
		//Else if (EstimateError_mesoScale_Tair_K > (Temperature_ErrorThreshold_K * 10)) enter to force Ta_est to satisfy Tb_obs
		//Note: LM numerical method calls Tair_AbsHumidity_LayerBalance and can find local minima yet have Tair_mesoScale_K <> Tb_obs
		//Note: To ensure Tair_AbsHumidity_LayerBalance_NumericalMethod maintains Tb_obs for all pixels this Else If was created
		//Note: This was needed in Naples, Italy simulations for 2017071510 in quad 02 with 140 rows and columns and 30 m resolution ...
		//Note: ... for pixels with NLCD Class 71 and various levels of impervious near the hippodrome, along the track, ...
		//Note: ... MapPixel_ID == int(116 * 140 + 94) || MapPixel_ID == int(117 * 140 + 94)
		else if (EstimateError_mesoScale_Tair_K > (Temperature_ErrorThreshold_K * 10) && Stability_Counter > 1 && flag_TE_Debug == 1) {
			//Ta_est (K) is based on rearranged form of Eq 1 from Yang et al. (2013), where Ta = Ta + (H*ra)/(rho*Cp), ...
			//Note: ... Tb = Tair_mesoScale_K or Tb_obs, Ta = Tair_localCell_K or Ta_est, ra = Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m, ...
			//Note: ... H = H_total_W_p_m2 (W/m2), rho = Density_Air_kg_p_m3, Cp = HeatCapacity_Air_J_p_kg_p_K  
			//Note: Unit balance right hand side = (W/m2) * (s/m) / [(kg/m3) * (J/kg/K)] = (J/s/m2) * (s/m) / (J/m3/K) = (J/m3) / (J/m3/K) = K
			Ta_est = Tb_obs + (H_total_W_p_m2 * resistanceVar->Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m) / (Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K);
			//Td_est (K) redefined to Td_lm (K)
			Td_est = Td_lm;
			//updateJ set to 1
			updateJ = 1;
			//Stability_Counter reset to 0 when algorithm re-enters updateJ = 1 condition
			Stability_Counter = 0;
			//cte 202410 Refactor
			counter_Tair_meso_update = counter_Tair_meso_update + 1;
		}
		//Else If e_lm greater than or equals Epsilon_ErrorThreshold then increase alamda and prepare for no entry into LMA if conditional above
		//Note: Conditional to find the local minimum by increasing alamda
		else {
			//alamda increased by factor of 10
			alamda = alamda * 10;
			//updateJ set to 0
			updateJ = 0;
			//Stability_Counter increased by 1 when updateJ = 0, but Stability_Counter resets to 0 if LMA re-enters update = 1
			Stability_Counter = Stability_Counter + 1;
		}

		//ErrorEstimate_canopyLayer_Tair_K (K) computes the absolute difference between the prior and current estimate of canopy layer local air temperature
		double ErrorEstimate_canopyLayer_Tair_K = abs(Ta_est_Prior - Ta_lm);
		//ErrorEstimate_canopyLayer_Tdew_K (K) computes the absolute difference between the prior and current estimate of canopy layer local dew point temperature
		double ErrorEstimate_canopyLayer_Tdew_K = abs(Td_est_Prior - Td_lm);
		//If Stability_Counter > 2, and ErrorEstimate_canopyLayer_Tair_K and ErrorEstimate_canopyLayer_Tdew_K estimates are less than Temperature_ErrorThreshold_K
		//Note: Criteria 1 Stability_Counter > 2 is used due to the LM algorithm cycling between updateJ = 1 and 0 to avoid local minima in the least squares fit
		//Note: Criteria 2 ErrorEstimate_canopyLayer_Tair_K < Temperature_ErrorThreshold_K ensures air temperatures are within 0.001 K, and share the same tenth of a degree
		//Note: Criteria 3 ErrorEstimate_canopyLayer_Tdew_K < Temperature_ErrorThreshold_K ensures dew point temperatures are within 0.001 K, and share the same tenth of a degree
		//Note: Consider Refactor to allow HydroPlusConfig.xml to set Temperature_ErrorThreshold_K value
		if (Stability_Counter > 2 && ErrorEstimate_canopyLayer_Tair_K < Temperature_ErrorThreshold_K && ErrorEstimate_canopyLayer_Tdew_K < Temperature_ErrorThreshold_K) {
			//break function leaves for loop
			break;
		}
	}
	//cte 202410 Refactor
	if (flag_TE_Debug == 1) {
		if ((timeStep + 1) == input->SimulationTimePeriod_timeSteps) {
			cout << "counter_Tair_meso_update = " << counter_Tair_meso_update << endl;
		}
	}
}

//AdiabaticLapseRates function will adjust air and dew point temperatures based elevation, using adiabatic lapse rate 
//Note: Even if Flag_MultipleStation=1 and WeatherPreprocessor lapse rate adjusted Tair_weighted_K and Tair_mesoScale_K, this adjustment is needed 
//Note: Explicit testing shows HeatFluxCal::AdiabaticLapseRates is required when flag_MultipleStation=1 to lapse rate adjust Tair_K and Tdew_K.
void HeatFluxCal::AdiabaticLapseRates(Inputs* input, DataFolder* folder, DataFolder* reffolder, int timeStep, int MapPixel_ID, WeatherPreprocessor* Weatherpre)
{
	//Rationale for use of adiabatic lapse rate adjustments to air temperature:
	//Note: Function calculates the effect of elevation difference with the reference station on local cell air temperature above ground
	//Note: Function modifies Stull (2000) theory of cooling by dry adiabatic lapse rate (ALR) with environmental lapse rate (ELR) of ~5.5 C/km, ...
	//Note: Assumes climbing 1 km up mountain air on mountain cools at ELR, while air lifting 1 km above ground cools at ALR.
	//Note: Stull (2000) gives dry adiabatic lapse rate Gamma_dry_C_p_km = 9.8 C/km; dew point lapse rate Gamma_dew_C_p_km = 1.8 C/km derived Eq 5.8
	//Note: Elevation_lcl_km = 1/(9.8 - 1.8) * (Tair_K - Tdew_K), Elevation_lcl_km = lifting condensation level based on Eq 5.8 Stull (2000)
	//Note: Elevation_lcl_km = 1/(5.5 - 1.8) * (Tair_K - Tdew_K), where Gamma_EnvironmentalLapseRate_C_p_km = 5.5 C/km, based on modification
	//Note: Elevation_delta_km = (Elevation_pixel - Elevation_referenceStation) and sets Tair_K = Tdew_K at Elevation_lcl_km
	//Note: If Elevation_delta_km <= Elevation_lcl_km Then Tair_update = Tair_K - Gamma_dry_C_p_km * Elevation_delta_km, based on Stull (2000)
	//Note: Else Tair_update = Tair_K - (Gamma_dry_C_p_km * Elevation_lcl_km) - [Gamma_dew_C_p_km * (Elevation_delta_km - Elevation_lcl_km)]; Stull (2000)
	//Note: If Elevation_delta_km <= Elevation_lcl_km Then Tair_update = Tair_K - Gamma_EnvironmentalLapseRate_C_p_km * Elevation_delta_km
	//Note: Else Tair_update = Tair_K - (Gamma_EnvironmentalLapseRate_C_p_km * Elevation_lcl_km) - [Gamma_dew_C_p_km * (Elevation_delta_km - Elevation_lcl_km)] based modification
	//Note: Tdew_update = Tdew_K - Gamma_dew_C_p_km * Elevation_delta_km based on Stull (2000) and modification
	//Note: For differencing temperatures, Kelvin can be used in place of Celsius, as they are linearly related
	//References:
	//Stull, R. (2000). Meteorology for Scientists and Engineers, 2nd Edition. Brooks Cole. ISBN 0-534-37214-7

	//Note: Algorithm validated in Colorado Rocky Mountains with Flag_MultipleStation=1 Flag_HottestDaySimulated=1 WeatherStationNum=2 for 2021
	//Note: Validation placed reference cell in map upper left corner, and test cells at weather stations (USAF WBAN): 725650-03017 and 720385-00419
	//Note: Station 720385-00419 (Mtn) DEM=3575.5 m, NLCD LC=52, TC=4%, IC=0%. Station 725650-03017 (Denver) DEM=1650 m, NLCD LC=24, TC=0%, IC=56%.
	//Note: Tests used two versions of WeatherStationAttributeTable.csv input file, one with and one without Station 720385-00419.
	//Note: Without Station 720385-00419 in file, 2 nearest stations to the local cell overlapping station 720385-00419 were 724640-93058 and 725640-24018
	//Note: With Station 720385-00419 in file, 2 nearest stations to the local cell overlapping station 720385-00419 were 720385-00419 and 725640-24018 
	//Note: Results found estimated Tair approximated observed Tair at Station 720385-00419 for runs using both versions of WeatherStationAttributeTable.csv
	//Note: Results at 3 pm for local cell at 720385-00419 Tair_modeled_w_station = 289.9K, Tair_modeled_wo_station = 290.1K, and Tair_observed = 290.4K
	//Note: Avoid using adiabatic lapse rate dry in place of environmental lapse rate, as it results in Tair_modeled_wo_station = 276.7K, much too cold. 

	//Elevation_Station_weighted_m (m) initialized to 0
	double Elevation_Station_weighted_m = 0;
	//If Flag_MultipleStation is true then read in Weatherpre-> reference station meteorological variables for flux calculations
	//Note: Even if Flag_MultipleStation=1 and WeatherPreprocessor lapse rate adjusted Tair_weighted_K, this adjustment is needed 
	if (input->SimulationStringParams["Flag_MultipleStation"] == "1") {
		//Note: WeightedInputMap[MapPixel_ID]["Elevation_WeatherStations_weighted_m"] is computed for each map pixel, only at timeStep = 0
		Elevation_Station_weighted_m = Weatherpre->WeightedInputMap[MapPixel_ID]["Elevation_WeatherStations_weighted_m"][0];
		//Elevation_delta_km (km) is height of pixel above station, equals DEM(MapPixel_ID) - Elevation_Station_weighted_m), converted from m to km
		Elevation_delta_km = (input->DEM[MapPixel_ID] - Elevation_Station_weighted_m) * Ratio_km_to_m;
	}
	//Else If Flag_MultipleStation is false then read in in input-> reference station meteorological variables for flux calculations
	else {
		//Elevation_delta_km (km) is pixel height above station, equals DEM(MapPixel_ID) - DEM(input->MapPixel_ReferenceStation_ID), convert from m to km
		Elevation_delta_km = (input->DEM[MapPixel_ID] - input->DEM[input->MapPixel_ReferenceStation_ID]) * Ratio_km_to_m;
	}

	//Elevation_lcl_km (km) equals 1 / (Gamma_EnvironmentalLapseRate_C_p_km - Gamma_dew_C_p_km) * (Tair_localCell_K - Tdew_localCell_K)
	//Note: Elevation_lcl_km (km) is lifting condensation level, modified from from Eq 5.8 Stull (2000), using the environmental lapse rate
	Elevation_lcl_km = 1 / (Gamma_EnvironmentalLapseRate_C_p_km - Gamma_dew_C_p_km) * (Tair_localCell_K - Tdew_localCell_K);

	//If Elevation_delta_km is below Elevation_lcl_km, then the lifting condensation level was not reached and air remains unsaturated
	if (Elevation_delta_km <= Elevation_lcl_km) {
		//Tair_weighted_K (K) equals Tair_weighted_K - Gamma_EnvironmentalLapseRate_C_p_km * Elevation_delta_km
		//Note: Tair_localCell_K (K) modified from Eq 5.12 Stull (2000) as explained above to use the environmental lapse rate
		Tair_localCell_K = Tair_localCell_K - Gamma_EnvironmentalLapseRate_C_p_km * Elevation_delta_km;
	}
	//Else, Elevation_delta_km > Elevation_lcl_km, so 1st lift air to Elevation_lcl_km, then 2nd lift additional (Elevation_delta_km - Elevation_lcl_km)
	//Note: Tair_K cools at adiabatic lapse rate dry Gamma_dry_C_p_km until Elevation_lcl_km, then becomes saturated and cools at Gamma_dew_C_p_km
	else {
		//Tair_weighted_K (K) equals Tair_localCell_K - Gamma_EnvironmentalLapseRate_C_p_km * Elevation_lcl_km;
		//Note: Tair_weighted_K (K) is initially updated using environmental lapse rate until Elevation_lcl_km, from Eq 5.12 Stull (2000)
		//Note: Tair_localCell_K (K) modified from Eq 5.12 Stull (2000) as explained above to use the environmental lapse rate
		Tair_localCell_K = Tair_localCell_K - Gamma_EnvironmentalLapseRate_C_p_km * Elevation_lcl_km;

		//Tair_localCell_K (K) is subsequently udpated using adiabatic lapse rate for dew point air, modified Eq 5.13 Stull (2000)
		Tair_localCell_K = Tair_localCell_K - Gamma_dew_C_p_km * (Elevation_delta_km - Elevation_lcl_km);
	}
	//Tdew_localCell_K (K) is updated based on the adiabatic lapse rate for saturated dew point air, modified Eq 5.13 Stull (2000)
	Tdew_localCell_K = Tdew_localCell_K - Gamma_dew_C_p_km * Elevation_delta_km;
}

//RescaleVariables_CoolAir function will rescale latent and sensible energy fluxes, compute corresponding mesoScale values for Tair and AbsoluteHumidity
void HeatFluxCal::RescaleVariables_CoolAir(Inputs* input, DataFolder* folder, DataFolder* reffolder, int timeStep)
{
	//If Tair_localCell_K became less than Tdew_localCell_K, set it to Tdew_localCell_K
	if (Tair_localCell_K < Tdew_localCell_K) { Tair_localCell_K = Tdew_localCell_K; }

	//Theory: Rescale latent energy (LE) and sensible heat (H) flux after iteratively computed in HeatFluxCal::Tair_AbsHumidity_LayerBalance
	//Note: Rescaling is not ideal; it recognizes accurate temperature prediction with unrealistic energy exchange. Alternatives are possible.
	//Note: Alternative 1, compute LE and H with larger aerodynamic resistances for canopy and mesoScale, and cooler mesoScale air temperature
	//Note: Alternative 2, allow heat domes with negative daytime H, negative aerodynamic resistance with H yet positive with LE in convective cells
	//Note: Eddy covariance LE and H data from Capodimonte Park, Naples, Italy 2017-2021 used to rescale values from Tair_AbsHumidity_LayerBalance
	//Note: Capodimonte eddy covariance data from Drs. Carlo Calfapietra (carlo.calfapietra@cnr.it) and Terenzio Zenone (terenzio.zenone@isafom.cnr.it)
	//Note: Faulty approach 1: Tried recomputing LE using Penman Monteith evaporation functions, with WeatherPrep type resistances, then ...
	//Note: ... deriving H from energy balance, H = NR - DeltaQ - AH - LE. Obtained reasonable H and LE values but Tair_AbsHumidity_LayerBalance then ...
	//Note: ... generated faulty air temperature values with too high temperatures above NLCD Class 11 and 40s, effectively destroying model fitness.
	//Note: Faulty approach 2: Tried correcting high temperatures above NLCD Class 11 and 40s with algorithm to mix fraction of Tdew and Tair, which ...
	//Note: ... generated spatial patterns of temperature but was an overly parameterized approach. Hence, simple rescaling of H and LE preferred.
	//Note: Faulty approach 3: Tried using larger aerodynamic resistances for canopy and mesoScale as well as negative values, which ...
	//Note: ... generated some promising results with preserving water and forest air temperatures, but losing urban. May need to adjust by cover type.
	//Note: Regarding fit of temperature for NLCD Class 11, Buoy data for Washington, DC  August 28, 2018 provides air temperature above water.
	//Note: Buoy Station WASD2 8594900, Coordinates: 38.873 N 77.021 W; Air temp height: 2.6 m above site elevation.
	//Note: Woolway et. al. (2018) provide Bowen Ratio data for lakes that supports the rescaling approach for computing the LE_fraction

	//Theory from KIT: 
	//Note: Rescale Tair_mesoScale_K (K) flux and Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m after computed in Tair_AbsHumidity_LayerBalance
	//Note: Algorithm allows H_total_W_p_m2 across domain to have positive or negative values, adjusting Tair_mesoScale_K to keep r_aero > 0
	//Note: Tair_mesoScale_K can vary spatially across domain due to heterogeneity within boundary layer, likely during sunrise and sunset transitions
	//Note: Algorithm keeps Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m < 1000 by adjusting Tair_mesoScale_K (K) to allow local heterogeneity
	//Note: If pixel_ref H < 0 then stable atmosphere and set target Tair_mesoScale_K > Tair_localCell_K based on boundary layer thickness and lapse rate
	//Note: If pixel_ref H < 0 & pixel_local H > 0, then allow for local instability with instance of Tair_mesoScale_K < Tair_localCell_K
	//Note: Tair_mesoScale_final_K and AbsHumidity_mesoScale_final_kg_p_m3 represent rescaled values to report with outputs
	//Note: Tair_mesoScale_K and AbsHumidity_mesoScale_kg_p_m3 represent unscaled values needed by HeatFluxCal::Tair_AbsHumidity_LayerBalance_NumericalMethod
	//Note: Algorithm inspired by Dr. Christopher Holst of Kalsruhe Institute of Technology (KIT) Alpine campus in GaPa, where he develops PALM-4U model
	//Note: Dr. Holst and post-doc ChangXing Lan (UW PhD) provided insights May-June 2023 at KIT that helped parameterize this energy balance model
	//Note: Consider refactor to control timing of boundary layer based on diurnal function, such as solar position or hour, with lag as needed
	//Note: Consider refactor to control thickness of boundary layer based on stability, such as USEPA 2000

	//References:
	//Woolway, R. I., ... & Jones, I. D. (2018). Geographic and temporal variations in turbulent heat loss from lakes: A global analysis across 45 lakes. Limnology and Oceanography, 63(6), 2436-2449. doi:https://doi.org/10.1002/lno.10950

	//Routine for daytime adjustments
	//If (ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) > Constant_1E_negative4 cover threshold AND NR_total_W_p_m2 > 0 then rescale H and LE
	if ((ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) > Constant_1E_negative4 && NR_total_W_p_m2 > 0 && ImpH_W_p_m2 < 0) {
		//H_rescaled_Wpm2 (W/m2) is 1st estimate of rescaled sensible heat flux, using abs function to change from negative to positive
		double H_rescaled_Wpm2 = abs(ImpH_W_p_m2);
		//LE_rescaled_Wpm2 (W/m2) is 1st estimate of rescaled latent energy flux, based on H_rescaled_Wpm2 being scaled by abs function 2 fold, from - to 0 to +
		//Note: If H_rescaled_Wpm2 = abs(H_initial), then LE_rescaled_Wpm2 = LE_initial + 2 * H_rescaled_Wpm2, and ... 
		//Note: ... X = LE_initial - H_initial, then X = LE_rescaled_Wpm2 - H_rescaled_Wpm2
		double LE_rescaled_Wpm2 = ImpLE_W_p_m2 + 2.0 * H_rescaled_Wpm2;
		//LE_frac (fraction) is fraction of latent energy flux in total rescaled flux, = LE_rescaled_Wpm2 / (LE_rescaled_Wpm2 + H_rescaled_Wpm2);
		double LE_frac = LE_rescaled_Wpm2 / (LE_rescaled_Wpm2 + H_rescaled_Wpm2);
		//H_frac (fraction) is defined as 1 minus LE_frac, where LE_frac + H_frac = unity in a Bowen Ratio
		double H_frac = 1.0 - LE_frac;
		//NR_available_W_p_m2 (W/m2) is total radiation available for LE and H flux, defined as NR_W_p_m2 + AH_W_p_m2 - DeltaQ_W_p_m2
		double NR_available_W_p_m2 = ImpNR_W_p_m2 + Imp_AH_W_p_m2 - ImpDeltaQ_W_p_m2;
		//ImpLE_W_p_m2 (W/m2) is final rescaled latent energy flux estimate, as product of NR_available_W_p_m2 and LE_frac
		ImpLE_W_p_m2 = NR_available_W_p_m2 * LE_frac;
		//ImpH_W_p_m2 (W/m2) is final rescaled sensible heat flux estimate, as product of NR_available_W_p_m2 and H_frac
		ImpH_W_p_m2 = NR_available_W_p_m2 * H_frac;
	}
	//If TreeCover_frac > Constant_1E_negative4 cover threshold AND NR_total_W_p_m2 > 0 then rescale H and LE
	if (TreeCover_frac > Constant_1E_negative4 && NR_total_W_p_m2 > 0 && TreeH_W_p_m2 < 0) {
		//H_rescaled_Wpm2 (W/m2) is 1st estimate of rescaled sensible heat flux, using abs function to change from negative to positive
		double H_rescaled_Wpm2 = abs(TreeH_W_p_m2);
		//LE_rescaled_Wpm2 (W/m2) is 1st estimate of rescaled latent energy flux, based on H_rescaled_Wpm2 being scaled by abs function 2 fold, from - to 0 to +
		//Note: If H_rescaled_Wpm2 = abs(H_initial), then LE_rescaled_Wpm2 = LE_initial + 2 * H_rescaled_Wpm2, and ... 
		//Note: ... X = LE_initial - H_initial, then X = LE_rescaled_Wpm2 - H_rescaled_Wpm2
		double LE_rescaled_Wpm2 = TreeLE_W_p_m2 + 2.0 * H_rescaled_Wpm2;
		//LE_frac (fraction) is fraction of latent energy flux in total rescaled flux, = LE_rescaled_Wpm2 / (LE_rescaled_Wpm2 + H_rescaled_Wpm2);
		double LE_frac = LE_rescaled_Wpm2 / (LE_rescaled_Wpm2 + H_rescaled_Wpm2);
		//H_frac (fraction) is defined as 1 minus LE_frac, where LE_frac + H_frac = unity in a Bowen Ratio
		double H_frac = 1.0 - LE_frac;
		//NR_available_W_p_m2 (W/m2) is total radiation available for LE and H flux, defined as NR_W_p_m2 + AH_W_p_m2 - DeltaQ_W_p_m2
		double NR_available_W_p_m2 = TreeNR_W_p_m2 + Tree_AH_W_p_m2 - TreeDeltaQ_W_p_m2;
		//TreeLE_W_p_m2 (W/m2) is final rescaled latent energy flux estimate, as product of NR_available_W_p_m2 and LE_frac
		TreeLE_W_p_m2 = NR_available_W_p_m2 * LE_frac;
		//TreeH_W_p_m2 (W/m2) is final rescaled sensible heat flux estimate, as product of NR_available_W_p_m2 and H_frac
		TreeH_W_p_m2 = NR_available_W_p_m2 * H_frac;
		//LET_to_LE_ratio is ratio defined by quotient of TreeLET_W_p_m2 to (TreeLET_W_p_m2 + TreeLEE_W_p_m2), where denominator = TreeLE_W_p_m2 
		double LET_to_LE_ratio = TreeLET_W_p_m2 / (TreeLET_W_p_m2 + TreeLEE_W_p_m2);
		//TreeLET_W_p_m2 is computed as product of LET_to_LE_ratio and TreeLE_W_p_m2
		TreeLET_W_p_m2 = LET_to_LE_ratio * TreeLE_W_p_m2;
		//TreeLEE_W_p_m2 is computed as product of (1.0 - LET_to_LE_ratio) and TreeLE_W_p_m2
		TreeLEE_W_p_m2 = (1.0 - LET_to_LE_ratio) * TreeLE_W_p_m2;
	}
	//If ShortVegCover_noTreeCanopy_frac > Constant_1E_negative4 cover threshold AND NR_total_W_p_m2 > 0 then rescale H and LE
	if (ShortVegCover_noTreeCanopy_frac > Constant_1E_negative4 && NR_total_W_p_m2 > 0 && SVegH_W_p_m2 < 0) {
		//H_rescaled_Wpm2 (W/m2) is 1st estimate of rescaled sensible heat flux, using abs function to change from negative to positive
		double H_rescaled_Wpm2 = abs(SVegH_W_p_m2);
		//LE_rescaled_Wpm2 (W/m2) is 1st estimate of rescaled latent energy flux, based on H_rescaled_Wpm2 being scaled by abs function 2 fold, from - to 0 to +
		//Note: If H_rescaled_Wpm2 = abs(H_initial), then LE_rescaled_Wpm2 = LE_initial + 2 * H_rescaled_Wpm2, and ... 
		//Note: ... X = LE_initial - H_initial, then X = LE_rescaled_Wpm2 - H_rescaled_Wpm2
		double LE_rescaled_Wpm2 = SVegLE_W_p_m2 + 2.0 * H_rescaled_Wpm2;
		//LE_frac (fraction) is fraction of latent energy flux in total rescaled flux, = LE_rescaled_Wpm2 / (LE_rescaled_Wpm2 + H_rescaled_Wpm2);
		double LE_frac = LE_rescaled_Wpm2 / (LE_rescaled_Wpm2 + H_rescaled_Wpm2);
		//H_frac (fraction) is defined as 1 minus LE_frac, where LE_frac + H_frac = unity in a Bowen Ratio
		double H_frac = 1.0 - LE_frac;
		//NR_available_W_p_m2 (W/m2) is total radiation available for LE and H flux, defined as NR_W_p_m2 + AH_W_p_m2 - DeltaQ_W_p_m2
		double NR_available_W_p_m2 = SVegNR_W_p_m2 + SVeg_AH_W_p_m2 - SVegDeltaQ_W_p_m2;
		//SVegLE_W_p_m2 (W/m2) is final rescaled latent energy flux estimate, as product of NR_available_W_p_m2 and LE_frac
		SVegLE_W_p_m2 = NR_available_W_p_m2 * LE_frac;
		//SVegH_W_p_m2 (W/m2) is final rescaled sensible heat flux estimate, as product of NR_available_W_p_m2 and H_frac
		SVegH_W_p_m2 = NR_available_W_p_m2 * H_frac;
		//LET_to_LE_ratio is ratio defined by quotient of SVegLET_W_p_m2 to (SVegLET_W_p_m2 + SVegLEE_W_p_m2), where denominator = SVegLE_W_p_m2 
		double LET_to_LE_ratio = SVegLET_W_p_m2 / (SVegLET_W_p_m2 + SVegLEE_W_p_m2);
		//SVegLET_W_p_m2 is computed as product of LET_to_LE_ratio and SVegLE_W_p_m2
		SVegLET_W_p_m2 = LET_to_LE_ratio * SVegLE_W_p_m2;
		//SVegLEE_W_p_m2 is computed as product of (1.0 - LET_to_LE_ratio) and SVegLE_W_p_m2
		SVegLEE_W_p_m2 = (1.0 - LET_to_LE_ratio) * SVegLE_W_p_m2;
	}
	//If SoilCover_noTreeCanopy_frac > Constant_1E_negative4 cover threshold AND NR_total_W_p_m2 > 0 then rescale H and LE
	if (SoilCover_noTreeCanopy_frac > Constant_1E_negative4 && NR_total_W_p_m2 > 0 && SoilH_W_p_m2 < 0) {
		//H_rescaled_Wpm2 (W/m2) is 1st estimate of rescaled sensible heat flux, using abs function to change from negative to positive
		double H_rescaled_Wpm2 = abs(SoilH_W_p_m2);
		//LE_rescaled_Wpm2 (W/m2) is 1st estimate of rescaled latent energy flux, based on H_rescaled_Wpm2 being scaled by abs function 2 fold, from - to 0 to +
		//Note: If H_rescaled_Wpm2 = abs(H_initial), then LE_rescaled_Wpm2 = LE_initial + 2 * H_rescaled_Wpm2, and ... 
		//Note: ... X = LE_initial - H_initial, then X = LE_rescaled_Wpm2 - H_rescaled_Wpm2
		double LE_rescaled_Wpm2 = SoilLE_W_p_m2 + 2.0 * H_rescaled_Wpm2;
		//LE_frac (fraction) is fraction of latent energy flux in total rescaled flux, = LE_rescaled_Wpm2 / (LE_rescaled_Wpm2 + H_rescaled_Wpm2);
		double LE_frac = LE_rescaled_Wpm2 / (LE_rescaled_Wpm2 + H_rescaled_Wpm2);
		//H_frac (fraction) is defined as 1 minus LE_frac, where LE_frac + H_frac = unity in a Bowen Ratio
		double H_frac = 1.0 - LE_frac;
		//NR_available_W_p_m2 (W/m2) is total radiation available for LE and H flux, defined as NR_W_p_m2 + AH_W_p_m2 - DeltaQ_W_p_m2
		double NR_available_W_p_m2 = SoilNR_W_p_m2 + Soil_AH_W_p_m2 - SoilDeltaQ_W_p_m2;
		//SoilLE_W_p_m2 (W/m2) is final rescaled latent energy flux estimate, as product of NR_available_W_p_m2 and LE_frac
		SoilLE_W_p_m2 = NR_available_W_p_m2 * LE_frac;
		//SoilH_W_p_m2 (W/m2) is final rescaled sensible heat flux estimate, as product of NR_available_W_p_m2 and H_frac
		SoilH_W_p_m2 = NR_available_W_p_m2 * H_frac;
	}
	//If WaterCover_noTreeCanopy_frac > Constant_1E_negative4 cover threshold AND NR_total_W_p_m2 > 0 then rescale H and LE
	if (WaterCover_noTreeCanopy_frac > Constant_1E_negative4 && NR_total_W_p_m2 > 0 && WaterH_W_p_m2 < 0) {
		//H_rescaled_Wpm2 (W/m2) is 1st estimate of rescaled sensible heat flux, using abs function to change from negative to positive
		double H_rescaled_Wpm2 = abs(WaterH_W_p_m2);
		//LE_rescaled_Wpm2 (W/m2) is 1st estimate of rescaled latent energy flux, based on H_rescaled_Wpm2 being scaled by abs function 2 fold, from - to 0 to +
		//Note: If H_rescaled_Wpm2 = abs(H_initial), then LE_rescaled_Wpm2 = LE_initial + 2 * H_rescaled_Wpm2, and ... 
		//Note: ... X = LE_initial - H_initial, then X = LE_rescaled_Wpm2 - H_rescaled_Wpm2
		double LE_rescaled_Wpm2 = WaterLE_W_p_m2 + 2.0 * H_rescaled_Wpm2;
		//LE_frac (fraction) is fraction of latent energy flux in total rescaled flux, = LE_rescaled_Wpm2 / (LE_rescaled_Wpm2 + H_rescaled_Wpm2);
		double LE_frac = LE_rescaled_Wpm2 / (LE_rescaled_Wpm2 + H_rescaled_Wpm2);
		//H_frac (fraction) is defined as 1 minus LE_frac, where LE_frac + H_frac = unity in a Bowen Ratio
		double H_frac = 1.0 - LE_frac;
		//NR_available_W_p_m2 (W/m2) is total radiation available for LE and H flux, defined as NR_W_p_m2 + AH_W_p_m2 - DeltaQ_W_p_m2
		double NR_available_W_p_m2 = WaterNR_W_p_m2 + Water_AH_W_p_m2 - WaterDeltaQ_W_p_m2;
		//WaterLE_W_p_m2 (W/m2) is final rescaled latent energy flux estimate, as product of NR_available_W_p_m2 and LE_frac
		WaterLE_W_p_m2 = NR_available_W_p_m2 * LE_frac;
		//WaterH_W_p_m2 (W/m2) is final rescaled sensible heat flux estimate, as product of NR_available_W_p_m2 and H_frac
		WaterH_W_p_m2 = NR_available_W_p_m2 * H_frac;
	}

	//Routine for nighttime adjustments
	//If (ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) > Constant_1E_negative4 cover threshold AND NR_total_W_p_m2 <= 0 then rescale H and LE
	if ((ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) > Constant_1E_negative4&& NR_total_W_p_m2 <= 0) {
		//If ImpLE_W_p_m2 > 0 then anthropogenic heat goes to latent energy and sensible heat equals net radiation minus ground heat flux
		if (ImpLE_W_p_m2 > 0) {
			ImpLE_W_p_m2 = Imp_AH_W_p_m2;
			ImpH_W_p_m2 = ImpNR_W_p_m2 - ImpDeltaQ_W_p_m2;
		}
		//Else If ImpLE_W_p_m2 = 0 then latent energy is zero and sensible heat equals net radiation minus ground heat flux plus anthropogenic heat
		else {
			ImpH_W_p_m2 = ImpNR_W_p_m2 - ImpDeltaQ_W_p_m2 + Imp_AH_W_p_m2;
		}
	}
	//If TreeCover_frac > Constant_1E_negative4 cover threshold AND NR_total_W_p_m2 <= 0 then rescale H and LE
	if (TreeCover_frac > Constant_1E_negative4 && NR_total_W_p_m2 <= 0) {
		//If TreeLE_W_p_m2 > 0 then anthropogenic heat goes to latent energy and sensible heat equals net radiation minus ground heat flux
		if (TreeLE_W_p_m2 > 0) {
			TreeLE_W_p_m2 = Tree_AH_W_p_m2;
			TreeH_W_p_m2 = TreeNR_W_p_m2 - TreeDeltaQ_W_p_m2;
		}
		//Else If TreeLE_W_p_m2 = 0 then latent energy is zero and sensible heat equals net radiation minus ground heat flux plus anthropogenic heat
		else {
			TreeH_W_p_m2 = TreeNR_W_p_m2 - TreeDeltaQ_W_p_m2 + Tree_AH_W_p_m2;
		}
		//LET_to_LE_ratio defined as ratio of TreeLET_W_p_m2 to (TreeLET_W_p_m2 + TreeLEE_W_p_m2)
		double LET_to_LE_ratio = TreeLET_W_p_m2 / (TreeLET_W_p_m2 + TreeLEE_W_p_m2);
		//TreeLET_W_p_m2 (W/m2) defined as product of LET_to_LE_ratio and TreeLE_W_p_m2
		TreeLET_W_p_m2 = LET_to_LE_ratio * TreeLE_W_p_m2;
		//TreeLEE_W_p_m2 (W/m2) defined as product of (1 - LET_to_LE_ratio) and TreeLE_W_p_m2
		TreeLEE_W_p_m2 = (1.0 - LET_to_LE_ratio) * TreeLE_W_p_m2;
	}
	//If ShortVegCover_noTreeCanopy_frac > Constant_1E_negative4 cover threshold AND NR_total_W_p_m2 <= 0 then rescale H and LE
	if (ShortVegCover_noTreeCanopy_frac > Constant_1E_negative4 && NR_total_W_p_m2 <= 0) {
		//If SVegLE_W_p_m2 > 0 then anthropogenic heat goes to latent energy and sensible heat equals net radiation minus ground heat flux
		if (SVegLE_W_p_m2 > 0) {
			SVegLE_W_p_m2 = SVeg_AH_W_p_m2;
			SVegH_W_p_m2 = SVegNR_W_p_m2 - SVegDeltaQ_W_p_m2;
		}
		//Else If SVegLE_W_p_m2 = 0 then latent energy is zero and sensible heat equals net radiation minus ground heat flux plus anthropogenic heat
		else {
			SVegH_W_p_m2 = SVegNR_W_p_m2 - SVegDeltaQ_W_p_m2 + SVeg_AH_W_p_m2;
		}
		//LET_to_LE_ratio defined as ratio of SVegLET_W_p_m2 to (SVegLET_W_p_m2 + SVegLEE_W_p_m2)
		double LET_to_LE_ratio = SVegLET_W_p_m2 / (SVegLET_W_p_m2 + SVegLEE_W_p_m2);
		//SVegLET_W_p_m2 (W/m2) defined as product of LET_to_LE_ratio and SVegLE_W_p_m2
		SVegLET_W_p_m2 = LET_to_LE_ratio * SVegLE_W_p_m2;
		//SVegLEE_W_p_m2 (W/m2) defined as product of (1 - LET_to_LE_ratio) and SVegLE_W_p_m2
		SVegLEE_W_p_m2 = (1.0 - LET_to_LE_ratio) * SVegLE_W_p_m2;
	}
	//If SoilCover_noTreeCanopy_frac > Constant_1E_negative4 cover threshold AND NR_total_W_p_m2 <= 0 then rescale H and LE
	if (SoilCover_noTreeCanopy_frac > Constant_1E_negative4 && NR_total_W_p_m2 <= 0) {
		//If SoilLE_W_p_m2  > 0 then anthropogenic heat goes to latent energy and sensible heat equals net radiation minus ground heat flux
		if (SoilLE_W_p_m2 > 0) {
			SoilLE_W_p_m2 = Soil_AH_W_p_m2;
			SoilH_W_p_m2 = SoilNR_W_p_m2 - SoilDeltaQ_W_p_m2;
		}
		//Else If SoilLE_W_p_m2 = 0 then latent energy is zero and sensible heat equals net radiation minus ground heat flux plus anthropogenic heat
		else {
			SoilH_W_p_m2 = SoilNR_W_p_m2 - SoilDeltaQ_W_p_m2 + Soil_AH_W_p_m2;
		}
	}
	//If WaterCover_noTreeCanopy_frac > Constant_1E_negative4 cover threshold AND NR_total_W_p_m2 <= 0 then rescale H and LE
	if (WaterCover_noTreeCanopy_frac > Constant_1E_negative4 && NR_total_W_p_m2 <= 0) {
		//If WaterLE_W_p_m2 > 0 then anthropogenic heat goes to latent energy and sensible heat equals net radiation minus ground heat flux
		if (WaterLE_W_p_m2 > 0) {
			WaterLE_W_p_m2 = Water_AH_W_p_m2;
			WaterH_W_p_m2 = WaterNR_W_p_m2 - WaterDeltaQ_W_p_m2;
		}
		//Else If WaterLE_W_p_m2 = 0 then latent energy is zero and sensible heat equals net radiation minus ground heat flux plus anthropogenic heat
		else {
			WaterH_W_p_m2 = WaterNR_W_p_m2 - WaterDeltaQ_W_p_m2 + Water_AH_W_p_m2;
		}
	}

	//H_total_W_p_m2 (W/m2) is Eq 12 of Yang et al. (2013), total sensible heat flux (W/m^2), sum of fractional components from each cover type
	//Note: Theory of Yang et al. (2013) above Eq 12, H_localAir_to_mesoAir = H_ground_to_localAir in steady state to maintain energy balance
	H_total_W_p_m2 = (ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) * ImpH_W_p_m2 + TreeCover_frac * TreeH_W_p_m2 + ShortVegCover_noTreeCanopy_frac * SVegH_W_p_m2 +	SoilCover_noTreeCanopy_frac * SoilH_W_p_m2 + WaterCover_noTreeCanopy_frac * WaterH_W_p_m2;
	//LE_total_W_p_m2 (W/m2) is Eq 13 of Yang et al. (2013), total latent heat flux (W/m^2), sum of fractional components from each cover type
	//Note: Theory of Yang et al. (2013) above Eq 12, LE_localAir_to_mesoAir = LE_ground_to_localAir in steady state to maintain energy balance
	LE_total_W_p_m2 = (ImperviousCover_noTreeCanopy_frac + PermeablePavementCover_noTreeCanopy_frac) * ImpLE_W_p_m2 + TreeCover_frac * TreeLE_W_p_m2 +	ShortVegCover_noTreeCanopy_frac * SVegLE_W_p_m2 + SoilCover_noTreeCanopy_frac * SoilLE_W_p_m2 +	WaterCover_noTreeCanopy_frac * WaterLE_W_p_m2;

	//AtmosphericBoundaryLayer_Thickness_max_m (m) is the maximum ABL thickness, ranging from 100s to 1000s of m, estimated at 1500m
	//Note: Consider refactor to compute value based on solar radiation, sensible heat flux, temperature and windspeed
	//Note: AbsHumidity_mesoScale_kg_p_m3 (kg/m3) and Tair_mesoScale_K (K) very sensitive to ABL thickness, so adjust to improve performance
	double AtmosphericBoundaryLayer_Thickness_max_m = 1500;
	//AtmosphericBoundaryLayer_Thickness_min_m (m) is the minimum ABL thickness, ranging from 10s to 100s of m, estimated at 50m
	//Note: Consider refactor to compute value based on solar radiation, sensible heat flux, temperature and windspeed
	//Note: AbsHumidity_mesoScale_kg_p_m3 (kg/m3) and Tair_mesoScale_K (K) very sensitive to ABL thickness, so adjust to improve performance
	double AtmosphericBoundaryLayer_Thickness_min_m = 50;
	//AtmosphericBoundaryLayer_Thickness_max_hr (hr) is the maximum thickness time from midnight, hr = 0, estimated at 13hr
	//Note: This should be based on solar radiation, sensible heat flux, temperature and windspeed
	double AtmosphericBoundaryLayer_Thickness_max_hr = 13;
	//SinWave_Coeff_A_m is the amplitude of the wave, defined as A = (thickness_max - thickness_min) / 2
	double SinWave_Coeff_A_m = (AtmosphericBoundaryLayer_Thickness_max_m - AtmosphericBoundaryLayer_Thickness_min_m) / 2;
	//SineWave_Coeff_B_hr is the frequency of the wave, defined as B = 2π / 24, based on two pi equals 360 degrees, and 24 hours in day
	double SineWave_Coeff_B_hr = 2.0 * M_PI / Ratio_Hour_to_Day;
	//SineWave_Coeff_C_hr is the horizontal shift to align the peak with DiurnalCycle_hr, defined as ...
	// ... C = AtmosphericBoundaryLayer_Thickness_max_hr - (π/ (2 * B))
	double SineWave_Coeff_C_hr = AtmosphericBoundaryLayer_Thickness_max_hr - (M_PI / (2.0 * SineWave_Coeff_B_hr));
	//SineWave_Coeff_D_m is the vertical shift of the wave, defined as D = (height_max + height_min) / 2
	double SineWave_Coeff_D_m = (AtmosphericBoundaryLayer_Thickness_max_m + AtmosphericBoundaryLayer_Thickness_min_m) / 2;
	//AtmosphericBoundaryLayer_Thickness_m (m) is the height of the ABL, defined as AtmosphericBoundaryLayer_Thickness_m = A * sin(B * (hour_int - C)) + D
	double AtmosphericBoundaryLayer_Thickness_m = SinWave_Coeff_A_m * sin(SineWave_Coeff_B_hr * (Diurnal_Hour_HH - SineWave_Coeff_C_hr)) + SineWave_Coeff_D_m;
	//AtmosphericBoundaryLayer_Thickness_km (km) is the height of the ABL converted to km with Ratio_km_to_m
	double AtmosphericBoundaryLayer_Thickness_km = AtmosphericBoundaryLayer_Thickness_m * Ratio_km_to_m;
	//ABL_adjust_frac (fraction) reduces the influence of the atmospheric boundary layer thickness on Tair_mesoScale_K to 10% of standard thickness
	//Note: Based very roughly on data discussed with Dr. Holst from KIT, Germany; heterogeneity in the ABL is often layered, with low lying inversions
	double ABL_adjust_frac = 0.1;
	//Resistance_Aerodynamic_CanopyToMesoLayer_max_s_p_m (s/m) defined arbitrarily as 100 s/m
	double Resistance_Aerodynamic_CanopyToMesoLayer_max_s_p_m = 100;

	//If folder->ParamDict["MapPixel_ID"] equals reffolder->ParamDict["MapPixel_ID"] then update for reference folder mesoScale values
	if (folder->ParamDict["MapPixel_ID"] == reffolder->ParamDict["MapPixel_ID"]) {
		//If H_total_W_p_m2 (W/m2) <= 0 then Tair_mesoScale_K > Tair_localCell_K to maintain Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m > 0
		//Note: Atmospheric stability is characterized by Tair_mesoScale_K > Tair_localCell_K, and H_total_W_p_m2 < 0 is downwelling 
		//Note: Ensure Tair_mesoScale_K > Tair_localCell_K for all pixels by computing maximum potential Tair_localCell_K
		if (H_total_W_p_m2 <= 0) {
			//Tair_mesoScale_final_K (K) defined as Tair_localCell_K + (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km)
			//Note: Approximation of the environmental lapse rate and its effect on air temperature is based on Eq 5.12 in Stull (2000)
			Tair_mesoScale_final_K = Tair_localCell_K + (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km);
		}
		//If H_total_W_p_m2 (W/m2) > 0 then Tair_mesoScale_K < Tair_localCell_K to maintain Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m > 0
		//Note: Atmospheric instability is characterized by Tair_mesoScale_K < Tair_localCell_K, and H_total_W_p_m2 > 0 is upwelling 
		if (H_total_W_p_m2 > 0) {
			//Tair_mesoScale_final_K (K) defined as Tair_localCell_K + (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km)
			//Note: Approximation of the environmental lapse rate and its effect on air temperature is based on Eq 5.12 in Stull (2000)
			Tair_mesoScale_final_K = Tair_localCell_K - (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km);
		}
	}
	//Else If folder->ParamDict["MapPixel_ID"] not equal to reffolder->ParamDict["MapPixel_ID"] then update for non-reference folder mesoScale values
	else if (folder->ParamDict["MapPixel_ID"] != reffolder->ParamDict["MapPixel_ID"]) {
		//If H_total_W_p_m2 (W/m2) & reffolder->VarDict["H_total_W_p_m2"] <= 0, then atmosphere is stable and Tair_localCell_K < Tair_mesoScale_K
		if (H_total_W_p_m2 <= 0 && reffolder->VarDict["H_total_W_p_m2"] <= 0) {
			//If Tair_localCell_K (K) > reffolder Tair_mesoScale_final_K (K) then cell has unstable atmosphere, so increase Tair_mesoScale_final_K
			if (Tair_localCell_K >= reffolder->VarDict["Tair_mesoScale_final_K"]) {
				//Tair_mesoScale_final_K (K) defined as Tair_localCell_K + ABL_adjust_frac * (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km)
				//Note: Approximation of the environmental lapse rate and its effect on air temperature is based on Eq 5.12 in Stull (2000)
				Tair_mesoScale_final_K = Tair_localCell_K + ABL_adjust_frac * (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km);
			}
			//Else Tair_localCell_K (K) < Tair_mesoScale_K when H_total_W_p_m2 < 0, then stable atmosphere with reffolder Tair_mesoScale_K
			else {
				//Tair_mesoScale_final_K (K) defined as reffolder Tair_mesoScale_final_K
				Tair_mesoScale_final_K = reffolder->VarDict["Tair_mesoScale_final_K"];
			}
		}
		//If H_total_W_p_m2 (W/m2) & reffolder->VarDict["H_total_W_p_m2"] > 0, then atmosphere is unstable and Tair_localCell_K > Tair_mesoScale_K
		else if (H_total_W_p_m2 > 0 && reffolder->VarDict["H_total_W_p_m2"] > 0) {
			//If Tair_localCell_K (K) < reffolder Tair_mesoScale_final_K (K) then cell has stable atmosphere, so decrease Tair_mesoScale_final_K
			if (Tair_localCell_K < reffolder->VarDict["Tair_mesoScale_final_K"]) {
				//Tair_mesoScale_final_K (K) defined as Tair_localCell_K - ABL_adjust_frac * (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km)
				//Note: Approximation of the environmental lapse rate and its effect on air temperature is based on Eq 5.12 in Stull (2000)
				Tair_mesoScale_final_K = Tair_localCell_K - ABL_adjust_frac * (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km);
			}
			//Else Tair_localCell_K (K) >= Tair_mesoScale_K when H_total_W_p_m2 > 0, then unstable atmosphere with reffolder Tair_mesoScale_K
			else {
				//Tair_mesoScale_final_K (K) defined as reffolder Tair_mesoScale_final_K
				Tair_mesoScale_final_K = reffolder->VarDict["Tair_mesoScale_final_K"];
			}
		}
		//Else If H_total_W_p_m2 (W/m2) & reffolder->VarDict["H_total_W_p_m2"] are different sign, then Tair_mesoScale_K <> reffolder->VarDict["Tair_mesoScale_K"]
		//Note: Tair_mesoScale_K varies spatially across domain due to heterogeneity within boundary layer, likely during sunrise and sunset transitions
		else {
			//If H_total_W_p_m2 (W/m2) <= 0 then Tair_mesoScale_K > Tair_localCell_K to maintain Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m > 0
			//Note: Atmospheric stability is characterized by Tair_mesoScale_K > Tair_localCell_K, and H_total_W_p_m2 < 0 is downwelling 
			if (H_total_W_p_m2 <= 0) {
				//Tair_mesoScale_final_K (K) defined as Tair_localCell_K + ABL_adjust_frac * (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km)
				//Note: Approximation of the environmental lapse rate and its effect on air temperature is based on Eq 5.12 in Stull (2000)
				Tair_mesoScale_final_K = Tair_localCell_K + ABL_adjust_frac * (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km);
			}
			//If H_total_W_p_m2 (W/m2) > 0 then Tair_mesoScale_K < Tair_localCell_K to maintain Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m > 0
			//Note: Atmospheric instability is characterized by Tair_mesoScale_K < Tair_localCell_K, and H_total_W_p_m2 > 0 is upwelling 
			if (H_total_W_p_m2 > 0) {
				//Tair_mesoScale_final_K (K) defined as Tair_localCell_K + ABL_adjust_frac * (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km)
				//Note: Approximation of the environmental lapse rate and its effect on air temperature is based on Eq 5.12 in Stull (2000)
				Tair_mesoScale_final_K = Tair_localCell_K - ABL_adjust_frac * (AtmosphericBoundaryLayer_Thickness_km * Gamma_EnvironmentalLapseRate_C_p_km);
			}
		}
	}

	//Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m (s/m) is based on rearranged form of Eq 1 from Yang et al. (2013), where ra = [(rho*Cp)* (Ta - Tb)] / H, ...
	//Note: Eq 1 of Yang et al. (2013), H = [(rho*Cp)* (Ta - Tb)] / ra, and ra = Resistance_Aerodynamic_CanopyToMesoLayer_Fitting_s_p_m
	//Note: ... Tb = Tair_mesoScale_K, Ta = Tair_localCell_K, H = H_total_W_p_m2 (W/m2), rho = Density_Air_kg_p_m3, Cp = HeatCapacity_Air_J_p_kg_p_K
	//Note: Unit balance right hand side = (W/m2) * (s/m) / [(kg/m3) * (J/kg/K)] = (J/s/m2) * (s/m) / (J/m3/K) = (J/m3) / (J/m3/K) = K
	Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m = (Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) *
		(Tair_localCell_K - Tair_mesoScale_final_K) / H_total_W_p_m2;

	//If Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m (s/m) > Resistance_Aerodynamic_CanopyToMesoLayer_max_s_p_m then unreasonable
	//Note: Ratio of (Tair_localCell_K - Tair_mesoScale_K) / H_total_W_p_m2 determines Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m
	//Note: Adjust Tair_mesoScale_K (K) to maintain reasonable Ratio of (Tair_localCell_K - Tair_mesoScale_K) / H_total_W_p_m2 ~ 1/20
	//Note: Consider refactor to improve error handling for large values of Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m 
	if (Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m > Resistance_Aerodynamic_CanopyToMesoLayer_max_s_p_m) {
		//Tair_localCell_K_minus_T_mesoScale_K (K) defined as ~1/20.0 of H_total_W_p_m2, using Diurnal_Hour_HH to add diurnal variability to fraction
		double Tair_localCell_K_minus_T_mesoScale_K_abs_K = 1 / (15.0 + Diurnal_Hour_HH) * abs(H_total_W_p_m2);
		//If H_total_W_p_m2 (W/m2) <= 0 then stable atmosphere 
		if (H_total_W_p_m2 <= 0) {
			//Tair_mesoScale_final_K (K) is Tair_localCell_K plus abs(Tair_localCell_K_minus_T_mesoScale_K) to create stable atmosphere
			Tair_mesoScale_final_K = Tair_localCell_K + Tair_localCell_K_minus_T_mesoScale_K_abs_K;
		}
		//Else If H_total_W_p_m2 (W/m2) > 0 then unstable atmosphere 
		else if (H_total_W_p_m2 > 0) {
			//Tair_mesoScale_final_K (K) is Tair_localCell_K - abs(Tair_localCell_K_minus_T_mesoScale_K) to create unstable atmosphere
			Tair_mesoScale_final_K = Tair_localCell_K - Tair_localCell_K_minus_T_mesoScale_K_abs_K;
		}
		//Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m (s/m) recomputed w rearranged form of Eq 1 from Yang et al. (2013), where ra = [(rho*Cp)* (Ta - Tb)] / H
		Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m = (Density_Air_kg_p_m3 * HeatCapacity_Air_J_p_kg_p_K) *
			(Tair_localCell_K - Tair_mesoScale_final_K) / H_total_W_p_m2;
	}

	//AbsHumidity_mesoScale_kg_p_m3 (kg/m^3) is based on rearranged form of Eq 2 from Yang et al. (2013), where AHb = AHa - (LE*ra)/Lambda, ...
	//Note: ... AHb = AbsHumidity_mesoScale_kg_p_m3, AHa = AbsHumidityAct_localCell_kg_p_m3, LE = LE_total_W_p_m2, ...
	//Note: ... Lambda = LatentHeatVaporization_Water_J_p_kg, ra = Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m
	//Note: Unit balance right hand side = (W/m2) * (s/m) / (J/kg) = (J/s/m2) * (s/m) / (J/kg) = (J/m3) / (J/kg) = kg/m3
	AbsHumidity_mesoScale_final_kg_p_m3 = AbsHumidityAct_localCell_kg_p_m3 - (LE_total_W_p_m2 *	Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m) / 
		LatentHeatVaporization_Water_J_p_kg;
	//If AbsHumidity_mesoScale_final_kg_p_m3 < 0 then set to 0; 
	//Note: This error may emerge due to algorithm using same Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m for heat and humidity flux
	if (AbsHumidity_mesoScale_final_kg_p_m3 < 0) { AbsHumidity_mesoScale_final_kg_p_m3 = 0; }
}

//CollectVariables_CoolAir function will store all values to memory
void HeatFluxCal::CollectVariables_CoolAir(Inputs* input, DataFolder* folder, DataFolder* reffolder, SolarCalculator* solarCalc, int MapPixel_ID, int timeStep)
{
	if (timeStep == 0) {
		HeatFlux_InitializeVectors(input);
	}
	//Tair_variation_threshold_K (K) represents maximum likely variation between weather station and pixel values in one time step
	//Note: Used for error handling, to protect against making very unlikely predictions 
	//cte 2025 Return from 440 to 40
	double Tair_variation_threshold_K = 40;
	//If abs(Tair_localCell_K - Tair_referenceCell_K) > 40
	if ((abs(Tair_localCell_K - Tair_referenceCell_K) > Tair_variation_threshold_K)) {
		int MapPixel_ID = int(folder->ParamDict["MapPixel_ID"]);
		cout << "Warning: The i-Tree Cool Air model predicted Tair of " << Tair_localCell_K << " K when observed Tair is " << Tair_referenceCell_K << " K" << endl;
		cout << " ... which exceeds the threshold of " << Tair_variation_threshold_K << " and triggers this notification." << endl;
		cout << "Aborting: This warning triggers the HydroPlus simulation to abort." << endl;
		cout << "Explanation: Such large variation in Tair suggests errors with input maps or parameters." << endl;
		cout << "Explanation: This occurred at timestep " << timeStep << " and date hour " << input->SimulationDate_GDH[timeStep] << endl;
		cout << "Explanation: This occurred at MapPixel_ID " << folder->ParamDict["MapPixel_ID"] << endl;
		cout << "Explanation: LandCover_Class " << input->NLCDLandCoverData[MapPixel_ID] << endl;
		cout << "Explanation: TreeCover_frac " << input->TreeCoverData[MapPixel_ID] << endl;
		cout << "Explanation: ImperviousCover_frac " << input->ImperCoverData[MapPixel_ID] << endl;
		cout << "Explanation: DEM_m " << input->DEM[MapPixel_ID] << endl;
		cout << "Explanation: Tair_K " << Tair_referenceCell_K << endl;
		cout << "Explanation: WindSpeed_mps " << WindSpeed_Reference_m_p_s << endl;
		cout << "Explanation: AnthropogenicHeat_Flux_Total_Avg_Wpm2 " << input->AnthropogenicHeat_Flux_Total_Avg_Wpm2[MapPixel_ID] << endl;
		cout << "Correction: Improve inputs or modify code to allow for such large Tair variation." << endl;
		//Call abort function, which ends the HydroPlus.exe simulation
		abort();
	}

	//Tair_K (K) = int((100.0*Tair_localCell_K) + 0.5)/100.0, air temperature of the local pixel
	//Note: RHS function divides by 100 after taking integer of the term that takes product with 100 and sums 0.5 to round up
	folder->VarDict["Tair_K"] = int((100.0 * Tair_localCell_K) + 0.5) / 100.0;
	//Tdew_K (K) = int((100.0*Tdew_localCell_K) + 0.5)/100.0, dew point temperature of the local pixel
	folder->VarDict["Tdew_K"] = int((100.0 * Tdew_localCell_K) + 0.5) / 100.0;
	//AbsHumidity_kg_p_m3 (kg/m3) = int((10000.0*AbsHumidityAct_localCell_kg_p_m3) + 0.5)/10000.0, absolute humidity of the local pixel
	folder->VarDict["AbsHumidity_kg_p_m3"] = int((10000.0 * AbsHumidityAct_localCell_kg_p_m3) + 0.5) / 10000.0;
	//Tair_mesoScale_final_K (K) = int((100.0*Tair_mesoScale_final_K) + 0.5)/100.0, air temperature of the mesocale layer
	//Note: Tair_mesoScale_final_K (K), mesoScale air temperature needed for output and HeatFluxCal::RescaleVariables_CoolAir
	//Note: Do not remove this Tair_mesoScale_final_K variable or replace with folder->VarDict["Tair_mesoScale_K"]
	folder->VarDict["Tair_mesoScale_final_K"] = int((100.0 * Tair_mesoScale_final_K) + 0.5) / 100.0;
	//AbsHumidity_mesoScale_final_kg_p_m3 (kg/m3) = int((10000.0*AbsHumidity_mesoScale_final_kg_p_m3) + 0.5)/10000.0, absolute humidity of the mesoscale layer
	//AbsHumidity_mesoScale_final_kg_p_m3 (kg/m3), mesoScale absolute humidity needed for output and HeatFluxCal::RescaleVariables_CoolAir
	//Note: Do not remove this AbsHumidity_mesoScale_final_kg_p_m3 variable or replace with folder->VarDict["AbsHumidity_mesoScale_kg_p_m3"]
	folder->VarDict["AbsHumidity_mesoScale_final_kg_p_m3"] = int((10000.0 * AbsHumidity_mesoScale_final_kg_p_m3) + 0.5) / 10000.0;
	//Tair_mesoScale_K (K) = Tair_mesoScale_K[i] at full precision, air temperature of the mesocale layer
	//Note: Tair_mesoScale_K (K), mesoScale air temperature needed for energy balance of HeatFluxCal::Tair_AbsHumidity_LayerBalance_NumericalMethod
	//Note: Do not remove this Tair_mesoScale_K variable or replace with folder->VarDict["Tair_mesoScale_final_K"]
	folder->VarDict["Tair_mesoScale_K"] = Tair_mesoScale_K;
	//AbsHumidity_mesoScale_kg_p_m3 (kg/m3) = AbsHumidity_mesoScale_kg_p_m3 at full precision, absolute humidity of the mesoscale layer
	//Note: AbsHumidity_mesoScale_kg_p_m3 (kg/m3), mesoScale absolute humidity needed for energy balance of HeatFluxCal::Tair_AbsHumidity_LayerBalance_NumericalMethod
	//Note: Do not remove this AbsHumidity_mesoScale_kg_p_m3 variable or replace with folder->VarDict["AbsHumidity_mesoScale_final_kg_p_m3"]
	folder->VarDict["AbsHumidity_mesoScale_kg_p_m3"] = AbsHumidity_mesoScale_kg_p_m3;
	//Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m (s/m) is Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m (s/m), using Tair_mesoScale_final_K (K)
	folder->VarDict["Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m"] = Resistance_Aerodynamic_CanopyToMesoLayer_s_p_m;

	//Note: Net Radiation, Sensible Heat (H), and Latent Energy (LE) terms for each cover type are per meter squared, not scaled to fractional area
	folder->VarDict["ImpNR_W_p_m2"] = ImpNR_W_p_m2;
	Imp_AH_W_p_m2_vec[MapPixel_ID] = Imp_AH_W_p_m2;
	folder->VarDict["ImpH_W_p_m2"] = ImpH_W_p_m2;
	folder->VarDict["ImpLE_W_p_m2"] = ImpLE_W_p_m2;
	ImpDeltaQ_W_p_m2_vec[MapPixel_ID] = ImpDeltaQ_W_p_m2;

	//Note: Net Radiation, Sensible Heat (H), and Latent Energy (LE) terms for each cover type are per meter squared, not scaled to fractional area
	folder->VarDict["TreeNR_W_p_m2"] = TreeNR_W_p_m2;
	Tree_AH_W_p_m2_vec[MapPixel_ID] = Tree_AH_W_p_m2;
	folder->VarDict["TreeH_W_p_m2"] = TreeH_W_p_m2;
	folder->VarDict["TreeLE_W_p_m2"] = TreeLE_W_p_m2;
	folder->VarDict["TreeLEE_W_p_m2"] = TreeLEE_W_p_m2;
	folder->VarDict["TreeLET_W_p_m2"] = TreeLET_W_p_m2;
	TreeDeltaQ_W_p_m2_vec[MapPixel_ID] = TreeDeltaQ_W_p_m2;

	//Note: Net Radiation, Sensible Heat (H), and Latent Energy (LE) terms for each cover type are per meter squared, not scaled to fractional area
	folder->VarDict["SVegNR_W_p_m2"] = SVegNR_W_p_m2;
	SVeg_AH_W_p_m2_vec[MapPixel_ID] = SVeg_AH_W_p_m2;
	folder->VarDict["SVegH_W_p_m2"] = SVegH_W_p_m2;
	folder->VarDict["SVegLE_W_p_m2"] = SVegLE_W_p_m2;
	folder->VarDict["SVegLEE_W_p_m2"] = SVegLEE_W_p_m2;
	folder->VarDict["SVegLET_W_p_m2"] = SVegLET_W_p_m2;
	SVegDeltaQ_W_p_m2_vec[MapPixel_ID] = SVegDeltaQ_W_p_m2;

	//Note: Net Radiation, Sensible Heat (H), and Latent Energy (LE) terms for each cover type are per meter squared, not scaled to fractional area
	folder->VarDict["SoilNR_W_p_m2"] = SoilNR_W_p_m2;
	Soil_AH_W_p_m2_vec[MapPixel_ID] = Soil_AH_W_p_m2;
	folder->VarDict["SoilH_W_p_m2"] = SoilH_W_p_m2;
	folder->VarDict["SoilLE_W_p_m2"] = SoilLE_W_p_m2;
	SoilDeltaQ_W_p_m2_vec[MapPixel_ID] = SoilDeltaQ_W_p_m2;

	//Note: Net Radiation, Sensible Heat (H), and Latent Energy (LE) terms for each cover type are per meter squared, not scaled to fractional area
	folder->VarDict["WaterNR_W_p_m2"] = WaterNR_W_p_m2;
	Water_AH_W_p_m2_vec[MapPixel_ID] = Water_AH_W_p_m2;
	folder->VarDict["WaterH_W_p_m2"] = WaterH_W_p_m2;
	folder->VarDict["WaterLE_W_p_m2"] = WaterLE_W_p_m2;
	WaterDeltaQ_W_p_m2_vec[MapPixel_ID] = WaterDeltaQ_W_p_m2;

	//Note: Net Radiation, Sensible Heat (H), and Latent Energy (LE) terms for total are per meter squared and were scaled by fractional areas
	NR_total_W_p_m2_vec[MapPixel_ID] = NR_total_W_p_m2;
	folder->VarDict["H_total_W_p_m2"] = H_total_W_p_m2;
	folder->VarDict["LE_total_W_p_m2"] = LE_total_W_p_m2;
	DeltaQ_W_p_m2_vec[MapPixel_ID] = DeltaQ_W_p_m2;

	//Store Anthropogenic Heat (W/m2) variables, total and for each land cover type
	AH_total_W_p_m2_vec[MapPixel_ID] = AH_total_W_p_m2;

	//Calculate HeatMetrics with call to HeatMetrics_Calc functions
	//HeatMetrics_Calc input structure from HeatMetrics_Calc.h is referenced as wetBulbGlobeTempCalc object
	HeatMetrics_Calc HeatMetricsCalc(input, solarCalculator);

	//Twetbulbglobe_K from call to HeatMetricsCalc.WetBulbGlobeTemperature_Calc function to compute wet bulb globe temperatures 
	//Note: Radiation_Shortwave_Direct_W_p_m2 and Radiation_Shortwave_Diffuse_W_p_m2 for single or multiple stations
	//Note: Radiation_Shortwave_Direct_W_p_m2 adjusted for Cos_IncidenceAngle_Solar of terrain azimuth and slope
	//Note: WetBulbGlobeTemperature algorithm from Liljegren et al. (2008) code: https://github.com/mdljts/wbgt/blob/master/src/wbgt.c
	double Twetbulbglobe_K = HeatMetricsCalc.WetBulbGlobeTemperature_Calc(input, folder, reffolder, MapPixel_ID, timeStep, Radiation_Shortwave_Direct_W_p_m2, Radiation_Shortwave_Diffuse_W_p_m2, Cos_IncidenceAngle_Solar);
	//Twetbulbglobe_K (K) is scaled to 2 digits precision
	//Note: RHS function divides by 100 after taking integer of the term that takes product with 100 and sums 0.5 to round up
	folder->VarDict["Twetbulbglobe_K"] = int((100.0 * Twetbulbglobe_K) + 0.5) / 100.0;

	//HeatIndex_K from call to HeatMetricsCalc.HeatIndex_Calc function to compute heat index temperatures 
	double HeatIndex_K = HeatMetricsCalc.HeatIndex_Calc(input, folder, reffolder, MapPixel_ID, timeStep);
	//HeatIndex_K (K) is equivalent to the NWS calculated HeatIndex_NWS_K, scaled to 2 digits precision
	//Note: RHS function divides by 100 after taking integer of the term that takes product with 100 and sums 0.5 to round up
	folder->VarDict["HeatIndex_K"] = int((100.0 * HeatIndex_K) + 0.5) / 100.0;

	//Humidex_K from call to HeatMetricsCalc.Humidex_Calc function to compute humidex temperatures 
	double Humidex_K = HeatMetricsCalc.Humidex_Calc(input, folder, reffolder, MapPixel_ID, timeStep);
	//Humidex_K (K) is scaled to 2 digits precision
	//Note: RHS function divides by 100 after taking integer of the term that takes product with 100 and sums 0.5 to round up
	folder->VarDict["Humidex_K"] = int((100.0 * Humidex_K) + 0.5) / 100.0;
}

void HeatFluxCal::HeatFlux_InitializeVectors(Inputs* input) {
	double nrows = input->nrows;
	double ncols = input->ncols;
	// Initialize with correct size and value
	WaterDeltaQ_W_p_m2_vec.assign(nrows * ncols, 0.0); 
	SoilDeltaQ_W_p_m2_vec.assign(nrows * ncols, 0.0);
	DeltaQ_W_p_m2_vec.assign(nrows * ncols, 0.0);
	NR_total_W_p_m2_vec.assign(nrows * ncols, 0.0);
	Water_AH_W_p_m2_vec.assign(nrows * ncols, 0.0);
	Soil_AH_W_p_m2_vec.assign(nrows * ncols, 0.0);
	SVeg_AH_W_p_m2_vec.assign(nrows * ncols, 0.0);
	Tree_AH_W_p_m2_vec.assign(nrows * ncols, 0.0);
	Imp_AH_W_p_m2_vec.assign(nrows * ncols, 0.0);
	AH_total_W_p_m2_vec.assign(nrows * ncols, 0.0);
	SVegDeltaQ_W_p_m2_vec.assign(nrows * ncols, 0.0);
	TreeDeltaQ_W_p_m2_vec.assign(nrows * ncols, 0.0);
	ImpDeltaQ_W_p_m2_vec.assign(nrows * ncols, 0.0);
}
//NetRadiation_Prior_Calc function to update rolling values and return the new average
double HeatFluxCal::NetRadiation_Prior_Calc(int timeStep, int NR_vec_size, vector<double>& NetRadiation_W_p_m2_vec, double NetRadiation_W_p_m2) 
{
	//NR_priorTS_W_p_m2 initialized to 0
	double NR_priorTS_W_p_m2 = 0;
	//If timeStep is zero return NR_priorTS_W_p_m2 as 0
	if (timeStep == 0) {
		return NR_priorTS_W_p_m2;
	}
	//Else If timeStep is 1 populate vector with uniform values
	else if (timeStep == 1) {
		//NetRadiation_W_p_m2_vec.assign(NR_vec_size , NetRadiation_W_p_m2) to assign initial values to vector
		NetRadiation_W_p_m2_vec.assign(NR_vec_size, NetRadiation_W_p_m2);
	}
	//Else for timeStep > 1
	else {
		//NetRadiation_W_p_m2_vec.erase(NetRadiation_W_p_m2_vec.begin()) to erase oldest element in vector
		NetRadiation_W_p_m2_vec.erase(NetRadiation_W_p_m2_vec.begin());
		//NetRadiation_W_p_m2_vec.push_back(NetRadiation_W_p_m2) to add newest element to vector
		NetRadiation_W_p_m2_vec.push_back(NetRadiation_W_p_m2);
	}

	//If not NetRadiation_W_p_m2_vec.empty() then compute and return the average, ensuring no division by zero
	if (!NetRadiation_W_p_m2_vec.empty()) {
		//NR_priorTS_W_p_m2 = accumulate(NetRadiation_W_p_m2_vec.begin(), NetRadiation_W_p_m2_vec.end(), 0.0) / NetRadiation_W_p_m2_vec.size();
		NR_priorTS_W_p_m2 = accumulate(NetRadiation_W_p_m2_vec.begin(), NetRadiation_W_p_m2_vec.end(), 0.0) / NetRadiation_W_p_m2_vec.size();
	}
	//return NR_priorTS_W_p_m2
	return NR_priorTS_W_p_m2;
}