#!/usr/bin/env bash

# Convert old to new in `netcdf4_classic` format chunked with:
# - 64K element chunks
# - Long Time dimension
# - Long Vertical dimension
# - Balanced planar (other) dimensions
#

old="${1}"
new="${2}"
echo "Process ${old}"
test -f "${old}" || (echo "Input ${old} does not exist" && exit 1)
echo "Create  ${new}"
test -f "${new}" && (echo "Output ${old} exists" && exit 1)
test -f "${new}" && rm -v "${new}"

# Find input file dimensions to fix
#dim_bottom_top=$(ncdump -h "${old}" | grep ' *bottom_top = ' | sed -E 's:[^0-9]*([0-9]+).*:\1:')
dim_bottom_top=13  # Most interpolated variables fit well within 10 layers
dim_Time=$(ncdump -h "${old}" | grep ' *Time = ' | sed -E 's:[^0-9]*([0-9]+).*:\1:')
echo "Fixed dimensions: bottom_top=${dim_bottom_top} Time=${dim_Time}"

ncks \
  --print \
  --overwrite \
  --fl_fmt=netcdf4_classic \
  --chunk_cache=1000000000 \
  --chunk_min=1048576 \
  --chunk_policy=g3d \
  --chunk_map=prd \
  --chunk_scalar=8192 \
  --chunk_dimension=Time,${dim_Time} \
  --chunk_dimension=bottom_top,${dim_bottom_top} \
  "${old}" \
  "${new}"
