#!/bin/ksh
#
# Script to transplant 1dvar retrieval into observations file, 
# and then convert into BUFR format.
#

export OBS=atm20110912_000312_M02_1230427200_N0019_XXXX.nc # input file, containing refractivity derived from bending angle 

export ANL=1dvar_sol.nc                                   # 1dvar output, containing forward-modelled refractivity based on 1DVAR retrieval.

export OUT2=atm20110912_000312_M02_1230427200_N0019_XXXX_1dvar.nc # new output ncdf file

export OUTB=atm20110912_000312_M02_1230427200_N0019_XXXX_1dvar.bufr # new output bufr file


# Copy obs to output file, retaining source info in global history attribute

ncks -a $OBS -O $OUT2 


# Transplant required data
# NB (1) "_sfc" serves as a proxy for lev2c, which is not stored as a dim=1 coord variable
#    (2) "dim_char64" ensures level_type is copied across


for lev in lev2b _sfc lev2d dim_char64 ; do   # data on these levels to be transplanted.  

  var_list=""
  
# Find out which fields are present on each level

  for var in `ncdump -h $ANL |grep $lev |grep dim_unlim |cut -d"(" -f1 |rev |cut -d" " -f1` ; do

    var_list=$var_list","$var

  done

  var_list=`echo $var_list |cut -c2- |rev`

  #echo \$var_list = $var_list # If you want to check

  if [[ $var_list != "" ]] ; then

    ncks -v$var_list $ANL -A $OUT2  # append these fields to $OUT2

  fi

done


# Unfortunately, and in contrast to what the NCO manual says, this procedure 
# overwrites some of the global attributes needed by ropp2bufr.  
# So reinstate them from $OBS.

ncks -x -A $OBS $OUT2

# To check you've done what you wanted:
# ncdump -h $OBS  `echo $OBS  |sed -es/'.nc'/'.cdl'`
# ncdump -h $OUT2 `echo $OUT2 |sed -es/'.nc'/'.cdl'`
# diff *.cdl, or tkdiff *.cdl.



# Convert to bufr format

/data/nwp1/idculv/ROPP/ropp-5.1/ifort/bin/ropp2bufr $OUT2 -o $OUTB 

# To check you've done what you wanted:
# decbufr -dh $OUTB > ${OUTB}.dh
# This could be compared with the bufr version of the original OBS file, if desired. 





