#!/bin/sh
set -e

USAGE='
Split input multi-year file into a number of 1-year files.
Each 1-year chunk contains December from the previous year and
January from the following year, if exists. 

Splitted files are placed in a subdirectory with the same name as the
input file, without edition number. An optional edition number of
output files can also be specified. Default is 999.

USAGE

  split_forcing_files input-file[.NNN] [MMM]

where

NNN is the edition number of input file (optional)
MMM is the edition number of output files (optional). Default is 999.

Examples:
  split-forcing-file td_pcmdi-amip-1-1-2-v1_187001-201612_gp_128_64_gt
'

if [ $# -eq 0 ] ; then
  echo "$USAGE"
  exit
fi

inp=$1
base=${inp%.[0-9][0-9][0-9]}
ed=${2:-999}

echo inp=$inp
echo base=$base
echo ed=$ed

pwd=`pwd`

# redefine RUNPATH
export RUNPATH=$pwd

wrkdir=$RUNPATH/tmp.split.$base
mkdir -p $wrkdir


cd $wrkdir

release base
access  base $base

# derive time period and date format from input file
date1=`ggstat base | grep GRID | head -1 | cut -c13-22`
date2=`ggstat base | grep GRID | tail -1 | cut -c13-22`

if [ $date1 -le 9999 ] ; then
  datefmt="YYYY"
  year1=$date1
  year2=$date2
elif [ $date1 -le 999912 ] ; then
  datefmt="YYYYMM"
  year1=`echo $date1 | awk '{printf "%04d",int($1/100)}'`
  year2=`echo $date2 | awk '{printf "%04d",int($1/100)}'`
elif [ $date1 -le 99991224 ] ; then
  datefmt="YYYYMMDD"
  year1=`echo $date1 | awk '{printf "%04d",int($1/10000+0.5)}'`
  year2=`echo $date2 | awk '{printf "%04d",int($1/10000+0.5)}'`
else
  datefmt="YYYYMMDDHH"
  year1=`echo $date1 | awk '{printf "%04d",int($1/1000000+0.5)}'`
  year2=`echo $date2 | awk '{printf "%04d",int($1/1000000+0.5)}'`
fi
echo datefmt=$datefmt year1=$year1 mon1=$mon1 year2=$year2 mon2=$mon2

# create directory for output file
mkdir -p $RUNPATH/$base

for yr in `seq $year1 1 $year2` ; do
  echo $yr
  yrm=`expr $yr - 1`
  yrp=`expr $yr + 2`
  if [ "$datefmt" = "YYYYMM" ] ; then
    echo "C*SELECT.  STEP   -${yrm}12    ${yrp}01    1     -9001 1000 NAME  ALL" | ccc select base ${base}_${yr}
  elif [ "$datefmt" = "YYYYMMDD" ] ; then
    echo "C*SELECT.  STEP -${yrm}1201  ${yrp}0131    1     -9001 1000 NAME  ALL" | ccc select base ${base}_${yr}
  elif [ "$datefmt" = "YYYYMMDDHH" ] ; then
    echo "C*SELECT.  STEP${yrm}120100${yrp}013124    1     -9001 1000 NAME  ALL" | ccc select base ${base}_${yr}
  else
    echo "ERROR: invalid datefmt=$datefmt"
    exit 1
  fi
  
  if [ -s $RUNPATH/${base}/${base}_${yr}.999 ] ; then
    # can't be saved, make a copy without saving
    mkdir -p $RUNPATH/${base}_unsaved
    mv ${base}_${yr} $RUNPATH/${base}_unsaved/${base}_${yr}
  else
    env RUNPATH=$RUNPATH/${base} save ${base}_${yr} ${base}_${yr} ed=$ed
    release ${base}_${yr}
  fi
done

# cleanup
cd $pwd
rm -rf $wrkdir

