#!/bin/bash
#BSUB -q serial_6h 
#BSUB -J iecmwf_16km 
#BSUB -n 1
#BSUB -o run.%J.out
#BSUB -e run.%J.err

## add atributes
R_OUT="/work/tessa08/wrf_v3.5.1/WPS/DATA/ecmwf_16km"
cd ${R_OUT}
 File="ecmwf_2d_281113_301113.nc"

## split variables
for ii in u10 v10 t2m d2m lsm sp msl ci skt sst sd stl1 stl2 stl3 stl4 swvl1 swvl2 swvl3 swvl4 
do
  fileN=file_${ii}.nc
  ncks -v ${ii} ${File} ${fileN}
done

##converting netcdf to grib
## "-t ecmwf copy" added to correctly read fields
 cdo -r -f grb -t ecmwf copy -setparam,165.128 file_u10.nc fileu10.grib
 cdo -r -f grb -t ecmwf copy -setparam,166.128 file_v10.nc filev10.grib
 cdo -r -f grb -t ecmwf copy -setparam,167.128 file_t2m.nc filet2m.grib
 cdo -r -f grb -t ecmwf copy -setparam,168.128 file_d2m.nc filed2m.grib
 cdo -r -f grb -t ecmwf copy -setparam,172.128 file_lsm.nc filelsm.grib
 cdo -r -f grb -t ecmwf copy -setparam,134.128 file_sp.nc filesp.grib
# cdo -r -f grb -t ecmwf copy -setparam,151.128 file_mls.nc filemsl.grib
 cdo -r -f grb -t ecmwf copy -setparam,31.128 file_ci.nc fileci.grib
 cdo -r -f grb -t ecmwf copy -setparam,235.128 file_skt.nc fileskt.grib
 cdo -r -f grb -t ecmwf copy -setparam,34.128 file_sst.nc filesst.grib
 cdo -r -f grb -t ecmwf copy -setparam,141.128 file_sd.nc filesd.grib
 cdo -r -f grb -t ecmwf copy -setparam,139.128 -setltype,112 file_stl1.nc filestl1.grib
 cdo -r -f grb -t ecmwf copy -setparam,170.128 -setltype,112 file_stl2.nc filestl2.grib
 cdo -r -f grb -t ecmwf copy -setparam,183.128 -setltype,112 file_stl3.nc filestl3.grib
 cdo -r -f grb -t ecmwf copy -setparam,236.128 -setltype,112 file_stl4.nc filestl4.grib
 cdo -r -f grb -t ecmwf copy -setparam,39.128 -setltype,112 file_swvl1.nc fileswvl1.grib
 cdo -r -f grb -t ecmwf copy -setparam,40.128 -setltype,112 file_swvl2.nc fileswvl2.grib
 cdo -r -f grb -t ecmwf copy -setparam,41.128 -setltype,112 file_swvl3.nc fileswvl3.grib
 cdo -r -f grb -t ecmwf copy -setparam,42.128 -setltype,112 file_swvl4.nc fileswvl4.grib

## set lower and upper borderl for level type 112 field
cdo setzaxis,myzaxis filestl1.grib filestl1_new.grib
cdo setzaxis,myzaxis filestl2.grib filestl2_new.grib
cdo setzaxis,myzaxis filestl3.grib filestl3_new.grib
cdo setzaxis,myzaxis filestl4.grib filestl4_new.grib
cdo setzaxis,myzaxis fileswvl1.grib fileswvl1_new.grib
cdo setzaxis,myzaxis fileswvl2.grib fileswvl2_new.grib
cdo setzaxis,myzaxis fileswvl3.grib fileswvl3_new.grib
cdo setzaxis,myzaxis fileswvl4.grib fileswvl4_new.grib

##merge into single grib file
cdo merge fileswvl4.grib fileswvl3.grib fileswvl2.grib fileswvl1.grib fileu10.grib filev10.grib filet2m.grib filed2m.grib filelsm.grib filesp.grib fileci.grib fileskt.grib filesst.grib filesd.grib filestl1_new.grib filestl2_new.grib filestl3_new.grib filestl4_new.grib fileswvl1_new.grib fileswvl2_new.grib fileswvl3_new.grib fileswvl4_new.grib ecmwf_2d_281113_301113.grib 

