#!/bin/bash


for YYYY1 in 2010 2025 2055 ; do

YYYY2=$(( $YYYY1 + 9 ))

rm -f *.dat3 *.dat4 MAR-$YYYY1-$YYYY2.nc

for YYYY in `seq $YYYY1 $YYYY2` ; do

rm -f *.dat1 *.dat2


 for file in MAR-RIOCHIM04-$YYYY* ; do

 echo $file

ferret <<EOF
use $file
set mem/size=10000
let ws=(WINZ^2+WINM^2)^0.5
let uu=winz
let vv=winm
let tt=temp
let PP=COPC+LSPC
let HH=HGHT
list/nohead/format=(f7.2)/file=ws10.dat1/append ws[k=22]
list/nohead/format=(f7.2)/file=ws30.dat1/append ws[k=18]
list/nohead/format=(f7.2)/file=uu50.dat1/append uu[k=17]
list/nohead/format=(f7.2)/file=vv50.dat1/append vv[k=17]
list/nohead/format=(f7.2)/file=uu75.dat1/append uu[k=10]
list/nohead/format=(f7.2)/file=vv75.dat1/append vv[k=10]
list/nohead/format=(f7.1)/file=pbl.dat1/append hh
list/nohead/format=(f7.2)/file=tmp.dat1/append tt[k=22]
list/nohead/format=(f7.2)/file=ppp.dat1/append pp
quit
EOF

 done

 for file in MAR-RIOCHIM04-$YYYY.07* MAR-RIOCHIM04-$YYYY.08* MAR-RIOCHIM04-$YYYY.09* ; do

 echo $file

ferret <<EOF
use $file
set mem/size=10000
let ws=(WINZ^2+WINM^2)^0.5
let uu=winz
let vv=winm
let tt=temp
let PP=COPC+LSPC
let HH=HGHT
list/nohead/format=(f7.2)/file=ws10.dat2/append ws[k=22]
list/nohead/format=(f7.2)/file=ws30.dat2/append ws[k=18]
list/nohead/format=(f7.2)/file=uu50.dat2/append uu[k=17]
list/nohead/format=(f7.2)/file=vv50.dat2/append vv[k=17]
list/nohead/format=(f7.2)/file=uu75.dat2/append uu[k=10]
list/nohead/format=(f7.2)/file=vv75.dat2/append vv[k=10]
list/nohead/format=(f7.1)/file=pbl.dat2/append  hh
list/nohead/format=(f7.2)/file=tmp.dat2/append  tt[K=22]
list/nohead/format=(f7.2)/file=ppp.dat2/append  pp
quit
EOF
 done


 for file2 in *.dat1 *.dat2 ; do

  var=${file2%.dat*}

  if [ "$file2" != "${file2%1}" ] ; then
   file3=${file2%1}3
  else
   file3=${file2%2}4
  fi

ferret <<EOF
set mem/size=10000
use $file
define axis/t="01-JAN-$YYYY1 00:00":"31-DEC-$YYYY2 00:00":1/units=hours time2
define grid/x=lon/y=lon/t=time2 gg
file/var=$var/col=1/grid=gg $file2
list/format=(f8.2)/file=$file3/append/nohead $var[l=@ave]
quit
EOF

 done


done


for file2 in *.dat3  *.dat4 ; do

  var=${file2%.dat*}

  if [ "$file2" != "${file2%3}" ] ; then
   var=${var}1
  else
   var=${var}2
  fi



ferret <<EOF
set mem/size=10000
use $file
define axis/t=$YYYY1:$YYYY2:1 time2
define grid/x=lon/y=lon/t=time2 gg
file/var=$var/col=1/grid=gg $file2
save/file=MAR-$YYYY1-$YYYY2.nc/append $var
quit
EOF

done


rm -f *.dat1 *.dat2 *.dat3 *.dat4

done
