#!/bin/bash

rm -f *.txt

for dir in IPS* EC* MIR* MPI* Nor* ; do

 cd $dir

 for file in ${dir}*.nc ; do

 YYYY1=2015
 YYYY2=2100

  if [ "$file" != "${file%histo*}" ] ; then
   YYYY1=1850 ; YYYY2=2014
  fi  

  rm -f ${file%.nc}.txt

  [ $YYYY1 -ge 2015 ] && cp ${dir}*histo*.txt ${file%.nc}.txt

ferret <<EOF
use $file
repeat/name=YYYY/range=$YYYY1:$YYYY2 (\
let l1=1+12*(\`YYYY\`-$YYYY1);\
let l2=12+12*(\`YYYY\`-$YYYY1);\
list/nohead/file=${file%.nc}.txt/append/format=(f5.0,f7.2)  \`YYYY\`,tas[x=@ave,y=@ave,l=\`l1\`:\`l2\`@sum] /12)
quit
EOF

 done

 cd ..

done
