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

set -e
test x${DEBUG+set} != xset || set -x

usage_exit1() {
  echo -e "generate 2d map plots with ncl" >&2
  echo -e "SYNOPSIS  plot2d_ncl [OPTIONS] FILE" >&2
  echo -e "DESCRIPTION ${n}\n\tGenerates 2d map plots from MPIOM data using ncl" >&2
  echo -e "FILE\n\t\t file to plot (required).\n" >&2
  echo -e "OPTIONS" >&2
  echo -e "\t--var , -v       \t VAR       \t\t variable name to plot (required)." >&2
  echo -e "\t--code , -c       \t CODE       \t\t code to plot (required)." >&2
  echo -e "\t--min , -x       \t MINIMUM   \t\t miniumum of colorbar (required for plot types 0,1 and 3)." >&2
  echo -e "\t--max , -y      \t MAXIMUM   \t\t maximum  of colorbar (required for plot types 0,1 and 3 )." >&2
  echo -e "\t--inc , -z       \t INCREMENT \t\t increment of colorbar (required for plot types 0,1 and 3)." >&2
  echo -e "\t--scal , -k     \t SCALE     \t\t linear scaling factor ; default is 1." >&2
  echo -e "\t--unit , -u     \t UNIT      \t\t physical unit of the data ; default is NN." >&2
  echo -e "\t--title ,-t    \t TITLE     \t\t title of the plot ; default is input file name." >&2
  echo -e "\t--cstring ,-C    \t CSTRING     \t\t center string of the plot ; default is depth." >&2
  echo -e "\t--lstring ,-L    \t LSTRING     \t\t left string of the plot ; default is depth." >&2
  echo -e "\t--rstring ,-R    \t RSTRING     \t\t right string of the plot ; default is date." >&2
  echo -e "\t--pal , -p      \t PALETTE   \t\t color palette ; default is BlueWhiteOrangeRed." >&2
  exit 1
}


CDO='cdo -s'

# Defaults
TITLE=""
UNIT=""
SCAL=1
#pal=temp_diff_18lev
#pal=BlueDarkRed18
pal=BlueWhiteOrangeRed
pal=BlueYellowRed
#pal=WhiteYellowOrangeRed

args=`getopt -u   -lvar:,code:,min:,max:,inc:,scal:,unit:,title:,cstring:,lstring:,rstring:,pal:,help  v:c:x:y:z:k:u:t:p:h "$@"` || {
  usage_exit1
}

set -- $args

while [ $1 != "--" ]
do
  case $1 in
    --help      ) usage_exit1 ;;
    --var | -v      ) VAR=$2  ;;
    --code | -c      ) CODE=$2  ;;
    --min | -x       ) MINI=$2  ;;
    --max | -y      ) MAXI=$2  ;;
    --inc | -z      ) INCR=$2  ;;
    --scal | -k     ) SCAL=$2  ;;
    --unit | -u     ) UNIT=$2   ;;
    --title | -t    ) TITLE=$2  ;;
    --cstring | -C    ) CSTRING=$2  ;;
    --lstring | -L    ) LSTRING=$2  ;;
    --rstring | -R    ) RSTRING=$2  ;;
    --pal | -p      ) pal=$2    ;;
  esac
  shift
done

shift
IFILE="$1"

OFILE=$(basename $IFILE .nc)


test x${VAR} == x && VAR=$(set +e ;  ${CDO} showvar -selcode,${CODE} $IFILE ) ; VAR=$(echo $VAR)
test x${VAR+set} != xset && $(echo $VAR "not found" ; exit )

#create .lst file

extension=pdf
filename=$(basename $IFILE .nc)
steps=$($CDO ntime $IFILE | awk '{ print $1-1 }' )
code=$($CDO vardes $IFILE | awk '{ print $1 }' )
name=$($CDO vardes $IFILE | awk '{ print $2 }' )
longname=$($CDO vardes $IFILE | awk '{ $1=$2=""; print $0 }' )
title=$TITLE
for (( n=0 ; n<=steps ; n++))
do
#echo $filename:$n:$extension:$name$n:$code:${filename%%_icon*}
echo $filename:$n:$extension:$title$n:$code:$title
done > $filename.lst_

#



echo 'FILE:  ' $IFILE
echo 'VAR:   ' $VAR
echo 'CODE:  ' $CODE
echo 'MIN:   ' $MINI
echo 'MAX:   ' $MAXI
echo 'INCR:  ' $INCR
echo 'SCALE: ' $SCAL
if [ "${UNIT}" = "" ] ; then
  UNIT=NN
fi
echo 'UNIT:  ' $UNIT
echo 'TITLE: ' $TITLE

echo 'CSTRING: ' $CSTRING
echo 'LSTRING: ' $LSTRING
echo 'RSTRING: ' $RSTRING

echo 'pal:   ' $pal







#exit

test x${DEBUG+set} != xset || set verbose



