#!/bin/bash
###############################################################################
#                           EXTRACTLATLON_BICUBINTP                           #
###############################################################################
#
# written 2016 by R. Dill
# GFZ, Potsdam, Germany
#
# update 05/2016
# can now handle also subdaily time steps of NTAL and NTOL
# new option -m: detect station locations along the coastline, given in maskfile
#                * bicubic interpolation apart from the coastline
#                * nearest gridpoint at the coastline to avoid interpolation
#                  with IB corrected values
#                * bicubic interpolation, if location is in ocean
# extraction of units corrected
#
# update 11/2017
# read single station position (latitude longitude) from command line corrected
# undocumented option -p now documented: as preprocessing the nc-files is a very time consuming step, option -p keeps the preprocessed files in the temporary
# directory. Next call of the script with option -p can reuse this preprocessed files for faster processing.
#
# update 03/2018
# using CDO capability to process global fields at once, the extraction procdure is changed to speed up processing. 
#
# update 09/2018
# using ncks --trd for NCO version 4.7.0 or newer to format output correctly
# corrected error (error in applied interpolation scheme since update 03/2018) 
#
# update 02/2019
# redefined 4 gridcells around station location when using option -m
#
# update 07/2021
# when using the direct specification of the station coordinate in the commandline (no option - s), latitudes > 180 and
# reverse order (longitude-latitude, option -c lonlat) is now possible
#
# Description:
# extract local time series (e.g. at a single station with longitude latitude) from multiple netCDF files
# for specific netCDF variables. This script needs the CDO (Climate Data Operator) library for bicubic
# interpolation and the NCO library for reading the netCDF files.
#
# Usage: to extract single station time series
#          >bash extractlatlon_bicubintp [-f 'infilename'] [-p] [-m maskfilename] latitude longitude [-v [time] variable1 [variable2 ...]] [-o outfilename]
#
#          arguments:
#             latitude        latitude of station [degree]
#             longitude       longitude of station [degree]
#
#        to extract multi station time series, saved as single files for each station
#          >bash extractlatlon_bicubintp [-f 'infilename'] [-p] [-m maskfilename] -s stationlistname [-c columnorder] [-v [time] variable1 [variable2 ...]] [-o outfilename]
#        
#          options:
#           -f 'infilename'       specify netCDF inputfiles, use wildcards for multiple files (put filename in single quotes)
#                                 without -f all netCDF files in the local directory are used 
#           -p                    keep and reuse temporary preprocessed files (separated files for each variable) -> faster 
#           -m maskfilename       land/ocean maskfile to prevent interpolation over the coastline (0=land/1=ocean)
#           -s stationlistname    filename of station coordinate list (no header, 2 or 3 columns: [stationname/id] longitude latitude)
#           -c columnorder        "latlon" or "lonlat", columnorder in stationlistname file (default=latlon)
#                                 "xyz" for cartesian coordinates [stationname/id] X Y Z
#           -v list of vars       specify variables from netCDF files (default: time, duV, duNS, duEW)
#                                 use "time" as 1st variable to extract and write the time column information
#                                 variable1, ...  extract time series only for variable1, [variable2, ...]
#           -o outfilename        specify path and file names for output(->outfilename.stationID.txt). Existing files will be overwritten, a not
#                                 existing path will be created
#
###############################################################################
#                   please adjust the user settings                           #
###############################################################################

# NCO library path ------------------------------------------------------------
# need commands ncks, ncap2
ncopath=''
#ncopath='/dsk/igsoftlocal/nco-4.0.6-1.1/bin/'
# CDO library path ------------------------------------------------------------
# need command cdo 
# if cdo is not available, the script uses ncap2 for bilinear interpolation
# instead of bicubic interpolation (for long station list CDO is much faster)
cdopath=''
#cdopath='/dsk/igsoftlocal/cdo-1.7.2/bin/'

# define temporal file names --------------------------------------------------
tmpdir="tmp"
tmpinfile="$tmpdir/extractlatlon.input"
interpolation="$tmpdir/extractlatlon.interp"
stationgrid="$tmpdir/extractlatlon.station.grid"
var_station_nc="$tmpdir/extractlatlon.station.nc"
var_station_txt="$tmpdir/extractlatlon.station.txt"
var_time_txt="$tmpdir/extractlatlon.time.txt"
var_header_txt="$tmpdir/extractlatlon.header.txt"

