#!/bin/sh
# Public Domain 1/2024 Wesley Ebisuzaki
#
# Convert ostia sst and sea ice to grib2
#
# this differs from mk_ostia_nc2grb.sh
#
# mk_ostia_nc2grb.sh uses wgrib2's -import_netcdf
#      which requires wgrib2 v3.0.0+ and netcdf4 installed
#      creates more fields: MASK and TMP anlaysis errors
#
# this code uses ncdump to read the ostia netcdf4 file
# wgrib2 is then used to write the grib2 files
#
# Why?
#   WCOSS2 operational wgrib2 is only v2.0.8 (1/2024)
#   CORe version doesn't have netcdf installed
#   easier and safer to use ncdump than install netcdf4
#
# software used
#  $NCDUMP  - ncdump      read netcdf4 file
#  $WGRIB2  - wgrib2      create grib2 file
#
# input
#  ${date}0000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB-v02.0-fv02.0.nc
# output
#  sst$date.grb2     grib2 sea-surface temperature
#  sice$date.grb2    grib2 sea-ice fraction
# fixed file
#  ostia.template    grib2 file with the ostia grid
#
# ncdump is used to read file and create text
#  file with grid data, and scaling and offset parameters
# posix standard utilities are used to parse text file
#  from ncdump to get offset, scaling and grid data
# wgrib2 is used to write a grib2 file with sst and sea-ice concentration
#  using -import_text to modify ostia.template
# 


WGRIB2=${WGRIB2:-wgrib2}
NCDUMP=${NCDUMP:-ncdump}

date=2024010112
file=${date}0000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB-v02.0-fv02.0.nc

variable="analysed_sst"
$NCDUMP -v $variable $file >sst

# make sure offset and scaling are ok
offset=`grep "$variable:add_offset =" <sst | sed -e 's/.*= //' -e 's/f.*//'`
scale=`grep "$variable:scale_factor =" <sst | sed -e 's/.*= //' -e 's/f.*//'`
echo "sst_offset=$offset scale=$scale"

# get the gridded data
sed -n "/ $variable =/,\$p" <sst >sst2
cat sst2 | egrep -v "(=|})" | sed -e 's/;//' -e 's/_/9.999e20/g' -e 's/,/ /g' >sst3

$WGRIB2 ostia.template -no_header -import_text sst3 -rpn "$scale:*:$offset:+" \
       -set_var TMP -set center 74 -set_date ${date} \
       -set_scaling -2 0 -set_grib_type c3 -grib_out sst$date.grb2

variable="sea_ice_fraction"
$NCDUMP -v $variable $file >seaice
offset=`grep "$variable:add_offset =" <seaice | sed -e 's/.*= //' -e 's/f.*//'`
scale=`grep "$variable:scale_factor =" <seaice | sed -e 's/.*= //' -e 's/f.*//'`
echo "sea_ice_offset=$offset scale=$scale"

# get the gridded data
sed -n "/ $variable =/,\$p" <seaice >seaice2
cat seaice2 | egrep -v "(=|})" | sed -e 's/;//' -e 's/_/9.999e20/g' -e 's/,/ /g' >seaice3
$WGRIB2 ostia.template -no_header -import_text seaice3 -rpn "$scale:*:$offset:+" \
       -set_var ICEC -set_scaling -2 0 -set center 254 -set_grib_type c1 -set_date ${date} \
       -grib_out sice$date.grb2

