#/bin/bash

site=daint


function plot_ts {

   infile=${1}
   outfile=${2}

   var=$(cdo showvar ${infile} | sed -e "s/^ *//")

   cat << __EOF__ | sed -e "s/^ *//" > plot.py
   
      import xarray as xr
      import numpy as np
      import matplotlib.pyplot as plt

      ds=xr.open_dataset('${infile}')
       
      #-- create figure and axes instances
      dpi = 100
      fig = plt.figure(figsize=(1100/dpi, 1100/dpi), dpi=dpi)
      ax  = fig.add_axes([0.1,0.1,0.8,0.9])
      ax.tick_params(axis='both', which='major', labelsize=24)

      ax.xaxis.label.set_size(24)
      ax.yaxis.label.set_size(24)

      ds.${var}.isel(lon=0,lat=0).plot()
       
      plt.savefig('${outfile}', bbox_inches='tight', dpi=dpi)
__EOF__

python3 plot.py

}


function plot_2d {  
   
   infile=${1}
   outfile=${2}

   var=$(cdo showvar ${infile} | sed -e "s/^ *//")

   case ${var} in
      totprec)
                clevs=',levels=[0,.25,.5,.75,1,1.25,1.5,1.75,2,2.25,2.5,3,3.5,4,4.5,5,15]'
                colour=",cmap=plt.cm.terrain_r,extend='max'"
                ;;
      temp2|tsurf)
                clevs=",levels=np.arange(-40,30,5)"
                colour=",cmap=plt.cm.jet,extend='both'"
                ;;
      wind10)
                clevs=",levels=np.arange(0,15,1.5)"
                colour=",cmap=plt.cm.jet,extend='both'"
                ;;
      *)
                clevs=""
                colour=""
                ;;
   esac



   cat << __EOF__ | sed -e "s/^ *//" > plot.py
      import xarray as xr
      import numpy as np
      import matplotlib.pyplot as plt
      import cartopy.crs as ccrs
      import cartopy.feature as cfeature
      
      #-- open netcdf file
      data = xr.open_dataset('${infile}')
      var = data.${var}
      
      #-- create figure and axes instances
      dpi = 100
      fig = plt.figure(figsize=(1100/dpi, 1100/dpi), dpi=dpi)
      ax = plt.axes(projection=ccrs.PlateCarree())
      ax.set_extent([-180, 180, -90, 90]) # setting the borders of our map
      
      #-- draw coastlines, state and country boundaries, edge of map
      ax.add_feature(cfeature.COASTLINE)
      
      #-- create and draw meridians and parallels grid lines
      gridlines = ax.gridlines(draw_labels=True)
      
      ax.text(-0.07, 0.55, 'latitude', va='bottom', ha='center',
              rotation='vertical', rotation_mode='anchor',
              transform=ax.transAxes)
      ax.text(0.5, -0.1, 'longitude', va='bottom', ha='center',
              rotation='horizontal', rotation_mode='anchor',
              transform=ax.transAxes);
      
      var.plot.contourf(ax=ax,transform=ccrs.PlateCarree()${clevs}${colour})
      
      #-- add plot title
      plt.title('${var}')
      
      #-- display on screen
      #plt.show()
      
      #-- maximize and save file
      plt.savefig('${outfile}', bbox_inches='tight', dpi=dpi)

__EOF__

# run python script

python3 plot.py

}
