#!/bin/ksh
# Script for post-treatment to be launched after genere_woodharvest_scenarios_extension.ksh. 
# The script does following:
# - rename some dimensions and variables
# - change to netcdf4 format 
# - add a description attribute to the netcdf file.
#
# This script takes as argument the name of the scenario to be used. 
# The script has been used on the scenarios MAGPIE-ssp585-2-1-e IMAGE-ssp126-2-1-e MAGPIE-ssp534-2-1-e
#
# Script done by N. Vuichard
#
files=`find /home/surface7/vuichard/LandUseMap_CMIP6/$1/outputs/ -name "*woodharvest*"`


for i in $files
do
  dir=`echo $i | sed -e "s/\(.*\/\).*/\1/"`
  year=`echo $i| sed -e "s/\(.*woodharvest_\)\(.*\)\.nc/\2/"`
  echo $i $dir $year
  file=${dir}"woodharvest_"${year}".nc"
  echo ${file}
  cp $i ${file}
  ncwa -a TIME ${file} temp.nc
  ncks -C -O -x -v TIME temp.nc temp.nc
  ncrename -v WOODHARVEST,woodharvest temp.nc
  ncrename -d LAT,latitude temp.nc
  ncrename -d LON,longitude temp.nc
  ncrename -v LAT,latitude temp.nc
  ncrename -v LON,longitude temp.nc
  mv temp.nc ${file}
  #ncap2 -O -s 'where (woodharvest < 0.) woodharvest=0.' woodharvest_${i}.nc woodharvest_${i}.nc
  ncatted -a long_name,woodharvest,o,c,"Harvested wood biomass" ${file}
  ncatted -a cell_methods,woodharvest,d,, ${file}
  ncatted -a units,woodharvest,o,c,"gC m-2[forest]" ${file}
  ncatted -a description,global,o,c,"This data is derived from LUH2v2h for CMIP6. It is computed as the total wood biomass (primf_bioh+primn_bioh+secmf_bioh+secyf_bioh+secnf_bioh) divided by the related land cell area ((primf+primn+secdf+secdn)*area). The ferret script used for generating this data has been stored at http://forge.ipsl.jussieu.fr/igcmg/browser/TOOLS/CMIP6_FORCING/WOOD_HARVEST/genere_woodharvest_scenarios_extension.jnl. Done by N. Vuichard, LSCE, June 25, 2019" ${file}
  ncks -O -4 ${file} ${file}
done

