/*
 * SUMMARY:      InitModelState.c - Initialize the model state variables
 * USAGE:        Part of DHSVM
 *
 * AUTHOR:       Bart Nijssen
 * ORG:          University of Washington, Department of Civil Engineering
 * E-MAIL:       nijssen@u.washington.edu
 * ORIG-DATE:    Apr-96
 * Last Change: Mon Dec  2 13:36:41 2002 by Scott Waichler <waichler@tuff.pnl.gov>
 * DESCRIPTION:  Initialize the model state variables using initial conditions
 *               or a saved state from an earlier model run
 * DESCRIP-END.
 * FUNCTIONS:    InitModelState()
 * COMMENTS:     
 */

#ifndef lint
static char vcid[] = "$Id: DefaultModelState.c,v 1.3 2001/05/15 17:30:25 waichler Exp $";
#endif /* lint */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "settings.h"
#include "data.h"
#include "DHSVMerror.h"
#include "fileio.h"
#include "functions.h"
#include "constants.h"
#include "sizeofnt.h"
#include "soilmoisture.h"
#include "varid.h"

/*****************************************************************************
  Function name: InitModelState()

  Purpose      : Initialize the state of the model using initial conditions
                 or a saved state from an earlier model run

  Required     :

  Returns      : void

  Modifies     :

  Comments : 
    Initialize the model state, by reading the state variables from a series
    of files.  This allows restarts of the model from any timestep for which
    the model state is known.  These model states can be stored using the
    routine StoreModelState().  Timesteps at which to dump the model state
    can be specified in the file with dump information.

*****************************************************************************/
void DefaultModelState(DATE *Start, MAPSIZE *Map, OPTIONSTRUCT *Options,
		    PRECIPPIX **PrecipMap, SNOWPIX **SnowMap, 
		    SOILPIX **SoilMap, LAYER Soil, SOILTABLE *SType, 
		    VEGPIX **VegMap, LAYER Veg, VEGTABLE *VType, char *Path, 
		    SNOWTABLE *SnowAlbedo, TOPOPIX **TopoMap, 
		    ROADSTRUCT **Network, UNITHYDRINFO *HydrographInfo,
		    float *Hydrograph, STATESTRUCT State)
{
  const char *Routine = "InitModelState";
  char Str[NAMESIZE+1];
  char FileName[NAMESIZE+1];
  FILE *HydroStateFile;
  int i;			/* counter */
  int x;			/* counter */
  int y;			/* counter */
  int NSoil;			/* Number of soil layers for current pixel */
  int NVeg;			/* Number of veg layers for current pixel */
  float TotalRootDepth = 0;
  float remove;

  printf("Restoring model state\n");

  /* Restore canopy interception */
  for (i = 0; i < Veg.MaxLayers; i++) {
    for (y = 0; y < Map->NY; y++) {
      for (x = 0; x < Map->NX; x++) {
        if (InBasin(TopoMap[y][x].Mask)) {
          NVeg = Veg.NLayers[(VegMap[y][x].Veg-1)];
          if (i < NVeg){
            PrecipMap[y][x].IntRain[i] = 0;
            PrecipMap[y][x].IntSnow[i] = 0;
          }
        }
      }
    }
  }

  
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (InBasin(TopoMap[y][x].Mask))
        PrecipMap[y][x].TempIntStorage = 0; 
    }
  }
  
  /* Restore snow pack conditions *********************************************/
  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) { 
      if (InBasin(TopoMap[y][x].Mask)) {
        SnowMap[y][x].HasSnow = 0;
        SnowMap[y][x].LastSnow = 0;
        SnowMap[y][x].Swq = 0;
        SnowMap[y][x].PackWater = 0;
        SnowMap[y][x].TPack = 0;
        SnowMap[y][x].SurfWater = 0;
        SnowMap[y][x].TSurf = 0;
        SnowMap[y][x].ColdContent = 0;
        SnowMap[y][x].Albedo = 0;
      }
    }
  }

 
  /* Restore soil conditions **********************************************/
  for (i = 0; i < Soil.MaxLayers+1; i++) {
    for (y = 0; y < Map->NY; y++) {
      for (x = 0; x < Map->NX; x++) {
        if (InBasin(TopoMap[y][x].Mask)) {
          NSoil = Soil.NLayers[(SoilMap[y][x].Soil-1)];
          if (i < NSoil) {
            SoilMap[y][x].Moist[i] = 
              State.SoilMoistureFactor * SType[SoilMap[y][x].Soil - 1].Porosity[i];
            SoilMap[y][x].Temp[i] = State.SoilTemp;
          }
          if (i == NSoil) {
            SoilMap[y][x].Moist[i] = 
              State.SoilMoistureFactor * SType[SoilMap[y][x].Soil - 1].Porosity[i-1];
          }

        }
      }
    }
  }

  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {
      if (InBasin(TopoMap[y][x].Mask)) {
        SoilMap[y][x].TSurf = 6.5;
        SoilMap[y][x].Qst = 0;
        SoilMap[y][x].Runoff = 0;
      }
    }
  }
  
  /* Calculate the water table depth at each point based on the soil 
     moisture profile. Give an error message if the water ponds on the
     surface since that should not be allowed at this point */
  remove=0.0;

  for (y = 0; y < Map->NY; y++) {
    for (x = 0; x < Map->NX; x++) {

      /* SatFlow needs to be initialized properly in the future.  For now it 
         will just be set to zero here */
      SoilMap[y][x].SatFlow = 0.0;
      if (InBasin(TopoMap[y][x].Mask)) {

        /* make sure depth at bottom of lowest roor zone < soil depth */
        TotalRootDepth = 0;
        for (i = 0; i < (Soil.NLayers[SoilMap[y][x].Soil-1]); i++) 
           TotalRootDepth += VType[VegMap[y][x].Veg-1].RootDepth[i];
        if( TotalRootDepth > SoilMap[y][x].Depth ) {
          printf("Total depth of root zone > soil depth in cell y: %d x: %d\n", y, x );
          exit(1);
        }

        if ((SoilMap[y][x].TableDepth = 
             WaterTableDepth((Soil.NLayers[SoilMap[y][x].Soil-1]),
                             SoilMap[y][x].Depth,
                             VType[VegMap[y][x].Veg-1].RootDepth,
                             SType[SoilMap[y][x].Soil-1].Porosity,
                             SType[SoilMap[y][x].Soil-1].FCap,
                             Network[y][x].Adjust, SoilMap[y][x].Moist)) 
            < 0.0) /*  ReportError((char *) Routine, 35);*/{
	      remove-=SoilMap[y][x].TableDepth*Map->DX*Map->DY;
	      SoilMap[y][x].TableDepth = 0.0;
	    }
        SoilMap[y][x].SatThickness = 0;
        SoilMap[y][x].CumGwRecharge = 0;
        SoilMap[y][x].CumChannelLoss = 0;
      }
      else {
        SoilMap[y][x].SatThickness = 0;
        SoilMap[y][x].TableDepth = 0;
        SoilMap[y][x].CumGwRecharge = 0;
        SoilMap[y][x].CumChannelLoss = 0;
      }
    }
  }
  if (remove>0.0){
  printf("WARNING:excess water in soil profile is %f m^3 \n",remove);
  printf("Expect possible large flood wave during first timesteps \n");
  }
  
  /* If the unit hydrograph is used for flow routing, initialize the unit 
     hydrograph array */

  if (Options->Extent == BASIN && Options->HasNetwork == FALSE) {
    sprintf(FileName, "%sHydrograph.State.%s", Path, Str);
    OpenFile(&HydroStateFile, FileName, "r", FALSE);
    for (i = 0; i < HydrographInfo->TotalWaveLength; i++)
      fscanf(HydroStateFile, "%f\n", &(Hydrograph[i]));
    fclose(HydroStateFile);
  }
}
