#!/bin/sh
# -*- Mode: sh -*-
#
#  Script to build 1mm and full record annual mean from monthly time serie
#
#  Uses nco tools
#
usage() {
echo
echo "usage : make_1mm [-d] [-v <field1>,<field2>...] [-t <record name>] [-m] <file> <nyears>"
echo "        -d : toggle debug mode"
echo "        -v : specify fields to work on"
echo "        -t : specify time record name (should be detected automatically)"
echo "        -m : do not make full record time mean"
echo "        <file>   : netcdf post-it format file"
echo "        <nyears> : number of years in file"
echo
}
#
#
# --------------------------------------------------------------
#  E. Guilyardi - LODYC -  July 1999 - Nov 2007
#
# 
# Inits
#

while getopts dhv:t:m name
do
    case $name in
	d) set -x ;;
	v) fields="$OPTARG" ;;
	t) timef="$OPTARG" ;;
	m) nomean=1;;
	h) usage 
	   echo
	   exit 1
	   ;;
    esac
done

#
# decode file name
#
shift `expr $OPTIND - 1`
file=$1

enam=`echo $file | awk -F\_ '{print $1}'`
ave=`echo $file | awk -F\_ '{print $2}'`
date1=`echo $file | awk -F\_ '{print $3}'`
year1=`echo $date1 | sed 's/\(.*\)../\1/'`
date2=`echo $file | awk -F\_ '{print $4}'`
year2=`echo $date2 | sed 's/\(.*\)../\1/'`
ndates=$2

root=${enam}_${ave}_${date1}_${date2}

type=`echo $file | awk -F\_ '{print $5}'`
type2=`echo $file | awk -F\_ '{print $6}'`
type3=`echo $file | awk -F\_ '{print $7}'`
type4=`echo $file | awk -F\_ '{print $8}'`
type=${type}_${type2}_${type3}_${type4}
type=`echo $type | sed 's/\(.*\)\.nc.*/\1/'`


type=${type:-"auto"}
nomean=${nomean:-0}

echo ""
echo "Processing: $enam $ave $year1 $year2 $ndates $type"

# detect time dimension

time=`ncdump -h ${file} | grep UNLIMITED | awk '{print $1}'`
time=${timef:-$time}
fields=${fields:-"-x -v $long,$lati"}
	  
#
case $ave in
    1m) # output file name
	month1=`echo $date1 | sed 's/.*\(..\)/\1/'`
	month2=`echo $date2 | sed 's/.*\(..\)/\1/'`

	aveoum=1mm
	;;

    *) echo " ERROR : case ave=$ave not relevant "
       exit 1
       ;;
esac

#
out1m=${enam}_${aveoum}_01_12_${year1}-${year2}_$type.nc
outmean=${enam}_${ndates}y_${year1}_${year2}_$type.nc
#
optg="-O"

m_list="00 01 02 03 04 05 06 07 08 09 10 11"

# average every month

for m in ${m_list}
    do
	m1=`expr $m + 1`
#	echo "   averaging month $m1 "
	ncks -O -d $time,$m,,12 ${file} ${root}_${type}_mean_month.nc || exit
	ncra -O -F -d $time,1,$ndates ${root}_${type}_mean_month.nc ${root}_${type}_mean_month_${m}.nc || exit
	rm ${root}_${type}_mean_month.nc
done
    
# build monthly means
    
echo " Building ${enam}_${aveoum}_01_12_${year1}-${year2}_$type.nc"
    
ncrcat ${optg} ${root}_${type}_mean_month_??.nc $out1m

if [ $nomean -eq 0 ] ; then 

    echo " Building ${outmean}"
    
    ncra ${optg} $out1m $outmean

fi

rm -f ${root}_${type}_mean_*.nc
