#/usr/bin/ksh

export nlev=60
export nlev=91
export nlev=137

export corr_file=bg_ses_ecmwf_error_corr_L${nlev}.nc

export sigma_file=ec_ses_diagonal${nlev}.2012


# Remove sigma from corr file

ncks -h -a -x -vsigma $corr_file -O temp1.nc


# Dump out sigma

ncks -h -vsigma $corr_file -O temp2.nc

ncdump temp2.nc > temp2.ncdump


# Remove -, and replace by values in sigma file

head --lines=-3 temp2.ncdump |sed -es/'_,'/' '/g  > temp3.ncdump

cat $sigma_file | awk '{print $0","}' >> temp3.ncdump

head --lines=-1 temp3.ncdump > temp4.ncdump

tail --lines=1  temp3.ncdump |sed -es/','/';'/g  >> temp4.ncdump

echo '}' >> temp4.ncdump


# Correct n_state

n_state1=`grep "n_state = " temp4.ncdump |cut -d'=' -f2 |cut -d';' -f1`

n_state2=`expr 2 \* $nlev \+ 1`

cat temp4.ncdump |sed -es/"n_state =$n_state1"/"n_state = $n_state2"/g > temp5.ncdump


# Generate cov file

ncgen -o temp5.nc temp5.ncdump


# Correct the sigma  file

ncatted -h -aunits,sigma,o,c,"K, 1, 1" temp5.nc 

ncatted -h -aauthor,global,o,c,"J K Nielsen, DMI and I D Culverwell, Met Office" temp5.nc

ncatted -h -atitle,global,o,c,"B-matrix generated by the Scaled Ensemble Standard Deviation method of Holm et al, ECMWF Tech Memo 680, 2012" temp5.nc

ncatted -h -anotes,global,o,c,"Requires use_logp = use_logq = .TRUE. to be used in ropp_1dvar" temp5.nc


# Append to the correlations

ncks -h temp5.nc -A temp1.nc

mv temp1.nc ropp_${corr_file}


# Clean up

rm temp*.nc*