###############################################################################
#                             end of user settings                            #
###############################################################################

# check NCO library ###########################################################
ncks=`command -v ${ncopath}ncks`
if [[ ${ncks} == '' ]]
then
   echo "WARNING: Cannot find ${ncopath}ncks."
   echo "         -> Please define correct library path"
   exit
fi
# since NCO 4.7.0 ncks print output in CDL format, --trd changes to traditional format
ncksversion=`${ncks} --version 2>&1 |  awk '( NR==2 ) {print $3}' | sed -e 's/\.//g'`
if [ ${ncksversion} -gt 470 ]
then
   ncks="${ncks} --trd"
fi   
# check CDO library ###########################################################
cdo=`command -v ${cdopath}cdo`
if [[ ${cdo} == '' ]]
then
   echo "WARNING: Cannot find ${cdopath}cdo for fast bicubic interpolation !!!!!!!"
   echo "         -> Continue with simple bilinear interpolation (ncap2)"
   ncap2=`command -v ${ncopath}ncap2`
   if [[ ${ncap2} == '' ]]
   then
      echo "WARNING: Cannot find ${ncap2}."
      echo "         -> Please define library path"
      exit
   fi
fi

# Command line arguments ######################################################

# provide help information
if [ $# -eq 0 ] || [ X$1 == "X-h" ] 
then
  echo "Usage:"
  echo ">extractlatlon_bicubintp [-f 'infilename'] [-p] [-m maskfilename] latitude longitude [-v [time] variable1 [variable2 ...]] [-o outfilename]"
  echo "       with arguments"
  echo "             latitude        latitude of station [degree]"
  echo "             longitude       longitude of station [degree]"
  echo "or"
  echo ">extractlatlon_bicubintp [-f 'infilename'] [-p] [-m maskfilename] -s stationlistname [-c columnorder] [-v [time] variable1 [variable2 ...]] [-o outfilename]"
  echo " "
  echo "   options:"
  echo "      -f 'infilename'     specify netCDF inputfiles"
  echo "                          use wildcards for multiple files"
  echo "                          (put filename in single quotes using wildcards)"
  echo "                          without -f all *.nc files are used" 
  echo "     -p                   keep and reuse temporary preprocessed files"
  echo "                          (separated files for each variable) for faster processing"
  echo "     -m l/o maskfilename  maskfile to prevent interpolation over the coastline"
  echo "                          0=land / 1=ocean"
  echo "     -s stationlistname   filename of station coordinate list"
  echo "                          no header, 2 or 3 columns:"
  echo "                          [stationname/id] longitude latitude"
  echo "     -c columnorder       <latlon> or <lonlat>, columnorder in"
  echo "                          stationlistname file (default=latlon)"
  echo "                          <xyz> for cartesian coordinates X Y Z"
  echo "     -v list of vars      specify variables from netCDF files"
  echo "                          (default: time, duV, duN, duEW)"
  echo "                          use <time> as 1st variable to extract"
  echo "                          and write the time column information"
  echo "                          variable1, ...  extract time series"
  echo "                          only for variable1, [variable2, ...]"
  echo "       -o outfilename       specify path and file names for output. Non existing path will be created"
  echo "                          -> outfilename.stationID.txt"
  echo "                          default is >extractlatlon<."
  echo " "
  exit
fi

# default arguments
infile='*.nc'
corder='latlon'
stationfile=''
maskfile=''
outname='extractlatlon'
prep='no'
declare -a vars=('time' 'duV' 'duNS' 'duEW')

# read command line arguments
while [ $# -ne 0 ]
do
   case $1 in
      -f) shift
          if [[ ! $1 == -* ]] && [[ ! $1 == "" ]]
          then
             infile=$1
             shift
          else   
             echo "argument of option -f is missing"
             exit
          fi
      ;;
      -m) shift
          if [[ ! $1 == -* ]] && [[ ! $1 == "" ]]
          then
             maskfile=$1
             shift
          else   
             echo "argument of option -m is missing"
             exit
          fi
      ;;
      -s) shift
          if [[ ! $1 == -* ]] && [[ ! $1 == "" ]]
          then
             stationfile=$1
             shift
          else  
             echo "argument of option -s is missing"
             exit
          fi
      ;;
      -c) shift
          if [[ ! $1 == -* ]] && [[ ! $1 == "" ]]
          then
             corder=$1
             shift   
          else
             echo "argument of option -c is missing"
             exit
          fi
      ;;
      -v) shift
          if [[ ! $1 == -* ]] && [[ ! $1 == "" ]]
          then
             vars=("$1")
             shift
             nv=0
             while [ $# -ne $nv ]
             do
                if [[ ! $1 == -* ]] && [[ ! $1 == "" ]]
                then
                   vars=("${vars[@]}" "$1")
                   shift
                else   
                   nv=$#
                fi   
             done
          else
             echo "argument of option -v is missing"
             exit
          fi
      ;;
      -o) shift
          if [[ ! $1 == -* ]] && [[ ! $1 == "" ]]
          then
             outname=$1
             shift
          else  
             echo "argument of option -o is missing"
             exit
          fi
      ;;
      -p) shift
          if [[ ! $1 == -* ]] && [[ ! $1 == "" ]]
          then
             echo "skip useless argument <$1> of -p"
             shift
          fi
          prep='yes'
      ;;
      *) if [ `echo $1 | awk '{print $1+0==0}'` == 1 ] 
         then
            if [[ $1 == -* ]] && [[ ! $1 == "" ]]
            then
               echo "option $1 not valid"
            else   
               echo "latitude $1 not a number"
            fi   
            exit
         else         
            lat=$1
            shift 
            if [ `echo $1 | awk '{print $1+0==0}'` == 1 ] 
            then
               if [[ $1 == -* ]] && [[ ! $1 == "" ]]
               then
                  echo "longitude is missing"
               else  
                  echo "longitude $1 not a number"
               fi   
               exit
            else   
               lon=$1
               shift 
               station="1"
               stationfile="no"            
            fi
         fi   
      ;;   
   esac
