#! /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

# --- 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

# --- required envs (defaults) ---
if ( ! $?WORK_DIR ) setenv WORK_DIR /app/run
if ( ! $?BIN_DIR  ) setenv BIN_DIR  /app/run
if ( ! $?GETD_ALEXI_SNOW ) then
  echo "ERROR: GETD_ALEXI_SNOW not set (destination)."
  exit 1
endif
set out_dir = "$GETD_ALEXI_SNOW"

set input_gz = ""

cp "$input_gz" "$WORK_DIR/ims_24km.asc"

if ( ! -e "$WORK_DIR/ims_24km.asc" ) then
  echo "ERROR: Missing $WORK_DIR/ims_24km.asc after decompress"
  exit 1
endif

# --- run converter ---
set cfg = "snow24km_1km.cfg"
if ( ! -e "$cfg" && -e "$WORK_DIR/$cfg" ) set cfg = "$WORK_DIR/$cfg"

if ( ! -e "$cfg" ) then
  echo "ERROR: cannot find snow config: $cfg"
  exit 1
endif

echo "Running: $BIN_DIR/getd.x -snow $cfg"
"$BIN_DIR/getd.x" -snow "$cfg" || exit 1

# --- move output ---
if ( -e "snow_mask.bin" ) then
  set dest = "$out_dir/${in_year}${idoy}"
  if ( ! -d "$dest" ) mkdir -p "$dest"
  mv -f "snow_mask.bin" "$dest/snow_mask"
  rm -f "$WORK_DIR/ims_24km.asc"
  echo "Snow mask created: $dest/snow_mask"
  exit 0
else
  echo "ERROR: Expected output snow_mask.bin not found."
  exit 1
endif
