#!/bin/sh

# 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 values
  name_d="Q1"
  timestep_d="4"
  level_d="20"

# init values
  name="-"
  timestep="-"
  level="-"

# command options
 while getopts hdn:t:l:o option ; do
   case ${option} in
     h) echo "usage:"
        echo "cdo_ntl [-d] [-n name] [-t timestep] [-l level] [-o] file"
        echo "  Options:"
        echo "  -d:          produce default output"
        echo "               (name=${name_d}, timestep=${timestep_d}, level=${level_d})"
        echo "  -n name:     produce output         with cdo selname,name"
        echo "  -t timestep: produce output         with cdo seltimestep,timestep"
        echo "  -l level:    produce output         with cdo sellevel,level"
        echo "  -o:          produce output for GMT with cdo outputbounds"
        exit
        ;;
     d) name=${name_d}
        timestep=${timestep_d}
        level=${level_d}
        ;;
     n) name=${OPTARG}
        ;;
     t) timestep=${OPTARG}
        ;;
     l) level=${OPTARG}
        ;;
     o) oflag="-o"
        ;;
   esac
 done
 shift $((${OPTIND} - 1))

 file=${1}

 base=${file%.*}
 suff=${file##*.}

 outnc=${base}
 cdo_cmd=""

 if [[ ${name} != "-" ]] ; then
   outnc="${outnc}_${name}"
   cdo_cmd="selname,${name} "
 fi

 if [[ ${timestep} != "-" ]] ; then
   time=`expr $timestep - 1`
   outnc="${outnc}_T${time}"
   if [[ -n ${cdo_cmd} ]] ; then
     cdo_cmd="${cdo_cmd}-"
   fi
   cdo_cmd="${cdo_cmd}seltimestep,${timestep} "
 fi

 if [[ ${level} != "-" ]] ; then
   outnc="${outnc}_L${level}"
   if [[ -n ${cdo_cmd} ]] ; then
     cdo_cmd="${cdo_cmd}-"
   fi
   cdo_cmd="${cdo_cmd}sellevel,${level} "
 fi

 outnc=${outnc}.${suff}

 if [[ -z ${cdo_cmd} ]] ; then
   echo "  !!! ERROR: specify at least one of the following options: -n name, -t timestep or -l level !!!"
   echo "             (see help with option -h.)"
   exit
 else
   echo
   echo "  EXEC: cdo -f nc ${cdo_cmd} ${file} ${outnc} ..."
   echo
 fi

# process file with cdo
 cdo -f nc ${cdo_cmd} ${file} ${outnc}

# produce output for GMT
 if [[ -n ${oflag} ]] ; then

   outgmt=${outnc%.${suff}}.gmt

   # process file with cdo
   cdo outputbounds ${outnc} > ${outgmt}

 fi

# print some information
 echo
 echo "  NetCDF-Output: ${outnc}"
 if [[ -n ${oflag} ]] ; then
   echo "  GMT-Output:    ${outgmt}"
 fi
 echo
