#! /bin/tcsh -f
# Process a single-day IMS snow ASCII file -> binary in GETD domain
# Usage: process_snow_24km.csh YEAR DOY(001-366)

set nonomatch

set in_LAI_dir = $GETD_ALEXI_LAI
set in_SNOWMASK_dir = $GETD_ALEXI_SNOW
set in_MET_dir = $GETD_ALEXI_MET 
set in_inso_dir = $GETD_ALEXI_INSO
set out_dir_et = $GETD_ET_OUT
set out_dir_esi = $GETD_ESI_OUT
set work_dir = $WORK_DIR
set tmp_dir = $TMP_DIR

# --- args ---
if ( $#argv != 2 ) then
  echo "Usage: $0 YEAR DOY(001-366)"
  exit 1
endif
set in_year = $1
set in_doy  = $2

# zero-pad DOY
if ( $in_doy < 10 ) then
  set idoy = 00$in_doy
else if ( $in_doy < 100 ) then
  set idoy = 0$in_doy
else
  set idoy = $in_doy
endif

echo Run ALEXI on $in_year $in_doy

#***************************************
# 1. Check ALEXI inputs.
# Note the input of the check requires
# the iday as digits instead of strings
# use in_doy will cause trouble.
#***************************************
echo Got $idoy > $CUR_DAY_LOG
set cur_met=$GETD_ALEXI_MET/$in_year$idoy
set et_file=$tmp_dir/XLE2.bin
#***************************************
# 2. Run ALEXI in ET mode
#***************************************
#Clean out the old outputs if any
#rm -f *.bin

# Run the ALEXI model with RS correction 
$BIN_DIR/alexi.x -r1 $SCRIPT_DIR/GETD_NA_2km_VLAI.cfg $in_year $in_doy 

if ( ! -e $et_file ) then
  echo Cannot find ALEXI output ET: $et_file
  goto error
endif

#***************************************
# 3. Move the outputs to the ET directory
#***************************************
set cur_out_dir = $out_dir_et/$in_year$idoy 

if (! -d $cur_out_dir ) then
  echo Creating $cur_out_dir
  mkdir $cur_out_dir
else
  rm $cur_out_dir/*
endif

mv -f $tmp_dir/*.bin $cur_out_dir
#cp -f $tmp_dir/GETD_QF$in_year$idoy.txt $cur_out_dir

# for time series analysis only
#mv -f $tmp_dir/GETD_QF$in_year$idoy.txt $out_dir_et/stat

goto done

#***************************************
# 4. Compute the ET in ESI mode, without 
#    RS correction
#***************************************

$BIN_DIR/alexi.x -r0 $SCRIPT_DIR/GETD_NA_2km_VLAI.cfg $in_year $in_doy

if ( ! -e $et_file ) then
  echo Cannot find ALEXI output ET: $et_file!
  goto error
endif

#***************************************
# 5. Move the outputs to the ESI directory
#***************************************
set cur_out_dir = $out_dir_esi/$in_year$idoy
#
if (! -d $cur_out_dir ) then
  echo Creating $cur_out_dir
  mkdir $cur_out_dir
else
  rm $cur_out_dir/*
endif
echo mv files to  $cur_out_dir
mv -f $tmp_dir/*.bin $cur_out_dir
#cp -f $tmp_dir/GETD_QF$in_year$idoy.txt $cur_out_dir

#***************************************
done:
  exit 0
#***************************************
error:
  exit 1