done

# check arguments (Stationfile or Station coordinates ?)
if [[ $stationfile == "" ]] 
then
   echo "Station coordinates missing - job aborted"
   exit
fi   
if [ ! -r $stationfile ] && [ ! $stationfile == "no" ]
then
   echo "Cannot read $stationfile - job aborted"
   exit
fi   

# check arguments (Input files readable ?, expand wildcards)
fid=0
for file in ${infile}
do
   if [ ! -r $file ]
   then
      echo "Cannot read $file - job aborted"
      exit
   fi
   # expand wildcards to file list
   files=("${files[@]}" "$file")
   # create temporary file names (used for separation of variables )
   fid=$((fid+1))
   tmpfiles=("${tmpfiles[@]}" "$tmpinfile.$fid")
done     
echo "... found ${#files[@]} input files"

# check arguments (Maskfile readable ?)
if [ ! ${maskfile} == "" ]
then
   if [ ! -r $maskfile ]
   then
      echo "Cannot read $maskfile - job aborted"
      exit
   fi
fi   

# check arguments (Lat / Lon culumn order)
if [ $corder != "lonlat" ] && [ $corder != "xyz" ]
then
    corder="latlon"
fi  

# prepare parameters for XYZ -> Lat Lon ########################################
# WGS84 ellipsoidal parameters
if [ $corder == "xyz" ]
then
   axis_a="6378137.0"
   axis_b="6366752.3142"
   flat1=$(echo "($axis_a^2 - $axis_b^2) / $axis_a^2" | bc -l) 
   flat2=$(echo "($axis_a^2 - $axis_b^2) / $axis_b^2" | bc -l) 
   Pi=$(echo "4 * a(1)" | bc -l) 
   echo "... convert XYZ to Lat Lon"
fi

# output directory ############################################################
outdir=`dirname "$outname"`
outname=`basename "$outname"`
if [[ $outdir != "" ]]
then
   if [ ! -d $outdir ]
   then
      mkdir $outdir
   fi 
   outdir="${outdir}/"
fi

# temporary directory #########################################################
if [ ! -d $tmpdir ]
then
   mkdir $tmpdir
   if [[ $prep == 'yes' ]]
   then
      prep='keep'
   fi   
