#!/bin/bash
#=== PURPOSE:
# One ozone files per year with 12 monthly records has been produced for the
#   historical ("h" index hereafter) period.
# ce0l interpolates them in space and create DJFMAMJJASONDJ files with two
#   more records to ensure correct time interpolation during first half of
#   January and second half of December:
#     * record 1: december of previous year
#     * record 14: january of next year
# No file was available for 2015, so Jan 2014 was used.
# When starting over with a SSP scenario (index "s" hereafter), using the 
#   historical 2014 december field would create a jump at Jan. 1st. To avoid
#   this, the 2014 file provided to ce0l contains a modified december field.
#   "i" denotes "interpolated", "m" modified.
# The interpolated field @2015-01-01 in the historical run is:
#     * Fi(2015-01-01_00) = [Fh(2014-12-15_12)+Fh(2014-01-15_12)]/2
# In the SSP run:
#     * Fi(2015-01-01_00) = [Fm +O3s(2015-01-15_12)]/2
# The gap vanishes if:
#     Fm = Fh(2014-12-15_12)+[Fh(2014-01-15_12)-Fs(2015-01-15_12)]
# This shows that we use the normally required field Fh(2014-12-15_12h)
#    plus the december anomaly ( historical 2014 - SSP 2015 ).
# This script generated the required 2014 modified file.
#
# INPUTS: tro3_2014.nc (historical)  tro3_2015_ssp**.nc (scenarii)
# OUTPUT: tro3_2014_ssp**.nc
#
# NB: Hard coded for input files at the 144x96x66 resolution.


#=== PARAMETERS
nlo=144
nla=96
nle=66
scenar="ssp434 ssp460"
data="/data/dcugnet/prodigfs/ipslfs/igcmg/IGCM/ATM/OZONE/UReading/CCMI-"

#=== NOT LIKELY TO BE CHANGED
res="${nlo}x${nla}x${nle}"
f='make_tro32014'

for s in $scenar; do

  fh=tro3_2014.nc
  fs=tro3_2015_${s}.nc
  fo=tro3_2014_${s}.nc

  #--- CREATE A MATLAB SCRIPT
  cat > $f.m << _fin
  Siz=[$nlo $nla $nle 1];                        %=== O3 FIELDS SIZES
  Jan=[0 0 0 0 ]; Dec=[0 0 0 11];                %=== NETCDF INDICES

  fid=netcdf.open('$fh','NOWRITE');              %=== HISTORICAL FILE
  vid=netcdf.inqVarID(fid,'tro3');
  Jh=netcdf.getVar(fid,vid,Jan,Siz);             %=== Hist. Jan 2014
  Dh=netcdf.getVar(fid,vid,Dec,Siz);             %=== Hist. Dec 2014
  netcdf.close(fid);

  fid=netcdf.open('$fs','NOWRITE');              %=== SCENARIO FILE
  vid=netcdf.inqVarID(fid,'tro3');
  Js=netcdf.getVar(fid,vid,Jan,Siz);             %=== SCENARIO Jan. 2015
  netcdf.close(fid);

  fid=netcdf.open('$fo','WRITE');                %=== OUTPUT FILE
  vid=netcdf.inqVarID(fid,'tro3');
  Dmod=Dh+Jh-Js; Dmod(Dmod<3E-9)=3E-9;           %=== MODIFIED Dec. 2014
  netcdf.putVar(fid,vid,Dec,Siz,Dmod);           %=== SAVE FIELD
  netcdf.close(fid);
_fin

  #--- LAUNCH THE MATLAB SCRIPT
  dh=$(ls -d ${data}historical.v20??????/original/$res/)
  do=$(ls -d ${data}${s}.v20??????/original/$res/)

  cp     $dh/$fh          $fo
  ln -sf $dh/$fh          $fh
  ln -sf $do/tro3_2015.nc $fs
  matlab -nojvm -nodisplay -nodesktop -r "$f; exit" > /dev/null 2>&1
  mv $fo $do/tro3_2014_hybrid.nc
  rm -f $fh $fs $f.m

done

