#!/bin/bash
#
export LIBDWD_BITMAP_TYPE=ASCII
export LIBDWD_FORCE_CONTROLWORDS=1

#### !!!! Adopt this directory !!!!
SPDIR=$HOME/cclm-sp_2.1
INIDIR=$WORK/reference_data_cclm/cclm_02800_CV_SOPI/int2lm_output/plev_tests
OUTPUT=$WORK/reference_data_cclm/cclm_02800_CV_SOPI/COSMO_output/CTRL_28_CV/E

cd ${PWD}

#################################################
# number of processors
#################################################

NPX=10
NPY=10
NPIO=0
NP1=`expr $NPX \* $NPY`
NP=`expr $NP1 + $NPIO`
N1=`expr $NP + 15`
NODES=`expr $N1 \/ 16`
#NN=`expr $NPY \/ $NNP`
anz_procs=$((${NPX}*${NPY}+${NPIO}))  # Anzahl Prozessoren


#################################################
# global settings
#################################################
#DATE=2012102000

class=p
wtime=4320 #4320 # Zeit, wie lange Job rechnen darf

#################################################
# cleanup
#################################################
rm -f YU* OUTPUT
rm -f cclm_job
mv -f Job*.* ./Jobs/
rm -f $LM_DIR/l*

# cat together the INPUT*-files
#################################################
cat > INPUT_ORG << end_input_org
 &LMGRID
  startlat_tot  = -8.75, startlon_tot  =-7.3,
  pollat = 40., pollon = -170.0, 
  dlon=0.025, dlat=0.025, 
  ie_tot=274, je_tot=262, ke_tot=59,
 /END
 &RUNCTL
  dt=20,
  hstart=0,   hstop=5064.0,
  ydate_ini='2012090100', ydate_end='2013040100',
  nprocx= ${NPX}, nprocy= ${NPY}, nprocio=${NPIO},