else
   if [[ ! $prep == 'yes' ]]
   then
      rm -rf $tmpdir/*
   fi   
fi   
       
# read station positions #######################################################
if [ ! $stationfile == "no" ]
then
   ncol=`awk '{print NF; exit}' $stationfile`
   nrow=`awk 'END{print NR; exit}' $stationfile`
   if [ $corder == "lonlat" ]
   then
      echo "... read Stationlist longitude-latitude ($ncol x $nrow)"
   elif [ $corder == "xyz" ]
   then
      echo "... read Stationlist X-Y-Z ($ncol x $nrow)"
   else   
      echo "... read Stationlist latitude-longitude ($ncol x $nrow)"
   fi
   for i in $(seq 1 $nrow)
   do
      if [ $corder != "xyz" ]
      then
         # lat lon columns ----------------- 
         if [ $ncol -gt 2 ]
         then
            col1=`awk -v i=$i 'FNR==i{print $1; exit}' $stationfile`
            col2=`awk -v i=$i 'FNR==i{print $2; exit}' $stationfile`
            col3=`awk -v i=$i 'FNR==i{print $3; exit}' $stationfile`
         else 
            col1="$i"
            col2=`awk -v i=$i 'FNR==i{print $1; exit}' $stationfile`
            col3=`awk -v i=$i 'FNR==i{print $2; exit}' $stationfile`
         fi
      else
         # X Y Z columns ----------------- 
         if [ $ncol -gt 3 ]
         then
            col1=`awk -v i=$i 'FNR==i{print $1; exit}' $stationfile`
            xxx=`awk -v i=$i 'FNR==i{print $2; exit}' $stationfile`
            yyy=`awk -v i=$i 'FNR==i{print $3; exit}' $stationfile`
            zzz=`awk -v i=$i 'FNR==i{print $4; exit}' $stationfile`
         else 
            col1="$i"
            xxx=`awk -v i=$i 'FNR==i{print $1; exit}' $stationfile`
            yyy=`awk -v i=$i 'FNR==i{print $2; exit}' $stationfile`
            zzz=`awk -v i=$i 'FNR==i{print $3; exit}' $stationfile`
         fi
         # convert X Y Z into Lat Lon ----
         P=$(echo "sqrt( $xxx^2 + $yyy^2 )" | bc -l) 
         G=$(echo "a( $zzz / $P * $axis_a / $axis_b )" | bc -l) 
         Y1=$(echo "$zzz + $flat2 * $axis_b * (s( $G ))^3" | bc -l) 
         X1=$(echo "$P - $flat1 * $axis_a * (c( $G ))^3" | bc -l) 
         sign=$(echo "$X1 > 0.0" | bc -l) 
         if [ $sign == 1 ]
         then
            col2=$(echo "a( $Y1 / $X1 ) * 180.0 / $Pi" | bc -l) 
         else
            sign=$(echo "$>1 < 0.0" | bc -l) 
            if [ $sign == 1 ]
            then
               col2=$(echo "a( $Y1 / $X1 ) * 180 / $Pi - 180.0" | bc -l) 
            else
               col2=$(echo "a( $Y1 / $X1 ) * 180 / $Pi + 180.0" | bc -l) 
            fi
         fi
         sign=$(echo "$xxx > 0.0" | bc -l) 
         if [ $sign == 1 ]
         then
            col3=$(echo "a( $yyy / $xxx ) * 180 / $Pi" | bc -l)
         else
            sign=$(echo "$yyy < 0.0" | bc -l) 
            if [ $sign == 1 ]
            then
               col3=$(echo "a( $yyy / $xxx ) * 180 / $Pi - 180.0" | bc -l)
            else
               col3=$(echo "a( $yyy / $xxx ) * 180 / $Pi + 180.0" | bc -l)
            fi
         fi
      fi 
     
      # add station coordinates to station list ----------------------------------------
      if [[ ! $col2 == "" ]] && [[ ! $col3 == "" ]]
      then
         # check column order 
         if [ $corder == "lonlat" ]
         then
            dummy=$col2
            col2=$col3
            col3=$dummy
         fi  
         # check for longitude format (subtract 360 when lon>180)
         biglon=$(echo "${col3} > 180.0" | bc -l) 
         if [ $biglon == 1 ]
         then 
            col3=$(echo "${col3} - 360.0" | bc -l) 
         fi
         # check for latitude (should be -90 -> +90)
         biglat=$(echo "sqrt(${col2}*${col2}) > 90.0" | bc -l)   
         if [ $biglat == 1 ]
         then  
            echo "latitude out of bounds (-90 < lat < 90) - job aborted"
            echo "(maybe latitude / longitudes are switched, try option -c lonlat)"
            exit
         fi
         # append to station list
         if [ $i -eq 1 ]
         then 
            station=$col1
            lat=$col2
            lon=$col3
         else
            station=("${station[@]}" "$col1")
            lat=("${lat[@]}" "$col2")
            lon=("${lon[@]}" "$col3")
         fi
      fi
   done
else
   # check column order 
   if [ $corder == "lonlat" ]
   then
      dummy=$lon
      lon=$lat
      lat=$dummy
   fi  
   # check for longitude format (subtract 360 when lon>180)
   biglon=$(echo "${lon} > 180.0" | bc -l) 
   if [ $biglon == 1 ]
   then 
      lon=$(echo "${lon} - 360.0" | bc -l) 
   fi
   # check for latitude (should be -90 -> +90)
   biglat=$(echo "sqrt(${lat}*${lat}) > 90.0" | bc -l)   
   if [ $biglat == 1 ]
   then  
      echo "latitude out of bounds (-90 < lat < 90) - job aborted"
      echo "(maybe latitude / longitudes are switched, try option -c lonlat)"
      exit
   fi
fi   
if [ ${#station[@]} -lt 1 ]
then
   echo "... cannot read station file - job terminated"
   exit
fi

# extract time information ####################################################
if [ ${vars[0]} == "time" ]
then
   echo "... read variable <time>"
   if [[ $prep == "yes" ]]
      then
      if [[ -r $var_time_txt ]]
      then
         echo "    -> use preprocessed file $var_time_txt"
      else
         echo "    -> no preprocessed file $var_time_txt"
         prep='keep'
      fi   
   fi   
   if [[ ! $prep == "yes" ]]
   then
      # generate new timeline for ASCII output --------------------------------
      rm -f $var_time_txt
      touch $var_time_txt
      # loop over all input files ---------------------------------------------
      for file in ${files[@]}
      do
         # extract time information from file
		 dt=`${ncks} -H -d time,1 -v time $file | cut -b 9-`                                                                 # 1 or 0.125
		 basedate=`${ncks} -M -m $file | grep -E -i '^time attribute [0-9]+: units' | cut -f 13 -d ' '`                      # 2000-01-01
         basetime=`${ncks} -M -m $file | grep -E -i '^time attribute [0-9]+: units' | cut -f 14 -d ' ' | cut -f 1 -d ':'`    # 12 [daily] or 00 [3-hourly]
         if [ `${ncks} -M -m $file | grep -E -i '^time attribute [0-9]+: units' | grep -c 'days'` == 0 ]
         then
            if [ `${ncks} -M -m $file | grep -E -i '^time attribute [0-9]+: units' | grep -c 'hours'` == 1 ]
            then
               dt=$(LC_NUMERIC="en_US.UTF-8" printf '%.3f' "$(echo "scale=3; ${dt} / 24" | bc -l)")                          # hours -> days
			else
               echo "... cannot read time unit from:"
               ${ncks} -M -m $file | grep -E -i '^time attribute [0-9]+: units'
               exit
            fi
		 fi
	     nt=`${ncks} -M -m $file | grep -E -i '^time dimension [0-9]+: time'  | cut -f 7 -d ' '`          # 366 / 2928
         echo "       $basedate, hour=$basetime, dt=$dt day, n=$nt -> $var_time_txt"
         # create and append time information from file to timeline 
         for t in $(seq 1 $nt)
         do
            th=$(echo "(${t}-1) * 24 * ${dt} " | bc -l)
            th=$(LC_NUMERIC="en_US.UTF-8" printf "%.0f" ${th})
            echo `date -u -d "$basedate + $th hours + $basetime hours" +%Y-%m-%d%t%R` >> $var_time_txt
         done
      done
   fi   
   # create header lines with time column
      header1=" time                               "
      header2="[days]                              "
else
   # header lines without time column
   header1="             "
   header2="             "
fi

# check variable / extract unit information ###################################
for var in ${vars[@]}
do
   if [[ ! $var == "time" ]]
   then      
      echo "... read variable <$var>" 
      
      fid=0
      for file in ${files[@]}
      do
         # check, if variable exists in netCDF input file and skip variable time
         if [[ `${ncks} -M -m $file | grep -E -i -o '^'"$var"':'` == "" ]] 
         then
            echo "Cannot find variable <$var> in netCDF input file $file - job aborted"
            exit
         fi 
         if [[ $file == ${files[0]} ]]
         then
            # extract unit information
            unit="`${ncks} -M -m $file | grep -E -i '^'"$var"' attribute [0-9]+: units' | cut -f11- -d ' '`"
            if [[ $unit == "" ]]
            then
               unit="`${ncks} -M -m $file | grep -E -i '^'"$var"' attribute [0-9]+: long_name' | sed 's/.*\[//g' | sed 's/\]//g'`"
            fi
            echo "       unit=$unit" 
            # extend header 
            header1=" $header1 $var          "
            header2=" $header2 [$unit]           "
         fi
         # write variables into seperate files for faster extraction of station time series
         fid=$((fid+1))
         if [[ $prep == "yes" ]]
         then
            if [[ -r ${tmpinfile}.${fid}.${var} ]]
            then
               echo "    -> use preprocessed file ${tmpinfile}.${fid}.${var}"
            else
               echo "    -> no preprocessed file ${tmpinfile}.${fid}.${var}"
               prep='keep'
            fi   
         fi   
         if [[ ! $prep == "yes" ]]
         then
            if [[ ${cdo} == "" ]]
            then
               echo "       ${file} -> ${tmpinfile}.${fid}.${var}"
               ${ncks} -O -v ${var} ${file} ${tmpinfile}.${fid}.${var}
            else
               if [[ ${#vars[@]} -gt 2 ]]
               then
                  echo "       split ${file} -> ${tmpinfile}.${fid}.${var}"
                  # CDO_FILE_SUFFIX is set to NULL -> ${tmpfile}.${fid}.${var}
                  export CDO_FILE_SUFFIX="NULL"
                  ${cdo} -s splitname ${file} ${tmpinfile}.${fid}.
                  prep='yes'
               else
                  ${cdo} -s selname,${var} ${file} ${tmpinfile}.${fid}.${var}
               fi
            fi
         fi   
      done   
   fi 
done

###############################################################################
# in case CDO is available 
# -> interpolate global gridded fields to station positions at once (faster)
#    and extract station timeseries from remapped grid
#    - nearest neighbour interpolation for stations alomg coastline
#    - bicubic interpolation for all other stations
if [[ ! ${cdo} == "" ]]
then
   echo "... interpolation to station positions"
   # generate station position gridfile for CDO 
   istation=0
   inewline=0
   newline=$'\n            '
   while [ $istation -lt ${#station[@]} ]
   do
      if [ ${istation} -eq 0 ]
      then
         lonvals=" ${lon[$istation]}"
         latvals=" ${lat[$istation]}"
      else
         if [ ${inewline} -gt 4 ]
         then
            lonvals="${lonvals}${newline}"
            latvals="${latvals}${newline}"
            inewline=0
         fi   
         lonvals="${lonvals} ${lon[$istation]}"
         latvals="${latvals} ${lat[$istation]}"
      fi
      istation=$((istation+1))
      inewline=$((inewline+1))
   done
   cat >${stationgrid} <<EOF
gridtype  = unstructured   
gridsize  = ${#station[@]}
xvals     = ${lonvals}
yvals     = ${latvals}
EOF

   # generate interpolation weights from 1st netCDF file
   echo "    -> generate bicubic interpolation weights"
   ${cdo} -s genbic,${stationgrid} ${files[0]} ${interpolation}.bic >/dev/null
   if [ ! -r ${interpolation}.bic ]
   then
      echo "Cannot create CDO interpolation weights - job aborted"
      exit
   fi
   echo "    -> generate nearest-neighbour interpolation weights"
   ${cdo} -s gennn,${stationgrid} ${files[0]} ${interpolation}.nn >/dev/null
   if [ ! -r ${interpolation}.nn ]
   then
      echo "Cannot create CDO interpolation weights - job aborted"
      exit
   fi
   # interpolate regular gridded fields to station grid
   # loop over all variables
   echo "    -> bicubic and nearest-neighbour interpolation:"
   for file in ${tmpfiles[@]}
   do
      for var in ${vars[@]}
      do
         if [ ! $var == "time" ]
         then
            echo "       ${file}.${var}"
            (${cdo} -s remap,${stationgrid},${interpolation}.bic ${file}.${var} ${file}.${var}.bic >/dev/null)&
            (${cdo} -s remap,${stationgrid},${interpolation}.nn ${file}.${var} ${file}.${var}.nn >/dev/null)&
            wait
         fi
      done
   done  
   rm -f ${interpolation}.bic
   rm -f ${interpolation}.nn
else
   echo "... use bilinear interpolation to station positions (no CDO available)"
fi

###############################################################################
# loop over station coordinates ###############################################
istation=0
while [ $istation -lt ${#station[@]} ]
do
   latout="${lat[$istation]}"
   lonout="${lon[$istation]}"
   
   if [ ${#station} -gt 1 ]
   then
      echo "... extract time series for station ${station[$istation]}  lat:$latout / lon:$lonout  ($((istation+1))/${#station[@]})"
      outfile="${outdir}${outname}.${station[$istation]}.txt"
   else
      echo "... extract time series for station lat:$latout / lon:$lonout"
      outfile="${outdir}${outname}.txt"
   fi
   
   # touch new temporary output file ------------------------------------------
   touch $outfile
   rm -f $outfile
   touch $outfile
   
   # prevent interpolation over the coastline ----------------------------------------------
   # check 4 gridcells around station position in maskfile                   |      |      |
   interp=3 # (0=nearest(NCKS), 1=bilin(NCO), 2=nearest(CDO), 3=bicub(CDO))  |  g1  |  g2  |     
   if [[ ! ${maskfile} == "" ]]                                         #    |      |      |        
   then                                                                 #    ---------------
      lon1=$(echo "${lonout} - 0.25 " | bc -l)                          #    |      |s     |
      lon2=$(echo "${lonout} + 0.25 " | bc -l)                          #    |  g3  |  g4  |
      lat1=$(echo "${latout} - 0.25 " | bc -l)                          #    |      |      |
      lat2=$(echo "${latout} + 0.25 " | bc -l)                          #    ---------------
      # if dimensions in netCDF are lat/lon
      gs=$(${ncks} -Q --no_nm_prn -H -d lon,${lonout},${lonout} -d lat,${latout},${latout} ${maskfile} | grep '^[0|1]$')
      g1=$(${ncks} -Q --no_nm_prn -H -d lon,${lon1},${lon1} -d lat,${lat2},${lat2} ${maskfile} | grep '^[0|1]$')
      g2=$(${ncks} -Q --no_nm_prn -H -d lon,${lon2},${lon2} -d lat,${lat2},${lat2} ${maskfile} | grep '^[0|1]$')
      g3=$(${ncks} -Q --no_nm_prn -H -d lon,${lon1},${lon1} -d lat,${lat1},${lat1} ${maskfile} | grep '^[0|1]$')
      g4=$(${ncks} -Q --no_nm_prn -H -d lon,${lon2},${lon2} -d lat,${lat1},${lat1} ${maskfile} | grep '^[0|1]$')
      # if dimensions in netCDF are latitude/longitude
      if [[ $gs == "" ]] || [[ $g1 == "" ]]
      then 
         gs=$(${ncks} -Q --no_nm_prn -H -d longitude,${lonout},${lonout} -d latitude,${latout},${latout} ${maskfile} | grep '^[0|1]$')
         g1=$(${ncks} -Q --no_nm_prn -H -d longitude,${lon1},${lon1} -d latitude,${lat2},${lat2} ${maskfile} | grep '^[0|1]$')
         g2=$(${ncks} -Q --no_nm_prn -H -d longitude,${lon2},${lon2} -d latitude,${lat2},${lat2} ${maskfile} | grep '^[0|1]$')
         g3=$(${ncks} -Q --no_nm_prn -H -d longitude,${lon1},${lon1} -d latitude,${lat1},${lat1} ${maskfile} | grep '^[0|1]$')
         g4=$(${ncks} -Q --no_nm_prn -H -d longitude,${lon2},${lon2} -d latitude,${lat1},${lat1} ${maskfile} | grep '^[0|1]$')
      fi
      if [[ $gs == "" ]] || [[ $g1 == "" ]]
      then 
         echo "Cannot read dimensions in maskfile $maskfile - job aborted"
         exit 
      fi       
      # station has land and ocean gridcells around
      if [ $gs -ne $g1  ] || [ $gs -ne $g2 ] || [ $gs -ne $g3 ] || [ $gs -ne $g4 ]
      then
         if [ $gs == "1" ]
         then
            echo "    -> detected station location in the ocean (1=ocean) !!!"
         else   
            echo "    -> detected station at the coastline (1=ocean)" 
         fi   
         echo "                  $g1  $g2"
         echo "                  $g3  $g4"  
         if [ $gs == "0" ]
         then
            interp=2
            echo "       use nearest gridpoint (avoid interpolation over coastline)"
         fi
      fi
   fi   
   
   if [[ ${cdo} == "" ]]
   then
      interp=$interp-2
   fi
   
   # loop over all variables ##################################################
   for var in ${vars[@]}
   do

      if [ $var == "time" ]
      then
         # paste optional timeline to output file -----------------------------
         mv -f $outfile ${outfile}.old
         paste $var_time_txt ${outfile}.old > $outfile
      else   
         
         echo "    -> extract $var"
         rm -f ${var_station_txt}
         touch ${var_station_txt}
         
         if [ $interp == 1 ]
         then
            # generate NCO script for bilinear time series extraction -> output-variable is <var>
            echo 'var[$time]=0.0; *nt=$time.size; *it=0;'                                                     >| ${interpolation}.nco
            echo "while(it<nt){var(it)=bilinear_interp_wrap($var(it,:,:),0.0,$latout,$lonout,lat,lon);it++;}" >> ${interpolation}.nco
         fi
         
         # loop over all input files ------------------------------------------
         for file in ${tmpfiles[@]}
         do
            case $interp in
               0) # no interpolation (extract nearest-neighbour with NCKS):
                  # netCDF -> ASCII
                  ${ncks} -O -s "%+15.11f\n" -H -C -v ${var} -d lon,$lonout,$lonout -d lat,$latout,$latout ${file}.${var} | awk 'NF' >> ${var_station_txt}
                  ;;
               1) # bilinear interpolation with NCO -> invoke NCO script:
                  ${ncap2} -v -O -S $interpolation.nco ${file}.${var} ${var_station_nc}
                  # netCDF -> ASCII
                  ${ncks} -O -s "%+15.11f\n" -H -C -v var ${var_station_nc} | awk 'NF' >> ${var_station_txt}
                  ;;
               2) # extract from CDO nearest-neighbour interpolated station grid
                  # netCDF -> ASCII
                  ${ncks} -O -s "%+15.11f\n" -H -C -v ${var} -d ncells,$((istation)),$((istation)) ${file}.${var}.nn | awk 'NF' >> ${var_station_txt}
                  ;;  
               3) # extract from CDO bicubic interpolated station grid
                  # netCDF -> ASCII
                  ${ncks} -O -s "%+15.11f\n" -H -C -v ${var} -d ncells,$((istation)),$((istation)) ${file}.${var}.bic | awk 'NF' >> ${var_station_txt}
                  ;;    
            esac
         done   
  
         # paste variable time series to output file ---------------------------
         mv -f $outfile $outfile.old
         paste $outfile.old $var_station_txt > $outfile
      
         # remove temporary variable files
         rm -f $outfile.old
         rm -f $var_station_nc
         rm -f $var_station_txt
         if [ $interp == 1 ]
         then
            rm -f $interpolation.nco
         fi   
      fi   
      
   done
   # end loop over all variables #############################################

   # add header --------------------------------------------------------------
   echo "Station: ${station[$istation]}   (lat: ${lat[$istation]} / lon: ${lon[$istation]})" > $var_header_txt
   echo " " >> $var_header_txt
   echo "$header1" >> $var_header_txt
   echo "$header2" >> $var_header_txt
   mv -f $outfile $outfile.old
   cat $var_header_txt $outfile.old > $outfile
   rm -f $outfile.old
   
   # remove temporary station files
   rm -f $var_header_txt
   
   istation=$((istation+1))
done
# end loop over all stations ##################################################
###############################################################################


if [[ $prep == "yes" || $prep == "keep" ]]
then 
   echo "    -> keep preprocessed files $tmpdir/${tmpinfile}.*"
fi   

# remove temporary global files
if [ ! $prep == "yes" ] && [ ! $prep == "keep" ]
then
   rm -f $var_time_txt
   rm -f $tmpinfile.*
   rm -rf $tmpdir
fi   


exit
