#include <iostream>
using namespace std;

#include "snow_module.h"

//---------------------------------------------------------------------
CSnowModule::CSnowModule()
{
}
//---------------------------------------------------------------------

CSnowModule::CSnowModule(double* Temperature, double* Precipitation, double T_Rain, double T_Melt, double DD_FAC, int size)
{
	this->T_Rain	= T_Rain;
	this->T_Melt	= T_Melt;
	this->DD_FAC	= DD_FAC;
	this->size	= size;
	SnowStorage	= new double[size];
	MeltRate	= new double[size];
	// Calculate daily snow storage and snow melt
	// After calling this function snow storage and snow melt values are
	// available using public functions:
	// - 'Get_SnowStorage(int pos)' and
	// - 'Get_SnowMelt(int pos)'.
	_Calc_SnowModule(Temperature, Precipitation, T_Rain, T_Melt, DD_FAC, size);
}
//---------------------------------------------------------------------


//---------------------------------------------------------------------
// PUBLIC FUNCTIONS
//---------------------------------------------------------------------
double CSnowModule::Get_SnowStorage(int pos)
{
	if (pos > 0 && pos < size) // && SnowStorage ! NULL)
		return(SnowStorage[pos]);
	else
		return(-1.0);
}
//---------------------------------------------------------------------

double CSnowModule::Get_MeltRate(int pos)
{
	if (pos > 0 && pos < size) // && SnowMelt[pos] != NULL)
		return(MeltRate[pos]);
	else
		return(-1.0);
}
//---------------------------------------------------------------------



//---------------------------------------------------------------------
//				SNOW MODULE
//		Calculate daily snow storage and snow melt
//---------------------------------------------------------------------
void CSnowModule::_Calc_SnowModule(double *Temperature, double *Precipitation,
				   double T_Rain, double T_Melt, double DD_FAC,
				   int size)
{
	int i;

	// initital snow storage and snow melt values = 0.0
	SnowStorage[0]	= 0.0;
	MeltRate[0]		= 0.0;

	for (i = 1; i < size; i++)
	{
		// calculate snow accumulation
		if (Temperature[i] < T_Rain)
		{
			SnowStorage[i] = SnowStorage[i-1] + Precipitation[i];
			MeltRate[i] = 0.0;
		}

		// calculate snowmelt
		if (Temperature[i] > T_Melt)
		{
			MeltRate[i] = DD_FAC * max(0.0,Temperature[i] - T_Melt);
			if (MeltRate[i] > SnowStorage[i-1])
			{
				MeltRate[i] = SnowStorage[i-1];
				SnowStorage[i] = 0.0;
			}
			SnowStorage[i] = SnowStorage[i-1] - MeltRate[i];
		}

		// if temperature between T_Rain and T_Melt
		if ((Temperature[i] > T_Rain) && (Temperature[i] < T_Melt))
		{
			MeltRate[i] = 0.0;
			if (Precipitation[i] > 0.0) MeltRate[i] = Precipitation[i] / 2;
			if (MeltRate[i] > SnowStorage[i-1])
			{
				MeltRate[i] = SnowStorage[i-1];
				SnowStorage[i] = 0.0;
			}
			SnowStorage[i] = SnowStorage[i-1] - MeltRate[i];
		}

		if (SnowStorage[i] < 0.0) SnowStorage[i] = 0.0;
	}
}
//---------------------------------------------------------------------
