#!/bin/bash

# ICON
#
# ------------------------------------------
# Copyright (C) 2004-2026, DWD, MPI-M, DKRZ, KIT, ETH, MeteoSwiss
# Contact information: icon-model.org
# See AUTHORS.TXT for a list of authors
# See LICENSES/ for license information
# SPDX-License-Identifier: BSD-3-Clause
# ------------------------------------------

########################################################################################################################
#
# default user settings
#
# experiment name
 EXP="jf_30U1R3L3"
#
# source resolution of ICON grid
 ICON="R3L3"
#
# target resolution of regular grid
 GRID="r180x91"
#
########################################################################################################################

 TESTCASE="PA"
 iflag=""

# command options
 while getopts E:I:G:T:i option ; do
   case ${option} in
     E) EXP="${OPTARG}"
        ;;
     I) ICON="${OPTARG}"
        ;;
     G) GRID="${OPTARG}"
        ;;
     T) TESTCASE="${OPTARG}"
        ;;
     i) iflag="-i"
        ;;
   esac
 done
 shift $((${OPTIND} - 1))


# add test case suffix
 EXP="${EXP}_${TESTCASE}"

# file with pre-processed interpolation weights
 WEIGHTS="icon${ICON}_2_${GRID}.nc"

# time step to extract
 TIMESTEP=${1:-"2"}
 TTIME=$((${TIMESTEP}-1))

#
# extract the tracer fields
#
 cdo -f nc selname,Q1,Q2  ${EXP}.nc        ${EXP}_Q1_Q2.nc

# extract initial fields
 if [[ -n ${iflag} ]] ; then

  # extract initial values of horizontal wind components
   cdo -f nc selname,U,V    ${EXP}.nc        ${EXP}_U_V.nc
   cdo -f nc seltimestep,1  ${EXP}_U_V.nc    ${EXP}_U_V_t0.nc

  # extract initial values of the tracers
   cdo -f nc seltimestep,1  ${EXP}_Q1_Q2.nc  ${EXP}_Q1_Q2_t0.nc

 fi

#
# extract values of the tracers at specified timestep
#
 cdo -f nc seltimestep,${TIMESTEP}  ${EXP}_Q1_Q2.nc  ${EXP}_Q1_Q2_t${TTIME}.nc

#
# interpolate to target regular grid
#

# generate interpolation weights
 if [[ ! -f ${WEIGHTS} && -f ../${WEIGHTS} ]] ; then
   WEIGHTS="../${WEIGHTS}"
 fi
 if [[ ! -f ${WEIGHTS} ]] ; then
   cdo -f nc gencon,${GRID}  ${EXP}_Q1_Q2_t${TTIME}.nc  ${WEIGHTS}
 fi

# extract initial fields
 if [[ -n ${iflag} ]] ; then

  # initial values of horizontal wind components
   cdo -f nc remap,${GRID},${WEIGHTS}  ${EXP}_U_V_t0.nc    ${EXP}_U_V_t0_${GRID}.nc
  # initial values of the tracers
   cdo -f nc remap,${GRID},${WEIGHTS}  ${EXP}_Q1_Q2_t0.nc  ${EXP}_Q1_Q2_t0_${GRID}.nc

 fi

#
# values of the tracers at specified timestep
#
 cdo -f nc remap,${GRID},${WEIGHTS}  ${EXP}_Q1_Q2_t${TTIME}.nc  ${EXP}_Q1_Q2_t${TTIME}_${GRID}.nc

 exit