hincmxt=24.0, hincmxu=1.0,                                ! Invertval in hours for the period of validity of minimum and maximum values of 2m-temperature/10-m wind gusts (default=6/1)
  itype_calendar=0,                                         ! Calendar is used during forecast                                         (default=0)
  lphys      = .TRUE.,                                      ! Switch inculde physcial parameterization                                 (default=T)
  lreorder = .FALSE.,                                       ! Numbering of the MPI processes                                           (default=T)
  lreproduce = .TRUE.,                                      ! Ensures the computation of reproducilble result in parallel mode         (default=F) 
  ldatatypes = .FALSE.,                                     ! Choose betewwn an explicit buffering or an implicit buffering            (default=F)
  nboundlines = 3,                                          ! Number of boundlines                                                     (default=3)
  ncomm_type = 3,                                           ! To choose a certain type of communication                                (default=1)
  ldump_ascii=.FALSE.,                                      ! To sve ASCII-files writing durin the model to disk in every time step    (default=T)
  lartif_data=.FALSE,                                       ! default=F
  luse_rttov    = .FALSE.,                                  ! Switch to compute synthetic satellite images                                    (default=F)
  luseobs = .FALSE.,                                        ! Switch to use observation during the model run (for data assimilation           (default=F)
  ldiagnos   = .TRUE.,                                      ! Switch to include diagnostic calculations                                       (default=F)
  ltime_barrier=.FALSE.,                                    ! Barriesr called dring the model run. Without barries, the model will run faster (default=T)
  ldebug_io=.FALSE.,                                        ! Debug output the input and output                                               (default=F)
  idbg_level=2,                                             ! Verbosity of ASCII output during the model rund
  linit_fields=.FALSE.,                                     ! Swith on/off initialization of local variables
!  hincmxt=24, hincmxu=24,
 ! itype_calendar=0,
!  lreorder = .FALSE.,  lreproduce = .TRUE.,
!  ldatatypes = .FALSE.,
!  nboundlines = 3, 
!  ncomm_type = 3,
!  lartif_data = .FALSE.,
!  ldump_ascii = .FALSE.,
 /END
 &TUNING
  clc_diag  =   0.5,              ! Cloud cover at saturation in statictical cloud diagnostic                            (default=0.5) 
  pat_len   = 500.0,              ! Length scale of sub-scale surface patterns over land                                 (default=500)
  tur_len   = 150.0,              ! Maximal turbulent length scale (m)                                                   (default=500)
  rlam_heat =   1,                ! Scaling factor for the thickness of the laminar boundary layer for heat formula      (default=1) 
  rlam_mom  =   0.0,              ! Scaling factor for the thickness of the laminar boundary layer for momentum formula  (default=0)
  rat_lam   =   1.0,              ! Ratio of laminar boundary layer thickness for water vapour and sensible heat         (default=1)
  rat_can   =   1.0,              ! Scaling factor for the calculation of the conopy height affecting the T2m            (default=1)
  rat_sea   =  20.0,              ! Scaling factor or rlam_heat over sea                                                 (default=20)
  c_lnd     =   2.0,              ! Surface area index of gridpoints over land                                           (default=2)
  c_soil    =   1.0,              ! Surface area index of the evporating fraction of gridpoints over land                (default=1)
  c_sea     =   1.5,              ! Surface area index of gridpoints over sea                                            (default=1.5)
  z0m_dia   =   0.2,              ! Typical roughness length for a Synop station                                         (default=0.2)
  crsmin    = 150.0,              ! Minimum value of stomatal resistance                                                 (default=150)
  qc0       =   0.0002,           ! Cloud water threshold for autoconverison                                             (default=0.0)
  qi0       =   0.0,              ! Coud ice threshold for autoconverison                                                (default=0.0)
  q_crit    =   1.6,              ! Critical value forn normaliued over-saturation                                       (default=0.0)
  wichfakt  =   0.0,              ! Vertical smoothing factor for explicit vertical diffusion coefficient                (default=0.0)
  mu_rain   =   0.5,              ! Shape parameter of the rain drop size distribution                                   (default=0.0)
  v0snow    =    20,              ! Factor in her terminal velocity for snow                                             (default=25)
  rain_n0_factor = 0.1,           ! To reduce the evaporation of rain drops                                              (default=1.0)
  tkhmin    =   0.4,              ! Minimal diffusion coefficients for heat active in stable BL conditions               (default=0.4)
  tkmmin    =   0.4,              ! Minimal diffusion coefficients for momentum active in stable BL conditions           (default=0.4)
 /END
end_input_org

cat > INPUT_IO  << end_input_io
 &IOCTL
  lasync_io=.FALSE., yform_read='ncdf',  
  lbdclim=.TRUE.,
  ngribout=1,
 ! nhour_restart=744,744,744,
 ! ydir_restart='${SPDIR}/step_by_step/cclm_to_cclm/data/cclm_output/restarts/'
 ! ytunit_restart='d',
 /END
 &DATABASE
 /END
 &GRIBIN
  lbdana = .FALSE.,
  lana_rho_snow  = .FALSE.,
  lan_t_so0  = .TRUE.,
  lan_t_snow = .TRUE.,
  lan_t_cl   = .TRUE.,
  lan_w_snow = .TRUE.,
  lan_w_i    = .TRUE.,
  lan_w_cl   = .TRUE.,
  lan_vio3   = .TRUE.,
  lan_hmo3   = .TRUE.,
  lan_plcov  = .TRUE.,
  lan_lai    = .TRUE.,
  lan_rootdp = .TRUE.,
  lana_qi    = .TRUE.,  llb_qi    = .TRUE.,
  lana_qr_qs = .FALSE.,  llb_qr_qs = .FALSE.,
  lana_qg    = .FALSE., llb_qg    = .FALSE.,
  ydirini='$INIDIR' 
  lchkini=.TRUE.,
  hincbound=1,
  ydirbd='$INIDIR',
  lchkbd =.TRUE.,
  ytunitbd='d',
 /END
 &GRIBOUT
  yform_write='ncdf',
  hcomb=0,2760,1,
 yvarml= 'U         ','V         ','OMEGA     ','T         ',        ! Wind and temperature
         'QV        ','QC        ','QI        ','QS        ',        ! Specific rain/snow content
         'QR        ','P         ','PP        ','QVSFLX    ',        ! PP=deviation from reference pressure
         'PS        ','T_S       ','QV_S      ','T_SNOW    ',        ! Surface pressure,temperature,specific water content          
 !        'W_SNOW    ','U_10M     ','V_10M     ','VMAX_10M  ',        ! Wind in 10m
  !       'T_2M      ','TD_2M     ','TMIN_2M   ','TMAX_2M   ',        ! Temperature 2m
   !      'QV_2M     ','RELHUM_2M ','CLDEPTH   ',                     ! Specific and relative humidity, normalized cloud depth
    !     'CLCT      ','CLCH      ','CLCM      ','CLCL      ',        ! Total cloud cover=CLCT,Cloud cover high/middle/low clouds
     !    'ASOB_S    ','ATHB_S    ','ASOB_T    ','ATHB_T    ',        ! Averaged surface/TOA shortwave and longwave radiation
        !'ASWDIR_S  ','ASWDIFD_S ','ASWDIFU_S ',         
      !   'RAIN_GSP  ','SNOW_GSP  ','RAIN_CON  ','SNOW_CON  ',        ! Sum of rain/snow precipitation and rain/snow convective
       !  'TOT_PREC  ','TWATER    ','TQV       ','TOT_PR    ',        ! Total precipitation and total water content(TWATER) and precipitable water(TQV) 
        ! 'ASHFL_S   ','ALHFL_S   ','SHFL_S    ','LHFL_S    ',        ! Average sensible and latent heat flux,surface sensible and latent heat flux
!         'CAPE_ML   ','CIN_ML    ','CAPE_MU   ','CIN_MU    ',        ! CAPE/CIN of mean surface layer (ML) and for most unstable parcel (MU)
 !        'CAPE_CON  ','QCVG_CON  ','TKE       ','TKE_CON   ',        ! CAPE specific(CON),moisture convergence in the air for kuo type closure(QCVG_CON)
  !       'SLI       ','SI        ','EVATRA_SUM','AEVAP_S   ',        ! Showalter index (SI)and surface lifted index (SLI) and Evaporation products        
   !      'BAS_CON   ','TOP_CON   ','HPBL      ',                     ! Index convective cloud base (BAS), cloud top(TOP),Height of boundary layer(HPBL) 
    !     'HTOP_DC   ','HTOP_CON  ','HBAS_CON  ',                     ! Height of dry convective top (HTOP_DC)and cloud top (HTOP_CON),cloud base(HBAS),  
     !    'PMSL      ','LCL_ML    ','LFC_ML    ',                     ! Mean sea level presure(PMSL),Lifting condensation level(LCL_ML),
      !   'RUNOFF_S  ','RUNOFF_G  ',                                  ! Surface water drainage, soil water drainage
       !  'RLAT','RLON','FR_LAND','SOILTYP','HSURF','Z0','FIS',       ! Constants
        ! 'LAI','PLCOV','T_SO','T_G','W_I','W_SO','FOR_D','FOR_E',    ! Soil and vegetation parameters
         !'ROOTDP','ALB_RAD','W_SO_ICE','FRESHSNW','RHO_SNOW',        ! Soil and vegetation parameters
 ! yvarpl='T','U','V','W','RELHUM','FI','QI','QV',  !'QS','QR',
  yvarpl='T','U','V','OMEGA','RELHUM','FI','QI','QV',  !'QS','QR',
  plev=100,150,200,250,300,400,500,600,700,850,900,925,950,975,1000,1050,
  luvmasspoint=.FALSE.,
  lcheck = .TRUE.,
  lwrite_const=.TRUE.,
  ydir='$OUTPUT',
  ytunit='d',
 /END
end_input_io

cat > INPUT_DYN << end_input_dyn
 &DYNCTL
 alphaass=0.5300,
  ldiabf_lh = .TRUE.,
  ldyn_bbc = .TRUE.,
  y_scalar_advect='BOTT2',
  lexpl_lbc = .TRUE.,
  l2tls = .TRUE.,
  ldyn_bbc = .FALSE.,
  rlwidth=85000.0,
  nrdtau = 6,
  iadv_order = 3,
  itype_bbc_w = 1,
  l_diff_Smag = .FALSE.,
  itype_fast_waves = 1,
  lspecnudge=.FALSE.,alpha_sn=0.05,
  isc_sn=6, jsc_sn=6,
  yvarsn='U     ','V    ',
!  alphaass=1.0,
!  hd_corr_trcr_in=0.0,                   ! difussion factor (interior domain) for tracers
!  hd_corr_t_bd=0.75,                     ! difussion factor (boundary zone)   for temperature
!  hd_corr_u_bd=0.75,                     ! difussion factor (boundary zone)   for wind
!  hd_corr_p_bd=0.75,                     ! difussion factor (boundary zone)   for pressure
!  hd_corr_trcr_bd=0.0,                   ! difussion factor (boundary zone)   for tracers
!  hd_corr_u_in=0.1,                      ! difussion factor (interior domain) for wind
!  hd_corr_t_in=0.0,                      ! difussion factor (interior domain) for temperature
!  hd_corr_p_in=0.0,                      ! difussion factor (interior domain) for pressure
!  ldiabf_lh = .TRUE.,
!  ldyn_bbc = .FALSE.,
!  y_scalar_advect='BOTT2_STRANG',
!  lexpl_lbc = .TRUE.,
!  l2tls = .TRUE.,
!  ldyn_bbc = .FALSE.,
!  rlwidth=50000.0,
!  nrdtau = 6,
!  iadv_order = 3,
!  itype_bbc_w = 1,
!  l_diff_Smag = .FALSE.,
!  itype_fast_waves = 1,
!  itype_outflow_qrsg=2,                  ! Choose the typw of lateral bounddary treatment for qr,qs,qg ; 
!					!=2 gqr,qs,,qg to 0.0 at boundary zone          (default=1)
!  lspecnudge=.FALSE.,alpha_sn=0.05,
!  isc_sn=6, jsc_sn=6,
!  yvarsn='U     ','V    ',
 /END
end_input_dyn

cat > INPUT_PHY << end_input_phy
&PHYCTL
    lgsp=.TRUE.,                          !Main switch for including grid scale precipitation.
					  !(default=T)               
     ldiniprec=.FALSE.,                   ! with on ta diagnostic initialization of rain and show  
					  !   (default=F)
     itype_gscp=4,                        ! select special scheme
					  !       (default=3)
    lrad=.TRUE.,                          !Main switch for including radiation. 
					  !   (default=T)
      nradcoarse=2,                       ! If nradcoarse > 1, the radiation is computedn on a coarser 
					  !grid to save computation time. (default=1)
      lradf_avg=.TRUE.,                   ! To average the radiative forcings when running on a 
					  !coarser grid (nradcoarse > 1). ???
      hincrad=0.25,                       ! Interval between two calls of the radiation scheme (in hours)
      lforest=.TRUE.,                     ! External parameter fields modifying the scnw albedo of 
	                                  !evergereen and deciduous foresest (default=F)
      ico2_rad=10,                        ! choose special CO2 concentration  (default=0)
      icldm_rad=4,                        ! Parameter to select the mode of cloud representation  
					  !as input to the radiation parameterization.
    ltur=.TRUE.,                          !Main switch for including turbulent diffusion.
      limpltkediff=.TRUE.,                ! inculded horizontal turbuelent difffusion 
      ninctura=1,                         ! Increment in time steps for recalculating the transport 
						!coefficientcients Km and Kh for vertical
      ltkesso=.TRUE.,                     ! Switch, to calculate SSO-wake turbulence production for TKE. (default=F)
      lexpcor=.FALSE.,                    ! Explicit corrections of the implicitly calculated turbulent heat 
					  !and moisture uxes due to effects from subgrid-scale condensation
      ltmpcor=.FALSE.,                    ! Consideration of thermal TKE-source in enthalpy budget (only if 
					  !itype turb=3)
      lnonloc=.FALSE.,                    ! Nonlocal calculation of vertical gradients used for turbulent 
						 !diffusion (only if itype turb=3).
      lcpfluc=.FALSE.,                    ! Consideration of uctuations of the heat capacity of air (only if 
					  !itype turb=3).
      itype_turb=3,                       ! Parameter to select the vertical turbulent diffusion parameterization.
      imode_turb=1,                       ! Mode of turbulent vertical diffusion parametrization in case of 
				          !itype turb = 3. (default=0)
      icldm_turb=2,                       ! Mode of cloud representation to take into account subgrid-scale 
					  !condensation within the turbulence parameterization in case of itype turb
    itype_tran=2,                         !Main prameter to select a specific surface-layer parameterization. 2: TKE-based scheme inculding a laminar sub-layer (default=2)
      imode_tran=1,                       ! Type of surface-atmosphere transfer. 1: Based on diagnostic TKE in the surface layer. (default=1)
      itype_wcld=2,                       ! Type of cloud water diagnosis.       2: Diagnosis based on a statistical scheme.
      icldm_tran=0,                       ! Mode of cloud representation to take into account subgridscale condensation 0: No clouds are considered
      itype_synd=2,                       ! Type of diagnosis of synoptic station values.  2: Interpolation of screen-level (2-m, 10-m) values based on profile relations used in the new surface-layer scheme.
      lprfcor=.FALSE.,                    ! Using the profile values of the lowest main level instead of the mean value of the lowest layer for surface ux calculations.
   lsoil=.TRUE.,                        !Main switch to include soil processes by running a soil model.
      itype_evsl=2,                       ! Parameter to select the type of parameterization for evaporation of bare soil. 2: BATS version.
      itype_trvg=2,                       ! Parameter to select the type of parameterization for transpiration by vegetation. 2: BATS version.
      lmulti_layer=.TRUE.,                ! Switch to run the multi-layer (TRUE)
      lmelt=.TRUE.,                       ! Switch to include melting processes within the soil when running the multi-layer soil modelTERRA ML (default=F)
      lmelt_var=.TRUE.,                   ! Sub-option for the lmelt parameter. IF lmelt var = .TRUE, the soil freezing temperature is treated to be dependent on the water content (default=F)
      czbot_w_so=4.0,                     ! Depth of the bottom of last hydrological atice soil layer (default=2.5)
      !ke_soil = 9,
      !czml_soil = 0.005, 0.025, 0.07, 0.16, 0.34, 0.7, 1.42, 2.86, 5.74, 11.5,
    lconv=.TRUE.,                       !Main switch for including subgrid-scale convection
      nincconv=10,                        ! Intervall between two calls of the convection scheme    (default=4)
      itype_conv=3,                       ! To specify the type of convection parameterization  0: Tiedtke scheme(COSMO-EU)  3: Shallow convection based on Tiedtke scheme (COSMO-DE)
      lconv_inst=.TRUE.,                  ! Switch to write instantaneous (.TRUE.) or aggregate (.FALSE.) values of top con and bas con to model output.
      lcape=.FALSE.,                      ! Enables a CAPE-type closure within the Tiedtke convection scheme (not fully tested yet).
    lsso=.FALSE.,                       !Main switch to include subgrid scale orography processes     (default=T) 
    lseaice=.FALSE.,                    !Main switch to ativate the sea ice scheme                    (default=T)
   !itype_albedo=2,                     !Switch to choose the type of solar surface albedo.
/END
end_input_phy

cat > INPUT_DIA << end_input_dia
 &DIACTL
  n0meanval=0, nincmeanval=24,
  lgplong=.FALSE., lgpshort=.TRUE., lgpspec=.FALSE.,
  n0gp=0,      hincgp=6.0,
!  stationlist_tot= 0, 0, 52.220, 14.135, 'Lindenberg_Obs',
!                   0, 0, 53.633,  9.983, 'Hamburg',
 /END
end_input_dia

cat > INPUT_INI << end_input_ini
 &INICTL
  ndfi=2,
  tspan=  600.0, taus=  600.0,
  dtbak=15.0, dtfwd=15.0,
 /END
end_input_ini

cat > INPUT_ASS << end_input_ass
 &NUDGING
  lnudge  =.FALSE.,
 /END
end_input_ass


#################################################
# run the program
#################################################

cat > cosmo_de_job << ****
job_submit -p${anz_procs} -c $class -t $wtime -m 8000 mpirun ${SPDIR}/src/cclm/bin/cclm.exe

****
chmod u+x cosmo_de_job
./cosmo_de_job
job_queue

cat YUSPECIF YUCHKDAT > OUTPUT