cat >plot.ncl<<EOF
;----------------------------------------------------------------------

load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/shea_util.ncl"

begin

  format = "pdf"

;---Determine paper size as orientation does not work as expected
      format@wkPaperSize = "A4"

;      format@wkPaperHeightF = 8.3
;      format@wkPaperWidthF = 11.7


;---Open workstation and change color map
  wks = gsn_open_wks(format,"$OFILE")   ; "ps", "pdf", "png"
  gsn_define_colormap(wks,"$pal")           ; optional

;---Read data
  a   = addfile("${IFILE}","r")

  x   = a->${VAR}(:, :, :, 0)
  lat_t = a->lat      ; Only necessary if "x" doesn't
  depth_t = a->depth      ; contain 1D coordinate arrays.

  printVarSummary(x)
;  print(x)
  time = a->time

  x=x*${SCAL}


;---Set some resources
  res                   = True

  res@gsnDraw = False
  res@gsnFrame= False

  res@gsnMaximize       = True     ; maximize plot in frame
  res@gsnPaperOrientation = "portrait"


;---These are sample resources you might want to set
;  res@cnFillOn          = True     ; turn on contour fill
;  res@cnLinesOn         = False    ; turn off contour lines
;  res@cnLineLabelsOn    = False    ; turn off line labels
;  res@cnInfoLabelOn        = False      ; turns off contour info label
;  res@lbOrientation        = "vertical" ; vertical label bar


  res@cnFillOn             = True                  ; turn on color fill
  res@cnLinesOn            = True
  res@cnInfoLabelOn        = False      ; turns off contour info label
  res@cnLineLabelsOn       = True      ; turns off contour line labels

  res@cnLabelMasking             = True
  res@cnLineLabelBackgroundColor = "transparent"

  res@cnLineLabelPlacementMode   = "constant"
  res@cnLineLabelInterval        = 1             ; default = 2

  res@vpWidthF            = 0.5           ; change aspect ratio of plot
  res@vpHeightF           = 0.3




;---Use if you have a high-res grid that could be slow to plot.
 res@cnFillMode        = "RasterFill"
; res@cnFillMode        = "CellFill"

;---This can also speed things up
; res@trGridType        = "TriangularMesh"

;---These two resources are not needed in V6.1.0
  res@gsnSpreadColors   = True     ; span full color map
  res@lbLabelAutoStride = True     ; nice spacing for labelbar labels
;  res@cnMissingValFillColor    = "gray30" ; set color for missing areas
  res@cnMissingValFillPattern = 0
  res@cnMissingValFillColor   = "black" ;;Color of miss values




  if ( "${TITLE}" .eq. "") then
    res@tiMainString = "${IFILE}"
  else
    res@tiMainString = "${TITLE}"
  end if


;---Uncomment if you want to change the contour levels
;  mnmxint = nice_mnmxintvl( min(x), max(x), 18, False)
  res@cnLevelSelectionMode = "ManualLevels"
  res@cnMinLevelValF       = $MINI
  res@cnMaxLevelValF       = $MAXI
  res@cnLevelSpacingF      = $INCR


  if ( "${LSTRING}" .eq. "") then

;        res@gsnLeftString =  x@long_name+" ["+ x@units+"]"
        res@gsnLeftString = "["+x@units+"]"

  else
      res@gsnLeftString = "${LSTRING}"
  end if

  if ( "${CSTRING}" .eq. "") then
     res@gsnCenterString =   x@long_name
  else
       res@gsnCenterString = "${CSTRING}"
  end if

  do timestep = 0, dimsizes(time)-1


   ; Convert to UTC time.
     utc_date = cd_calendar(time(timestep), 0)
   ; Store return information into more meaningful variables.

    year   = tointeger(utc_date(0,0))
    month  = tointeger(utc_date(0,1))
    day    = tointeger(utc_date(0,2))

    sdate = sprinti("%0.4i", year) +"-"+ sprinti("%0.2i", month) +"-"+ sprinti("%0.2i", day)

    if ( "${RSTRING}" .eq. "") then
      res@gsnRightString = sdate
    else
      res@gsnRightString = "${RSTRING}"
    end if

    res@sfXArray             = lat_t
    res@sfYArray             = depth_t

    res@gsnYAxisIrregular2Linear = True   ; converts irreg depth to linear
    res@trYReverse               = True   ; reverses y-axis

    plot = gsn_csm_contour(wks,x(timestep,:,:),res)     ; create plot

    res@gsnContourZeroLineThicknessF = 4.5

    res@cnLineThicknessF  = 2.



    draw(plot)                                            ; draw
    frame(wks)                                            ; advance frame

  end do

end


EOF

time ncl plot.ncl




#outfile=`basename ${PFILE} .ps`
#cat  ${PFILE}.[0-9]* | ps2pdf - ${IFILE##*/}.pdf
#\rm -f ${PFILE}.[0-9]* tt ${OFILE} ${OFILE}.* mist*


exit
