out_stats.f90 Source File


This file depends on

sourcefile~~out_stats.f90~~EfferentGraph sourcefile~out_stats.f90 out_stats.f90 sourcefile~modfields.f90 modfields.f90 sourcefile~out_stats.f90->sourcefile~modfields.f90 sourcefile~modglobal.f90 modglobal.f90 sourcefile~out_stats.f90->sourcefile~modglobal.f90 sourcefile~modmpi.f90 modmpi.f90 sourcefile~out_stats.f90->sourcefile~modmpi.f90 sourcefile~modsubgrid.f90 modsubgrid.f90 sourcefile~out_stats.f90->sourcefile~modsubgrid.f90 sourcefile~modthermodynamics.f90 modthermodynamics.f90 sourcefile~out_stats.f90->sourcefile~modthermodynamics.f90 sourcefile~out_write_nc.f90 out_write_nc.f90 sourcefile~out_stats.f90->sourcefile~out_write_nc.f90 sourcefile~vegetation.f90 vegetation.f90 sourcefile~out_stats.f90->sourcefile~vegetation.f90 sourcefile~modfields.f90->sourcefile~modglobal.f90 sourcefile~modglobal.f90->sourcefile~modmpi.f90 sourcefile~modsubgrid.f90->sourcefile~modfields.f90 sourcefile~modsubgrid.f90->sourcefile~modglobal.f90 sourcefile~modsubgrid.f90->sourcefile~modmpi.f90 sourcefile~modboundary.f90 modboundary.f90 sourcefile~modsubgrid.f90->sourcefile~modboundary.f90 sourcefile~modsubgriddata.f90 modsubgriddata.f90 sourcefile~modsubgrid.f90->sourcefile~modsubgriddata.f90 sourcefile~modsurfdata.f90 modsurfdata.f90 sourcefile~modsubgrid.f90->sourcefile~modsurfdata.f90 sourcefile~modthermodynamics.f90->sourcefile~modfields.f90 sourcefile~modthermodynamics.f90->sourcefile~modglobal.f90 sourcefile~modthermodynamics.f90->sourcefile~modmpi.f90 sourcefile~modthermodynamics.f90->sourcefile~modsurfdata.f90 sourcefile~out_write_nc.f90->sourcefile~modglobal.f90 sourcefile~out_write_nc.f90->sourcefile~modmpi.f90 sourcefile~vegetation.f90->sourcefile~modfields.f90 sourcefile~vegetation.f90->sourcefile~modglobal.f90 sourcefile~vegetation.f90->sourcefile~modmpi.f90 sourcefile~in_readsparsefiles.f90 in_readsparsefiles.f90 sourcefile~vegetation.f90->sourcefile~in_readsparsefiles.f90 sourcefile~in_readsparsefiles.f90->sourcefile~modglobal.f90 sourcefile~in_readsparsefiles.f90->sourcefile~modmpi.f90 sourcefile~modboundary.f90->sourcefile~modfields.f90 sourcefile~modboundary.f90->sourcefile~modglobal.f90 sourcefile~modboundary.f90->sourcefile~modmpi.f90 sourcefile~modboundary.f90->sourcefile~modsubgriddata.f90 sourcefile~modboundary.f90->sourcefile~modsurfdata.f90 sourcefile~moddriver.f90 moddriver.f90 sourcefile~modboundary.f90->sourcefile~moddriver.f90 sourcefile~modinletdata.f90 modinletdata.f90 sourcefile~modboundary.f90->sourcefile~modinletdata.f90 sourcefile~moddriver.f90->sourcefile~modfields.f90 sourcefile~moddriver.f90->sourcefile~modglobal.f90 sourcefile~moddriver.f90->sourcefile~modmpi.f90 sourcefile~moddriver.f90->sourcefile~modinletdata.f90 sourcefile~modsave.f90 modsave.f90 sourcefile~moddriver.f90->sourcefile~modsave.f90 sourcefile~modsave.f90->sourcefile~modfields.f90 sourcefile~modsave.f90->sourcefile~modglobal.f90 sourcefile~modsave.f90->sourcefile~modmpi.f90 sourcefile~modsave.f90->sourcefile~modsubgriddata.f90 sourcefile~modsave.f90->sourcefile~modinletdata.f90 sourcefile~initfac.f90 initfac.f90 sourcefile~modsave.f90->sourcefile~initfac.f90 sourcefile~initfac.f90->sourcefile~modglobal.f90 sourcefile~initfac.f90->sourcefile~modmpi.f90

Files dependent on this one

sourcefile~~out_stats.f90~~AfferentGraph sourcefile~out_stats.f90 out_stats.f90 sourcefile~program.f90 program.f90 sourcefile~program.f90->sourcefile~out_stats.f90 sourcefile~tests.f90 tests.f90 sourcefile~program.f90->sourcefile~tests.f90 sourcefile~tests.f90->sourcefile~out_stats.f90

Source Code

!> \file out_stats.f90
!! Writes statistics of various fields to various NetCDF files.
!>
!
!! Inspired from the uDALES v2.2.0 modstatsdump.f90 routine by Tom Grylls, ICL (2016).
!! \author Dipanjan Majumdar, ICL (2023-2026)
!! \author Jingzi Huang, ICL (2024-2026)
!! \todo documentation
!
! This file is part of uDALES (https://github.com/uDALES/u-dales).
!
! uDALES is free software; you can redistribute it and/or modify
! it under the terms of the GNU General Public License as published by
! the Free Software Foundation; either version 3 of the License, or
! (at your option) any later version.
!
! uDALES is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
! GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License
! along with this program.  If not, see <http://www.gnu.org/licenses/>.
!
! Copyright (C) 2016- the uDALES Team, Imperial College London.
!
module stats
  use modglobal,  only : cexpnr, ltempeq, lmoist, lchem, nsv, rk3step, &
                         ltdump, lxytdump, lxydump, lytdump, lydump, ltreedump, &
                         ltislicedump, ltjslicedump, ltkslicedump, &
                         islice, nislice, jslice, njslice, kslice, nkslice, &
                         ib, ie, ih, jb, je, jh, kb, ke, kh, itot, jtot, xf, xh, yf, yh, zf, zh, &
                         dxf, dzf, dzfi, dxhi, dzhi, dzh2i, dyi, dzhiq, &
                         timee, tstatsdump, tstatstart, tstatsgap, tsample, receptor_height, &
                         nreceptor_heights, receptor_heights, &
                         dt, runtime, btime, &
                         k1, JNO2
  use modfields,  only : um, vm, wm, pres0, presf, thlm, qtm, ql0, exnf, svm, &
                         IIu, IIus, IIut, IIv, IIvs, IIvt, IIw, IIws, IIwt, IIc, IIcs, IIct, &
                         IIuw, IIuws, IIuwt, IIvw, IIvws, IIuv, IIuvs
  use modsubgrid, only : ekh, ekm
  use modthermodynamics, only : air_temperature, relative_humidity
  use vegetation, only : veg, vegp, npts_u, npts_v, npts_w, ijk_u, ijk_v, ijk_w, veg_up, veg_vp, veg_wp
  use modmpi,     only : cmyidx, cmyidy, myid, myidx, myidy, spatial_avg, mpierr
  use mpi
  use decomp_2d,  only : zstart, zend
  use modstat_nc, only : ncinfo, open_nc, define_nc, writestat_dims_nc, writestat_nc, &
                         writeoffset, writeoffset_2d, writeoffset_1dx, &
                         write_pedestrian_wind_metadata_nc, write_pedestrian_wind_heights_nc, nc_fillvalue
  use netcdf

  implicit none
  private
  public :: stats_init, stats_main, stats_exit, stats_sgs_fluxes
  save

  integer :: xdim, ydim, zdim
  real    :: tsamplep, tstatsdumpp, tstatsdumppi

  logical :: lstatsdump, lstatstavgdump, lrh
  logical :: ltavgslice   !< any time-averaged slice output (ltislicedump, ltjslicedump, ltkslicedump)
  logical :: ltavg3d      !< any output built from the 3-D time-average accumulators (stats_t or slices)
  character(80) :: filenametis, filenametjs, filenametks
  integer :: ncidtis, nrectis, ncidtjs, nrectjs, ncidtks, nrectks
  integer :: local_ntislice = 0   !< number of islice planes inside this rank's x-range
  integer :: local_ntjslice = 0   !< number of jslice planes inside this rank's y-range
  
  character(80)              :: filenamet
  character(80)              :: filenamexyt
  character(80)              :: filenamexy
  character(80)              :: filenameyt
  character(80)              :: filenamey
  character(80)              :: filenametree
  character(80)              :: timeVar(1,4)
  character(80), allocatable :: tVars(:,:), xytVars(:,:), xyVars(:,:), ytVars(:,:), yVars(:,:), treeVars(:,:)
  character(80)              :: pedestrianWindVars(2,4)
  integer                    :: tVarsCount, xytVarsCount, xyVarsCount, ytVarsCount, yVarsCount, treeVarsCount
  logical                    :: lstatsprepared = .false.  !< accumulators allocated and files created (done lazily at tstatstart)
  integer                    :: ctrt,    ncidt,    nrect, &
                                ctrxyt,  ncidxyt,  nrecxyt, &
                                ctrxy,   ncidxy,   nrecxy, &
                                ctryt,   ncidyt,   nrecyt, &
                                ctry,    ncidy,    nrecy, &
                                ctrtree, ncidtree, nrectree, &
                                dumpcount

  !!> Variables to store time averaged quantities
  real, allocatable :: ut(:,:,:)
  real, allocatable :: vt(:,:,:)
  real, allocatable :: wt(:,:,:)
  real, allocatable :: pt(:,:,:)

  real, allocatable :: uik(:,:,:)
  real, allocatable :: wik(:,:,:)
  real, allocatable :: vjk(:,:,:)
  real, allocatable :: wjk(:,:,:)
  real, allocatable :: uij(:,:,:)
  real, allocatable :: vij(:,:,:)
  real, allocatable :: utik(:,:,:)
  real, allocatable :: wtik(:,:,:)
  real, allocatable :: uwtik(:,:,:)
  real, allocatable :: vtjk(:,:,:)
  real, allocatable :: wtjk(:,:,:)
  real, allocatable :: vwtjk(:,:,:)
  real, allocatable :: utij(:,:,:)
  real, allocatable :: vtij(:,:,:)
  real, allocatable :: uvtij(:,:,:)

  real, allocatable :: uc(:,:,:)
  real, allocatable :: vc(:,:,:)
  real, allocatable :: wc(:,:,:)
  real, allocatable :: utc(:,:,:)
  real, allocatable :: vtc(:,:,:)
  real, allocatable :: wtc(:,:,:)
  real, allocatable :: uutc(:,:,:)
  real, allocatable :: vvtc(:,:,:)
  real, allocatable :: wwtc(:,:,:)

  real, allocatable :: usgs(:,:,:)
  real, allocatable :: vsgs(:,:,:)
  real, allocatable :: wsgs(:,:,:)
  real, allocatable :: usgst(:,:,:)
  real, allocatable :: vsgst(:,:,:)
  real, allocatable :: wsgst(:,:,:)

  real, parameter   :: utci_wind_height  = 10.0
  real, allocatable :: ws_localt(:,:,:), ws_10t(:,:), ws_now(:,:), wind_heights(:)
  logical, allocatable :: ws_local_valid(:,:,:), ws_10_valid(:,:), ws_local_available(:)
  integer, allocatable :: ws_local_klo(:), ws_local_khi(:)
  real, allocatable :: ws_local_weight(:)
  integer :: ws_10_klo, ws_10_khi
  real    :: ws_10_weight
  logical :: ws_10_available

  real, allocatable :: thlt(:,:,:)
  real, allocatable :: tempnow(:,:,:), tempt(:,:,:)
  real, allocatable :: rhnow(:,:,:), rht(:,:,:)
  real, allocatable :: thli(:,:,:)
  real, allocatable :: thlj(:,:,:)
  real, allocatable :: thlk(:,:,:)
  real, allocatable :: thlti(:,:,:)
  real, allocatable :: thltj(:,:,:)
  real, allocatable :: thltk(:,:,:)
  real, allocatable :: uthlti(:,:,:)
  real, allocatable :: vthltj(:,:,:)
  real, allocatable :: wthltk(:,:,:)
  real, allocatable :: thlthlt(:,:,:)
  real, allocatable :: thlsgs(:,:,:)
  real, allocatable :: thlsgst(:,:,:)

  real, allocatable :: qtt(:,:,:)
  real, allocatable :: qlt(:,:,:)
  real, allocatable :: qtk(:,:,:)
  real, allocatable :: qttk(:,:,:)
  real, allocatable :: wqttk(:,:,:)
  real, allocatable :: qtqtt(:,:,:)
  real, allocatable :: qtsgs(:,:,:)
  real, allocatable :: qtsgst(:,:,:)

  character(10), allocatable :: svtname(:)
  character(20), allocatable :: upsvptname(:)
  character(20), allocatable :: vpsvptname(:)
  character(20), allocatable :: wpsvptname(:)
  character(20), allocatable :: svpsvptname(:)
  character(10), allocatable :: svsgsname(:)
  real, allocatable :: svt(:,:,:,:)
  real, allocatable :: svi(:,:,:,:)
  real, allocatable :: svj(:,:,:,:)
  real, allocatable :: svk(:,:,:,:)
  real, allocatable :: svti(:,:,:,:)
  real, allocatable :: svtj(:,:,:,:)
  real, allocatable :: svtk(:,:,:,:)
  real, allocatable :: usvti(:,:,:,:)
  real, allocatable :: vsvtj(:,:,:,:)
  real, allocatable :: wsvtk(:,:,:,:)
  real, allocatable :: svsvt(:,:,:,:)
  real, allocatable :: svsgs(:,:,:,:)
  real, allocatable :: svsgst(:,:,:,:)

  real, allocatable :: PSS(:,:,:)
  real, allocatable :: PSSt(:,:,:)

  real, allocatable :: tr_now(:,:,:)

  !!> Variables to store time, y and x averaged quantities
  real, allocatable :: uxyt(:)
  real, allocatable :: vxyt(:)
  real, allocatable :: wxyt(:)
  real, allocatable :: pxyt(:)
  real, allocatable :: upwpxytik(:)
  real, allocatable :: vpwpxytjk(:)
  real, allocatable :: upvpxytij(:)
  real, allocatable :: uwxytik(:)
  real, allocatable :: vwxytjk(:)
  real, allocatable :: uvxytij(:)
  real, allocatable :: uuxyti(:)
  real, allocatable :: vvxytj(:)
  real, allocatable :: wwxytk(:)
  real, allocatable :: upupxytc(:)
  real, allocatable :: vpvpxytc(:)
  real, allocatable :: wpwpxytc(:)
  real, allocatable :: tkexytc(:)
  real, allocatable :: usgsxyt(:)
  real, allocatable :: vsgsxyt(:)
  real, allocatable :: wsgsxyt(:)

  real, allocatable :: thlxyt(:)
  real, allocatable :: tempxyt(:)
  real, allocatable :: rhxyt(:)
  real, allocatable :: wpthlpxytk(:)
  real, allocatable :: wthlxytk(:)
  real, allocatable :: thlpthlpxyt(:)
  real, allocatable :: thlsgsxyt(:)

  real, allocatable :: qtxyt(:)
  real, allocatable :: qlxyt(:)
  real, allocatable :: wpqtpxytk(:)
  real, allocatable :: wqtxytk(:)
  real, allocatable :: qtpqtpxyt(:)
  real, allocatable :: qtsgsxyt(:)

  !!> Variables to store y and x averaged quantities
  real, allocatable :: uxy(:)
  real, allocatable :: vxy(:)
  real, allocatable :: wxy(:)
  real, allocatable :: pxy(:)
  real, allocatable :: upwpxyik(:)
  real, allocatable :: vpwpxyjk(:)
  real, allocatable :: upvpxyij(:)
  real, allocatable :: uwxyik(:)
  real, allocatable :: uxyik(:)
  real, allocatable :: wxyik(:)
  real, allocatable :: vwxyjk(:)
  real, allocatable :: vxyjk(:)
  real, allocatable :: wxyjk(:)
  real, allocatable :: uvxyij(:)
  real, allocatable :: uxyij(:)
  real, allocatable :: vxyij(:)
  real, allocatable :: uuxyi(:)
  real, allocatable :: vvxyj(:)
  real, allocatable :: wwxyk(:)
  real, allocatable :: usgsxy(:)
  real, allocatable :: vsgsxy(:)
  real, allocatable :: wsgsxy(:)

  real, allocatable :: thlxy(:)
  real, allocatable :: tempxy(:)
  real, allocatable :: rhxy(:)
  real, allocatable :: wpthlpxyk(:)
  real, allocatable :: wthlxyk(:)
  real, allocatable :: thlxyk(:)
  real, allocatable :: thlsgsxy(:)

  real, allocatable :: qtxy(:)
  real, allocatable :: qlxy(:)
  real, allocatable :: wpqtpxyk(:)
  real, allocatable :: wqtxyk(:)
  real, allocatable :: qtxyk(:)
  real, allocatable :: qtsgsxy(:)

  !!> Variables to store time and y averaged quantities
  real, allocatable :: uyt(:,:)
  real, allocatable :: vyt(:,:)
  real, allocatable :: wyt(:,:)
  real, allocatable :: pyt(:,:)
  real, allocatable :: upwpytik(:,:)
  real, allocatable :: uwytik(:,:)
  real, allocatable :: upupytc(:,:)
  real, allocatable :: vpvpytc(:,:)
  real, allocatable :: wpwpytc(:,:)
  real, allocatable :: usgsyt(:,:)
  real, allocatable :: wsgsyt(:,:)

  real, allocatable :: thlyt(:,:)
  real, allocatable :: tempyt(:,:)
  real, allocatable :: rhyt(:,:)
  real, allocatable :: wpthlpytk(:,:)
  real, allocatable :: wthlytk(:,:)
  real, allocatable :: thlpthlpyt(:,:)
  real, allocatable :: thlsgsyt(:,:)

  real, allocatable :: qtyt(:,:)
  real, allocatable :: qlyt(:,:)
  real, allocatable :: wpqtpytk(:,:)
  real, allocatable :: wqtytk(:,:)
  real, allocatable :: qtpqtpyt(:,:)
  real, allocatable :: qtsgsyt(:,:)

  character(10), allocatable :: svytname(:)
  character(20), allocatable :: wpsvpytname(:)
  character(20), allocatable :: wsvytname(:)
  character(20), allocatable :: svpsvpytname(:)
  character(10), allocatable :: svsgsytname(:)
  real, allocatable :: svyt(:,:,:)
  real, allocatable :: wpsvpytk(:,:,:)
  real, allocatable :: wsvytk(:,:,:)
  real, allocatable :: svpsvpyt(:,:,:)
  real, allocatable :: svsgsyt(:,:,:)

  !!> Variables to store y averaged quantities
  real, allocatable :: uy(:,:)
  real, allocatable :: vy(:,:)
  real, allocatable :: wy(:,:)
  real, allocatable :: py(:,:)
  real, allocatable :: upwpyik(:,:)
  real, allocatable :: uwyik(:,:)
  real, allocatable :: uyik(:,:)
  real, allocatable :: wyik(:,:)
  real, allocatable :: usgsy(:,:)
  real, allocatable :: wsgsy(:,:)

  real, allocatable :: thly(:,:)
  real, allocatable :: tempy(:,:)
  real, allocatable :: rhy(:,:)
  real, allocatable :: wpthlpyk(:,:)
  real, allocatable :: wthlyk(:,:)
  real, allocatable :: thlyk(:,:)
  real, allocatable :: thlsgsy(:,:)

  real, allocatable :: qty(:,:)
  real, allocatable :: qly(:,:)
  real, allocatable :: wpqtpyk(:,:)
  real, allocatable :: wqtyk(:,:)
  real, allocatable :: qtyk(:,:)
  real, allocatable :: qtsgsy(:,:)

  character(10), allocatable :: svyname(:)
  character(20), allocatable :: wpsvpyname(:)
  character(20), allocatable :: wsvyname(:)
  character(10), allocatable :: svsgsyname(:)
  real, allocatable :: svy(:,:,:)
  real, allocatable :: wpsvpyk(:,:,:)
  real, allocatable :: wsvyk(:,:,:)
  real, allocatable :: svyk(:,:,:)
  real, allocatable :: svsgsy(:,:,:)

  !!> Variables to store time averaged tree quantities
  real, allocatable :: tr_ut(:,:,:)
  real, allocatable :: tr_vt(:,:,:)
  real, allocatable :: tr_wt(:,:,:)
  real, allocatable :: tr_thlt(:,:,:)
  real, allocatable :: tr_qtt(:,:,:)
  real, allocatable :: tr_qtRt(:,:,:)
  real, allocatable :: tr_qtAt(:,:,:)
  real, allocatable :: tr_omegat(:,:,:)
  character(10), allocatable :: svtreename(:)
  real, allocatable :: tr_svt(:,:,:,:)


  interface stats_compute_tavg
    module procedure stats_compute_tavg_1D
    module procedure stats_compute_tavg_2D
    module procedure stats_compute_tavg_3D
  end interface stats_compute_tavg


  contains
    subroutine stats_init
      implicit none
      integer :: nperiod
      real    :: tperiod

      ltavgslice = ltislicedump .or. ltjslicedump .or. ltkslicedump
      ltavg3d    = ltdump .or. ltavgslice
      lstatsdump = ltavg3d .or. lxytdump .or. lxydump .or. lytdump .or. lydump
      lstatstavgdump = ltavg3d .or. lxytdump .or. lytdump
      lrh = ltempeq .and. lmoist

      ! the time-averaged slices reuse the plane positions of the instantaneous slices
      call stats_validate_slice_inputs(ltislicedump, nislice, islice, 'islice')
      call stats_validate_slice_inputs(ltjslicedump, njslice, jslice, 'jslice')
      call stats_validate_slice_inputs(ltkslicedump, nkslice, kslice, 'kslice')
      
      if(.not.(lstatsdump .or. ltreedump)) return

      ! With tstatsgap > 0 the time-averaged statistics follow a fixed, absolute
      ! schedule: dumps at tstatstart + n*(tstatsdump + tstatsgap), n = 1, 2, ...,
      ! each averaging the tstatsdump seconds that precede it (gap first, averaging
      ! window last). E.g. tstatstart = 21600, tstatsdump = 900, tstatsgap = 13500
      ! gives 15-min means ending exactly at t = 36000, 50400, 64800, ...
      ! The schedule is anchored to absolute time, so a warm-started run keeps the
      ! same dump instants: tstatstart is advanced here to the first averaging
      ! window that (at least half) lies after the restart time btime.
      if (tstatsgap > 0.) then
        tperiod    = tstatsdump + tstatsgap
        tstatstart = tstatstart + tstatsgap          ! start of the first averaging window
        if (btime > tstatstart) then
          nperiod    = floor((btime - tstatstart)/tperiod)
          tstatstart = tstatstart + nperiod*tperiod  ! window containing or preceding btime
          if (tstatstart + 0.5*tstatsdump < btime) tstatstart = tstatstart + tperiod
        end if
        if (myid==0) write(*,'(a,f12.2,a,f12.2)') &
          ' stats: tstatsgap > 0, first averaging window starts at t = ', tstatstart, &
          ', first dump at t = ', tstatstart + tstatsdump
      end if

      if( (lstatstavgdump .or. ltreedump) &
          .and. runtime + btime <= tstatstart + tstatsdump ) then
        if(myid==0) then
          write(*,*) "ERROR: no time-averaged statistics file will be written as runtime + btime <= tstatstart + tstatsdump. &
                      &Note that runtime + btime must be greater than tstatstart + tstatsdump for writing time-averaged statistics files."
          write(*,*) "You have used runtime = ", runtime, ", btime = ", btime, ", tstatstart = ", tstatstart, ", and &
                     &tstatsdump = ", tstatsdump
          write(*,*) "Either correct the time settings or change all time-averaged stats writing flags to false."
          !abort every rank: a bare STOP inside a rank-0 guard leaves the other ranks alive until walltime
          call MPI_ABORT(MPI_COMM_WORLD, 1, mpierr)
        end if
      end if
      
      xdim = ie-ib+1
      ydim = je-jb+1
      zdim = ke-kb+1
      tsamplep = 0.
      tstatsdumpp = 0.
      dumpcount = 0
      call ncinfo(timeVar( 1,:), 'time', 'Time', 's', 'time')
    end subroutine stats_init

    !> Allocate the accumulators and create the NetCDF files. Called from stats_main the
    !> first time the sampling window is reached (timee >= tstatstart) rather than at
    !> start-up, so a run that stops before its first window - a chain link cut at the
    !> walltime, a short test - neither holds the accumulators nor leaves empty files.
    subroutine stats_prepare
      implicit none
      if (lstatsprepared) return
      lstatsprepared = .true.

      if(lstatsdump) then
        call stats_allocate_interp_and_sgs_vel
        if (ltempeq) call stats_allocate_interp_and_sgs_temp
        if (lmoist)  call stats_allocate_interp_and_sgs_moist
        if (lrh)     call stats_allocate_relative_humidity
      end if
      if(ltavg3d .or. lytdump .or. lydump) then
        if (nsv>0)   call stats_allocate_interp_and_sgs_scalar
      end if

      if(lstatstavgdump) then
        !> allocate variables to compute time-averaged quantities
        call stats_allocate_tavg_vel
        if (ltdump .or. ltkslicedump) call stats_allocate_tavg_pedestrian_wind
        if (ltempeq) call stats_allocate_tavg_temp
        if (lmoist)  call stats_allocate_tavg_moist
        if (lrh)     call stats_allocate_tavg_relative_humidity
      end if
      if(ltavg3d .or. lytdump) then
        if (nsv>0)   call stats_allocate_tavg_scalar
      end if

      !> Variable table of the outputs built from the 3-D accumulators, shared by
      !> stats_t.xxx.xxx.nc and the time-averaged slice files; kept for the writers.
      if (ltavg3d) then
        !> Total numbers of variables to be written
        tVarsCount = 15
        if (ltempeq) tVarsCount = tVarsCount + 7
        if (lmoist)  tVarsCount = tVarsCount + 5
        if (lrh)     tVarsCount = tVarsCount + 1
        if (nsv>0)   tVarsCount = tVarsCount + 6*nsv
        if ((lchem) .and. (nsv>2)) tVarsCount = tVarsCount + 1

        allocate(tVars(tVarsCount,4))   !!> Array to store the variable description of the quantities to be written
        ctrt = 0
        call stats_ncdescription_tavg_vel
        if (ltempeq) call stats_ncdescription_tavg_temp
        if (lmoist)  call stats_ncdescription_tavg_moist
        if (lrh)     call stats_ncdescription_tavg_relative_humidity
        if (nsv>0)   call stats_ncdescription_tavg_scalar
        if ((lchem) .and. (nsv>2)) call stats_init_tavg_PSS

        if (ltdump)       call stats_createnc_tavg
        if (ltislicedump) call stats_createnc_tislice
        if (ltjslicedump) call stats_createnc_tjslice
        if (ltkslicedump) call stats_createnc_tkslice
      end if

      !> Generate time, y and x averaged NetCDF: stats_xyt.xxx.nc
      if (lxytdump) then
        xytVarsCount = 21
        if (ltempeq) xytVarsCount = xytVarsCount + 6
        if (lmoist)  xytVarsCount = xytVarsCount + 6
        if (lrh)     xytVarsCount = xytVarsCount + 1

        allocate(xytVars(xytVarsCount,4))   !!> Array to store the variable description of the quantities to be written
        ctrxyt = 0
        call stats_init_xytavg_vel
        if (ltempeq) call stats_init_xytavg_temp
        if (lmoist)  call stats_init_xytavg_moist
        if (lrh)     call stats_init_xytavg_relative_humidity

        call stats_createnc_xytavg
        
        deallocate(xytVars)
      end if

      !> Generate y and x averaged NetCDF: stats_xy.xxx.nc
      if (lxydump) then
        xyVarsCount = 17
        if (ltempeq) xyVarsCount = xyVarsCount + 5
        if (lmoist)  xyVarsCount = xyVarsCount + 5
        if (lrh)     xyVarsCount = xyVarsCount + 1

        allocate(xyVars(xyVarsCount,4))   !!> Array to store the variable description of the quantities to be written
        ctrxy = 0
        call stats_init_xyavg_vel
        if (ltempeq) call stats_init_xyavg_temp
        if (lmoist)  call stats_init_xyavg_moist
        if (lrh)     call stats_init_xyavg_relative_humidity

        call stats_createnc_xyavg
        
        deallocate(xyVars)
      end if

      !> Generate time and y averaged NetCDF: stats_yt.xxx.xxx.nc
      if (lytdump) then
        ytVarsCount = 12
        if (ltempeq) ytVarsCount = ytVarsCount + 6
        if (lmoist)  ytVarsCount = ytVarsCount + 6
        if (lrh)     ytVarsCount = ytVarsCount + 1
        if (nsv>0)   ytVarsCount = ytVarsCount + 5*nsv

        allocate(ytVars(ytVarsCount,4))   !!> Array to store the variable description of the quantities to be written
        ctryt = 0
        call stats_init_ytavg_vel
        if (ltempeq) call stats_init_ytavg_temp
        if (lmoist)  call stats_init_ytavg_moist
        if (lrh)     call stats_init_ytavg_relative_humidity
        if (nsv>0)   call stats_init_ytavg_scalar

        call stats_createnc_ytavg
        
        deallocate(ytVars)
      end if

      !> Generate y averaged NetCDF: stats_y.xxx.xxx.nc
      if (lydump) then
        yVarsCount = 9
        if (ltempeq) yVarsCount = yVarsCount + 5
        if (lmoist)  yVarsCount = yVarsCount + 5
        if (lrh)     yVarsCount = yVarsCount + 1
        if (nsv>0)   yVarsCount = yVarsCount + 4*nsv

        allocate(yVars(yVarsCount,4))   !!> Array to store the variable description of the quantities to be written
        ctry = 0
        call stats_init_yavg_vel
        if (ltempeq) call stats_init_yavg_temp
        if (lmoist)  call stats_init_yavg_moist
        if (lrh)     call stats_init_yavg_relative_humidity
        if (nsv>0)   call stats_init_yavg_scalar

        call stats_createnc_yavg

        deallocate(yVars)
      end if

      !> Generate time averaged tree data NetCDF: stats_tree.xxx.xxx.xxx.nc
      if (ltreedump) then
        treeVarsCount = 3
        if (ltempeq) treeVarsCount = treeVarsCount + 1
        if (lmoist)  treeVarsCount = treeVarsCount + 4
        if (nsv>0)   treeVarsCount = treeVarsCount + nsv
        allocate(treeVars(treeVarsCount,4))   !!> Array to store the variable description of the quantities to be written
        ctrtree = 0
        call stats_init_tree_vel
        if (ltempeq) call stats_init_tree_temp
        if (lmoist)  call stats_init_tree_moist
        if (nsv>0)   call stats_init_tree_scalar

        call stats_createnc_tree
        
        deallocate(treeVars)
      end if
    end subroutine stats_prepare


    subroutine stats_main
      implicit none

      if (timee < tstatstart) return
      if (.not. rk3step==3)  return
      if(.not.(lstatsdump .or. ltreedump)) return

      if (.not. lstatsprepared) call stats_prepare

      ! For one-timestep diagnostics with dump intervals no larger than dt,
      ! treat the just-completed step as a valid first sample immediately
      ! instead of waiting for a second call to statsdump.
      if (tsamplep == 0. .and. tsample <= dt) tsamplep = dt
      if (tstatsdumpp == 0. .and. tsample <= dt) tstatsdumpp = dt

      if (tsamplep >= tsample) then        ! at every stats sampling instance
        tstatsdumppi = 1./tstatsdumpp

        if(lstatsdump) then
          call stats_interpolate_and_sgs_vel
          if (ltempeq) call stats_interpolate_and_sgs_temp
          if (lmoist)  call stats_interpolate_and_sgs_moist
          if (ltempeq) call stats_calculate_air_temperature
          if (lrh)     call stats_calculate_relative_humidity
        end if
        if(ltavg3d .or. lytdump .or. lydump) then
          if (nsv>0)   call stats_interpolate_and_sgs_scalar
        end if

        if(lstatstavgdump) then
          call stats_compute_tavg_vel
          if (ltdump .or. ltkslicedump) call stats_compute_tavg_pedestrian_wind
          if (ltempeq) call stats_compute_tavg_temp
          if (lmoist)  call stats_compute_tavg_moist
          if (lrh)     call stats_compute_tavg_relative_humidity
        end if
        if(ltavg3d .or. lytdump) then
          if (nsv>0) call stats_compute_tavg_scalar
        end if
        if(ltavg3d) then
          if ((lchem) .and. (nsv>2)) call stats_compute_tavg_PSS
        end if

        if(lxydump) then
          call stats_compute_xyavg_vel
          if (ltempeq) call stats_compute_xyavg_temp
          if (lmoist)  call stats_compute_xyavg_moist
          if (lrh)     call stats_compute_xyavg_relative_humidity
          if (myid==0) then
            call writestat_nc(ncidxy, 'time', timee, nrecxy, .true.)
            call stats_write_xyavg_vel
            if (ltempeq) call stats_write_xyavg_temp
            if (lmoist)  call stats_write_xyavg_moist
            if (lrh)     call stats_write_xyavg_relative_humidity
          end if
        end if

        if(lydump) then
          call stats_compute_yavg_vel
          if (ltempeq) call stats_compute_yavg_temp
          if (lmoist)  call stats_compute_yavg_moist
          if (lrh)     call stats_compute_yavg_relative_humidity
          if (nsv>0)   call stats_compute_yavg_scalar
          if (myidy==0) then
            call writestat_nc(ncidy, 'time', timee, nrecy, .true.)
            call stats_write_yavg_vel
            if (ltempeq) call stats_write_yavg_temp
            if (lmoist)  call stats_write_yavg_moist
            if (lrh)     call stats_write_yavg_relative_humidity
            if (nsv>0)   call stats_write_yavg_scalar
          end if
        end if

        if(ltreedump) then
          call stats_compute_tree_vel
          if (ltempeq) call stats_compute_tree_temp
          if (lmoist)  call stats_compute_tree_moist
          if (nsv>0)   call stats_compute_tree_scalar
        end if
        
        tsamplep = dt
      else
        tsamplep = tsamplep + dt
      endif

      if ( (lstatstavgdump .or. ltreedump) &
           .and. tstatsdumpp >= tstatsdump ) then    ! at every stats dump time instance
        dumpcount = dumpcount + 1
        if (myid==0) then
          write(*,*) "---------------------------------"
          write(*,*) "Writing time average statistics"
          write(*,*) "stats dump count ::: ", dumpcount
          write(*,*) "timee ::: ", timee
          write(*,*) "---------------------------------"
        end if
        
        if(ltdump) then
          if (myidy == 0) call writestat_nc(ncidt, 'time', timee, nrect, .true.)
          call stats_write_tavg
        end if
        if (ltislicedump) call stats_write_tavg_islice
        if (ltjslicedump) call stats_write_tavg_jslice
        if (ltkslicedump) call stats_write_tavg_kslice

        if(lxytdump) then
          call stats_compute_xytavg_vel
          if (ltempeq) call stats_compute_xytavg_temp
          if (lmoist)  call stats_compute_xytavg_moist
          if (lrh)     call stats_compute_xytavg_relative_humidity
          if (myid==0) then
            call writestat_nc(ncidxyt, 'time', timee, nrecxyt, .true.)
            call stats_write_xytavg_vel
            if (ltempeq) call stats_write_xytavg_temp
            if (lmoist)  call stats_write_xytavg_moist
            if (lrh)     call stats_write_xytavg_relative_humidity
          end if
        end if

        if(lytdump) then
          call stats_compute_ytavg_vel
          if (ltempeq) call stats_compute_ytavg_temp
          if (lmoist)  call stats_compute_ytavg_moist
          if (lrh)     call stats_compute_ytavg_relative_humidity
          if (nsv>0)   call stats_compute_ytavg_scalar
          if (myidy==0) then
            call writestat_nc(ncidyt, 'time', timee, nrecyt, .true.)
            call stats_write_ytavg_vel
            if (ltempeq) call stats_write_ytavg_temp
            if (lmoist)  call stats_write_ytavg_moist
            if (lrh)     call stats_write_ytavg_relative_humidity
            if (nsv>0)   call stats_write_ytavg_scalar
          end if
        end if

        if(ltreedump) then
          if (myidy == 0) call writestat_nc(ncidtree, 'time', timee, nrectree, .true.)
          call stats_write_tree_vel
          if (ltempeq) call stats_write_tree_temp
          if (lmoist)  call stats_write_tree_moist
          if (nsv>0)   call stats_write_tree_scalar
        end if

        tstatsdumpp = dt
        tsamplep = dt

        if(tstatsgap>0.) then
          ! next averaging window starts after the gap, at tstatstart + tstatsgap
          ! relative to this dump (see stats_init); the current step does not
          ! belong to it, so the accumulation counters start from zero.
          tstatstart = tstatstart + tstatsdump + tstatsgap
          tstatsdumpp = 0.
          tsamplep = 0.
          !! note that if tstatsgap is used, stats_xy and stats_y will also be not written during the gap duration as the entire stats_main is skipped for the duration of the gap.
        end if

        if(lstatstavgdump) then
          call stats_reset_tavg_vel
          if (ltdump .or. ltkslicedump) call stats_reset_tavg_pedestrian_wind
          if (ltempeq) call stats_reset_tavg_temp
          if (lmoist)  call stats_reset_tavg_moist
          if (lrh)     call stats_reset_tavg_relative_humidity
        end if
        if(ltavg3d .or. lytdump) then
          if (nsv>0)   call stats_reset_tavg_scalar
        end if
        if(ltavg3d) then
          if ((lchem) .and. (nsv>2)) call stats_reset_tavg_PSS
        end if
        if (ltreedump) then
          call stats_reset_tree_vel
          if (ltempeq) call stats_reset_tree_temp
          if (lmoist)  call stats_reset_tree_moist
          if (nsv>0)   call stats_reset_tree_scalar
        end if

      else
        tstatsdumpp = tstatsdumpp + dt
      endif

    end subroutine stats_main


    !! ## %% Interpolated and sgs fields initialization routines
    subroutine stats_allocate_interp_and_sgs_vel
      implicit none
      allocate(uik(ib:ie,jb:je,kb:ke+kh))
      allocate(wik(ib:ie,jb:je,kb:ke+kh))
      allocate(vjk(ib:ie,jb:je,kb:ke+kh))
      allocate(wjk(ib:ie,jb:je,kb:ke+kh))
      allocate(uij(ib:ie,jb:je,kb:ke+kh))
      allocate(vij(ib:ie,jb:je,kb:ke+kh))
      allocate(uc(ib:ie,jb:je,kb:ke+kh))
      allocate(vc(ib:ie,jb:je,kb:ke+kh))
      allocate(wc(ib:ie,jb:je,kb:ke+kh))
      allocate(usgs(ib:ie,jb:je,kb:ke+kh))
      allocate(vsgs(ib:ie,jb:je,kb:ke+kh))
      allocate(wsgs(ib:ie,jb:je,kb:ke+kh))
    end subroutine stats_allocate_interp_and_sgs_vel

    subroutine stats_allocate_interp_and_sgs_temp
      implicit none
      allocate(tempnow(ib:ie,jb:je,kb:ke+kh))
      allocate(thli(ib:ie,jb:je,kb:ke+kh))
      allocate(thlj(ib:ie,jb:je,kb:ke+kh))
      allocate(thlk(ib:ie,jb:je,kb:ke+kh))
      allocate(thlsgs(ib:ie,jb:je,kb:ke+kh))
    end subroutine stats_allocate_interp_and_sgs_temp

    subroutine stats_calculate_air_temperature
      implicit none
      integer :: k
      do k = kb, ke+kh
        tempnow(:,:,k) = air_temperature(thlm(ib:ie,jb:je,k), ql0(ib:ie,jb:je,k), exnf(k))
      end do
    end subroutine stats_calculate_air_temperature

    subroutine stats_allocate_relative_humidity
      implicit none
      allocate(rhnow(ib:ie,jb:je,kb:ke+kh))
    end subroutine stats_allocate_relative_humidity

    subroutine stats_calculate_relative_humidity
      implicit none
      integer :: k
      do k = kb, ke+kh
        rhnow(:,:,k) = relative_humidity(qtm(ib:ie,jb:je,k), ql0(ib:ie,jb:je,k), tempnow(:,:,k), presf(k))
      end do
    end subroutine stats_calculate_relative_humidity

    subroutine stats_allocate_interp_and_sgs_moist
      implicit none
      allocate(qtk(ib:ie,jb:je,kb:ke+kh))
      allocate(qtsgs(ib:ie,jb:je,kb:ke+kh))
    end subroutine stats_allocate_interp_and_sgs_moist

    subroutine stats_allocate_interp_and_sgs_scalar
      implicit none
      allocate(svi(ib:ie,jb:je,kb:ke+kh,nsv))
      allocate(svj(ib:ie,jb:je,kb:ke+kh,nsv))
      allocate(svk(ib:ie,jb:je,kb:ke+kh,nsv))
      allocate(svsgs(ib:ie,jb:je,kb:ke+kh,nsv))
    end subroutine stats_allocate_interp_and_sgs_scalar
      

    !! ## %% Time averaging initialization routines
    subroutine stats_allocate_tavg_vel
      implicit none
      allocate(ut(ib:ie,jb:je,kb:ke+kh))   ; ut    = 0.;
      allocate(vt(ib:ie,jb:je,kb:ke+kh))   ; vt    = 0.;
      allocate(wt(ib:ie,jb:je,kb:ke+kh))   ; wt    = 0.;
      allocate(pt(ib:ie,jb:je,kb:ke+kh))   ; pt    = 0.;
      allocate(utik(ib:ie,jb:je,kb:ke+kh)) ; utik  = 0.;
      allocate(wtik(ib:ie,jb:je,kb:ke+kh)) ; wtik  = 0.;
      allocate(uwtik(ib:ie,jb:je,kb:ke+kh)); uwtik = 0.;
      allocate(vtjk(ib:ie,jb:je,kb:ke+kh)) ; vtjk  = 0.;
      allocate(wtjk(ib:ie,jb:je,kb:ke+kh)) ; wtjk  = 0.;
      allocate(vwtjk(ib:ie,jb:je,kb:ke+kh)); vwtjk = 0.;
      allocate(utij(ib:ie,jb:je,kb:ke+kh)) ; utij  = 0.;
      allocate(vtij(ib:ie,jb:je,kb:ke+kh)) ; vtij  = 0.;
      allocate(uvtij(ib:ie,jb:je,kb:ke+kh)); uvtij = 0.;
      allocate(utc(ib:ie,jb:je,kb:ke+kh))  ; utc   = 0.;
      allocate(vtc(ib:ie,jb:je,kb:ke+kh))  ; vtc   = 0.;
      allocate(wtc(ib:ie,jb:je,kb:ke+kh))  ; wtc   = 0.;
      allocate(uutc(ib:ie,jb:je,kb:ke+kh)) ; uutc  = 0.;
      allocate(vvtc(ib:ie,jb:je,kb:ke+kh)) ; vvtc  = 0.;
      allocate(wwtc(ib:ie,jb:je,kb:ke+kh)) ; wwtc  = 0.;
      allocate(usgst(ib:ie,jb:je,kb:ke+kh)); usgst = 0.;
      allocate(vsgst(ib:ie,jb:je,kb:ke+kh)); vsgst = 0.;
      allocate(wsgst(ib:ie,jb:je,kb:ke+kh)); wsgst = 0.;
    end subroutine stats_allocate_tavg_vel

    subroutine stats_allocate_tavg_pedestrian_wind
      implicit none
      integer :: h

      if (nreceptor_heights > 0) then
        allocate(wind_heights(nreceptor_heights))
        wind_heights = receptor_heights(1:nreceptor_heights)
      else
        allocate(wind_heights(1))
        wind_heights(1) = receptor_height
      end if
      allocate(ws_localt(ib:ie,jb:je,1:size(wind_heights))); ws_localt = 0.
      allocate(ws_10t   (ib:ie,jb:je)); ws_10t    = 0.
      allocate(ws_now   (ib:ie,jb:je)); ws_now    = 0.
      allocate(ws_local_valid(ib:ie,jb:je,1:size(wind_heights))); ws_local_valid = .false.
      allocate(ws_local_klo(size(wind_heights)), ws_local_khi(size(wind_heights)))
      allocate(ws_local_weight(size(wind_heights)), ws_local_available(size(wind_heights)))
      allocate(ws_10_valid   (ib:ie,jb:je)); ws_10_valid    = .false.

      do h = 1, size(wind_heights)
        call stats_find_vertical_bracket(wind_heights(h), ws_local_klo(h), ws_local_khi(h), &
                                         ws_local_weight(h), ws_local_available(h))
        if (ws_local_available(h)) then
          if (ws_local_klo(h) == ws_local_khi(h)) then
            ws_local_valid(:,:,h) = IIc(ib:ie,jb:je,ws_local_klo(h)) == 1
          else
            ws_local_valid(:,:,h) = (IIc(ib:ie,jb:je,ws_local_klo(h)) == 1) .and. &
                                     (IIc(ib:ie,jb:je,ws_local_khi(h)) == 1)
          end if
        else if (myid == 0) then
          write(0,'(a,f10.3,a)') 'WARNING: ws_local cannot be sampled at ', &
                                 wind_heights(h), ' m: outside the scalar-level range.'
        end if
      end do
      call stats_find_vertical_bracket(utci_wind_height, ws_10_klo, ws_10_khi, &
                                       ws_10_weight, ws_10_available)

      if (ws_10_available) then
        if (ws_10_klo == ws_10_khi) then
          ws_10_valid = IIc(ib:ie,jb:je,ws_10_klo) == 1
        else
          ws_10_valid = (IIc(ib:ie,jb:je,ws_10_klo) == 1) .and. &
                        (IIc(ib:ie,jb:je,ws_10_khi) == 1)
        end if
      else if (myid == 0) then
        write(0,*) 'WARNING: ws_10 cannot be sampled because z=10 m is outside the scalar-level range.'
      end if

      call ncinfo(pedestrianWindVars(1,:), 'ws_local', &
                  'Time-mean horizontal wind speed at configured height above model ground', 'm/s', 'tt0t')
      call ncinfo(pedestrianWindVars(2,:), 'ws_10', &
                  'Time-mean horizontal wind speed at z=10 m above model ground', 'm/s', 'tt0t')
    end subroutine stats_allocate_tavg_pedestrian_wind

    subroutine stats_find_vertical_bracket(height, klo, khi, weight, available)
      implicit none
      real,    intent(in)  :: height
      integer, intent(out) :: klo, khi
      real,    intent(out) :: weight
      logical, intent(out) :: available
      integer :: k
      real    :: tol

      klo = kb
      khi = kb
      weight = 0.
      available = .false.

      if (height < zf(kb) .or. height > zf(ke)) return

      do k = kb, ke
        tol = 100.*epsilon(1.)*max(1., abs(height), abs(zf(k)))
        if (abs(height-zf(k)) <= tol) then
          klo = k
          khi = k
          available = .true.
          return
        end if
      end do

      do k = kb, ke-1
        if (height > zf(k) .and. height < zf(k+1)) then
          klo = k
          khi = k+1
          weight = (height-zf(k))/(zf(k+1)-zf(k))
          available = .true.
          return
        end if
      end do
    end subroutine stats_find_vertical_bracket

    subroutine stats_ncdescription_tavg_vel
      implicit none
      !> Generate variable description for the quantities to be written in the time averaged NetCDF: stats.xxx.xxx.xxx.nc
      call ncinfo( tVars(ctrt+ 1,:), 'u'       , 'Streamwise velocity'        , 'm/s'       , 'mttt' )
      call ncinfo( tVars(ctrt+ 2,:), 'v'       , 'Spanwise velocity'          , 'm/s'       , 'tmtt' )
      call ncinfo( tVars(ctrt+ 3,:), 'w'       , 'Vertical velocity'          , 'm/s'       , 'ttmt' )
      call ncinfo( tVars(ctrt+ 4,:), 'p'       , 'Kinematic Pressure'         , 'm^2/s^2'   , 'tttt' )
      call ncinfo( tVars(ctrt+ 5,:), 'pabs'    , 'Hydrostatic absolute pressure', 'Pa'      , 'tttt' )

      call ncinfo( tVars(ctrt+ 6,:), 'upwp'    , 'Turbulent momentum flux'    , 'm^2/s^2'   , 'mtmt' )
      call ncinfo( tVars(ctrt+ 7,:), 'vpwp'    , 'Turbulent momentum flux'    , 'm^2/s^2'   , 'tmmt' )
      call ncinfo( tVars(ctrt+ 8,:), 'upvp'    , 'Turbulent momentum flux'    , 'm^2/s^2'   , 'mmtt' )

      call ncinfo( tVars(ctrt+ 9,:), 'upup'    , 'u variance - cell centered' , 'm^2/s^2'   , 'tttt' )
      call ncinfo( tVars(ctrt+10,:), 'vpvp'    , 'v variance - cell centered' , 'm^2/s^2'   , 'tttt' )
      call ncinfo( tVars(ctrt+11,:), 'wpwp'    , 'w variance - cell centered' , 'm^2/s^2'   , 'tttt' )
      call ncinfo( tVars(ctrt+12,:), 'tke'     , 'TKE - cell centered'        , 'm^2/s^2'   , 'tttt' )

      call ncinfo( tVars(ctrt+13,:), 'usgs'    , 'SGS u flux'                 , 'm^2/s^2'   , 'mtmt' )
      call ncinfo( tVars(ctrt+14,:), 'vsgs'    , 'SGS v flux'                 , 'm^2/s^2'   , 'tmmt' )
      call ncinfo( tVars(ctrt+15,:), 'wsgs'    , 'SGS normal stress'          , 'm^2/s^2'   , 'tttt' )
      ctrt = ctrt+15
    end subroutine stats_ncdescription_tavg_vel

    subroutine stats_allocate_tavg_temp
      implicit none
      allocate(thlt(ib:ie,jb:je,kb:ke+kh))   ; thlt    = 0.;
      allocate(tempt(ib:ie,jb:je,kb:ke+kh))  ; tempt   = 0.;
      allocate(thlti(ib:ie,jb:je,kb:ke+kh))  ; thlti   = 0.;
      allocate(thltj(ib:ie,jb:je,kb:ke+kh))  ; thltj   = 0.;
      allocate(thltk(ib:ie,jb:je,kb:ke+kh))  ; thltk   = 0.;
      allocate(uthlti(ib:ie,jb:je,kb:ke+kh)) ; uthlti  = 0.;
      allocate(vthltj(ib:ie,jb:je,kb:ke+kh)) ; vthltj  = 0.;
      allocate(wthltk(ib:ie,jb:je,kb:ke+kh)) ; wthltk  = 0.;
      allocate(thlthlt(ib:ie,jb:je,kb:ke+kh)); thlthlt = 0.;
      allocate(thlsgst(ib:ie,jb:je,kb:ke+kh)); thlsgst = 0.;
    end subroutine stats_allocate_tavg_temp
    subroutine stats_ncdescription_tavg_temp
      implicit none
      call ncinfo( tVars(ctrt+1,:) , 'thl'     , 'Liquid water potential temperature', 'K'         , 'tttt' )
      call ncinfo( tVars(ctrt+2,:) , 'upthlp'  , 'Turbulent heat flux in x'  , 'K m/s'     , 'mttt' )
      call ncinfo( tVars(ctrt+3,:) , 'vpthlp'  , 'Turbulent heat flux in y'  , 'K m/s'     , 'tmtt' )
      call ncinfo( tVars(ctrt+4,:) , 'wpthlp'  , 'Turbulent heat flux in z'  , 'K m/s'     , 'ttmt' )
      call ncinfo( tVars(ctrt+5,:) , 'thlpthlp', 'Temperature variance'      , 'K^2'       , 'tttt' )
      call ncinfo( tVars(ctrt+6,:) , 'thlsgs'  , 'SGS temperature flux'      , 'K m/s'     , 'ttmt' )
      call ncinfo( tVars(ctrt+7,:) , 'tha'     , 'Air temperature'            , 'K'         , 'tttt' )
      ctrt = ctrt+7
    end subroutine stats_ncdescription_tavg_temp

    subroutine stats_allocate_tavg_moist
      implicit none
      allocate(qtt(ib:ie,jb:je,kb:ke+kh))   ; qtt    = 0.;
      allocate(qlt(ib:ie,jb:je,kb:ke+kh))   ; qlt    = 0.;
      allocate(qttk(ib:ie,jb:je,kb:ke+kh))  ; qttk   = 0.;
      allocate(wqttk(ib:ie,jb:je,kb:ke+kh)) ; wqttk  = 0.;
      allocate(qtqtt(ib:ie,jb:je,kb:ke+kh)) ; qtqtt  = 0.;
      allocate(qtsgst(ib:ie,jb:je,kb:ke+kh)); qtsgst = 0.;
    end subroutine stats_allocate_tavg_moist
    subroutine stats_ncdescription_tavg_moist
      implicit none
      call ncinfo( tVars(ctrt+1,:) , 'qt'      , 'Total water specific humidity', 'kg/kg'     , 'tttt' )
      call ncinfo( tVars(ctrt+2,:) , 'wpqtp'   , 'Turbulent moisture flux'      , 'kg m/kg s' , 'ttmt' )
      call ncinfo( tVars(ctrt+3,:) , 'qtpqtp'  , 'Moisture variance'            , 'kg^2/kg^2' , 'tttt' )
      call ncinfo( tVars(ctrt+4,:) , 'qtsgs'   , 'SGS moisture flux'            , 'kg m/kg s' , 'ttmt' )
      call ncinfo( tVars(ctrt+5,:) , 'ql'      , 'Liquid-water specific humidity', 'kg/kg'    , 'tttt' )
      ctrt = ctrt+5
    end subroutine stats_ncdescription_tavg_moist

    subroutine stats_allocate_tavg_relative_humidity
      implicit none
      allocate(rht(ib:ie,jb:je,kb:ke+kh)); rht = 0.
    end subroutine stats_allocate_tavg_relative_humidity

    subroutine stats_ncdescription_tavg_relative_humidity
      implicit none
      call ncinfo(tVars(ctrt+1,:), 'rh', 'Relative humidity', '%', 'tttt')
      ctrt = ctrt+1
    end subroutine stats_ncdescription_tavg_relative_humidity

    subroutine stats_allocate_tavg_scalar
      implicit none
      allocate(svt(ib:ie,jb:je,kb:ke+kh,nsv))   ; svt    = 0.;
      allocate(svti(ib:ie,jb:je,kb:ke+kh,nsv))  ; svti   = 0.;
      allocate(svtj(ib:ie,jb:je,kb:ke+kh,nsv))  ; svtj   = 0.;
      allocate(svtk(ib:ie,jb:je,kb:ke+kh,nsv))  ; svtk   = 0.;
      allocate(usvti(ib:ie,jb:je,kb:ke+kh,nsv)) ; usvti  = 0.;
      allocate(vsvtj(ib:ie,jb:je,kb:ke+kh,nsv)) ; vsvtj  = 0.;
      allocate(wsvtk(ib:ie,jb:je,kb:ke+kh,nsv)) ; wsvtk  = 0.;
      allocate(svsvt(ib:ie,jb:je,kb:ke+kh,nsv)) ; svsvt  = 0.;
      allocate(svsgst(ib:ie,jb:je,kb:ke+kh,nsv)); svsgst = 0.;
    end subroutine stats_allocate_tavg_scalar
    subroutine stats_ncdescription_tavg_scalar
      implicit none
      integer :: n
      character(2) :: sid
      allocate(svtname(nsv))
      allocate(upsvptname(nsv))
      allocate(vpsvptname(nsv))
      allocate(wpsvptname(nsv))
      allocate(svpsvptname(nsv))
      allocate(svsgsname(nsv))
      do n = 1, nsv
        write (sid, '(I0)') n
        svtname(n)     = 's'//trim(sid)                        ! s1       at n = 1
        upsvptname(n)  = 'ups'//trim(sid)//'p'                 ! ups1p    at n = 1
        vpsvptname(n)  = 'vps'//trim(sid)//'p'                 ! vps1p    at n = 1
        wpsvptname(n)  = 'wps'//trim(sid)//'p'                 ! wps1p    at n = 1
        svpsvptname(n) = 's'//trim(sid)//'ps'//trim(sid)//'p'  ! s1ps1p   at n = 1
        svsgsname(n)   = 's'//trim(sid)//'sgs'                 ! s1sgs    at n = 1
        call ncinfo(tVars(ctrt+n,:)      , trim(svtname(n))    , 'Concentration field '//trim(sid)                     , 'g/m^3'  , 'tttt' )
        call ncinfo(tVars(ctrt+nsv+n,:)  , trim(upsvptname(n)) , 'Turbulent scalar flux along x for scalar_'//trim(sid), 'g/m^2s' , 'mttt' )
        call ncinfo(tVars(ctrt+2*nsv+n,:), trim(vpsvptname(n)) , 'Turbulent scalar flux along y for scalar_'//trim(sid), 'g/m^2s' , 'tmtt' )
        call ncinfo(tVars(ctrt+3*nsv+n,:), trim(wpsvptname(n)) , 'Turbulent scalar flux along z for scalar_'//trim(sid), 'g/m^2s' , 'ttmt' )
        call ncinfo(tVars(ctrt+4*nsv+n,:), trim(svpsvptname(n)), 'Concentration variance '//trim(sid)                  , 'g^2/m^6', 'tttt' )
        call ncinfo(tVars(ctrt+5*nsv+n,:), trim(svsgsname(n))  , 'SGS scalar flux along z for scalar_'//trim(sid)      , 'g/m^2s' , 'ttmt' )
      end do
      ctrt = ctrt+6*nsv
    end subroutine stats_ncdescription_tavg_scalar

    subroutine stats_init_tavg_PSS
      implicit none
      allocate(PSS(ib:ie,jb:je,kb:ke+kh))
      allocate(PSSt(ib:ie,jb:je,kb:ke+kh)); PSSt = 0.;
      call ncinfo( tVars(ctrt+1,:) , 'PSS'      , 'PSS defect'                , 'gm/s'      , 'tttt' )
      ctrt = ctrt+1
    end subroutine stats_init_tavg_PSS

    subroutine stats_createnc_tavg
      implicit none
      filenamet = 'stats_t.xxx.xxx.nc'
      filenamet(9:11)  = cmyidx
      filenamet(13:15) = cexpnr

      nrect = 0
      if (myidy==0) then
        call open_nc(filenamet, ncidt, nrect, n1=xdim, n2=jtot, n3=zdim)
        if (nrect==0) then
          call define_nc(ncidt, 1, timeVar)
          call writestat_dims_nc(ncidt)
        end if
        call define_nc(ncidt, tVarsCount, tVars)
        call stats_define_pedestrian_wind(ncidt)
      end if
    end subroutine stats_createnc_tavg

    subroutine stats_define_pedestrian_wind(ncid)
      implicit none
      integer, intent(in) :: ncid

      if (size(wind_heights) == 1) then
        call define_nc(ncid, size(pedestrianWindVars,1), pedestrianWindVars)
        call write_pedestrian_wind_metadata_nc(ncid, wind_heights(1))
      else
        call define_nc(ncid, 1, pedestrianWindVars(2:2,:))
        call write_pedestrian_wind_heights_nc(ncid, wind_heights)
      end if
    end subroutine stats_define_pedestrian_wind

    subroutine stats_reset_tavg_vel
      implicit none
      ut = 0.; vt = 0.; wt = 0.; pt = 0.
      utik  = 0. ; wtik  = 0. ; uwtik = 0.
      vtjk  = 0. ; wtjk  = 0. ; vwtjk = 0.
      utij  = 0. ; vtij  = 0. ; uvtij = 0.
      utc   = 0. ; vtc   = 0. ; wtc   = 0.
      uutc  = 0. ; vvtc  = 0. ; wwtc  = 0.
      usgst = 0. ; vsgst = 0. ; wsgst = 0.
    end subroutine stats_reset_tavg_vel

    subroutine stats_reset_tavg_pedestrian_wind
      implicit none
      ws_localt = 0.
      ws_10t = 0.
    end subroutine stats_reset_tavg_pedestrian_wind

    subroutine stats_reset_tavg_temp
      implicit none
      thlt = 0.; tempt = 0.
      thlti   = 0. ; thltj   = 0. ; thltk = 0.
      uthlti  = 0. ; vthltj  = 0. ; wthltk = 0.
      thlthlt = 0. ; thlsgst = 0.
    end subroutine stats_reset_tavg_temp

    subroutine stats_reset_tavg_moist
      implicit none
      qtt = 0.; qlt = 0.; qttk = 0.; wqttk = 0.; qtqtt = 0.; qtsgst = 0.
    end subroutine stats_reset_tavg_moist

    subroutine stats_reset_tavg_relative_humidity
      implicit none
      rht = 0.
    end subroutine stats_reset_tavg_relative_humidity

    subroutine stats_reset_tavg_scalar
      implicit none
      svt = 0.; svti = 0.; svtj = 0.; svtk = 0.
      usvti = 0. ; vsvtj  = 0.; wsvtk = 0.
      svsvt = 0. ; svsgst = 0.
    end subroutine stats_reset_tavg_scalar

    subroutine stats_reset_tavg_PSS
      implicit none
      PSSt = 0.
    end subroutine stats_reset_tavg_PSS


    !! ## %% Time, y and x averaging initialization routines
    subroutine stats_init_xytavg_vel
      implicit none
      allocate(uxyt(kb:ke+kh))
      allocate(vxyt(kb:ke+kh))
      allocate(wxyt(kb:ke+kh))
      allocate(pxyt(kb:ke+kh))
      allocate(upwpxytik(kb:ke+kh))
      allocate(vpwpxytjk(kb:ke+kh))
      allocate(upvpxytij(kb:ke+kh))
      allocate(uwxytik(kb:ke+kh))
      allocate(vwxytjk(kb:ke+kh))
      allocate(uvxytij(kb:ke+kh))
      allocate(uuxyti(kb:ke+kh))
      allocate(vvxytj(kb:ke+kh))
      allocate(wwxytk(kb:ke+kh))
      allocate(upupxytc(kb:ke+kh))
      allocate(vpvpxytc(kb:ke+kh))
      allocate(wpwpxytc(kb:ke+kh))
      allocate(tkexytc(kb:ke+kh))
      allocate(usgsxyt(kb:ke+kh))
      allocate(vsgsxyt(kb:ke+kh))
      allocate(wsgsxyt(kb:ke+kh))

      call ncinfo( xytVars(ctrxyt+ 1,:), 'u'        , 'Streamwise velocity'        , 'm/s'       , 'tt' )
      call ncinfo( xytVars(ctrxyt+ 2,:), 'v'        , 'Spanwise velocity'          , 'm/s'       , 'tt' )
      call ncinfo( xytVars(ctrxyt+ 3,:), 'w'        , 'Vertical velocity'          , 'm/s'       , 'mt' )
      call ncinfo( xytVars(ctrxyt+ 4,:), 'p'        , 'Kinematic Pressure'         , 'm^2/s^2'   , 'tt' )
      call ncinfo( xytVars(ctrxyt+ 5,:), 'upwp'     , 'Turbulent mom. flux'        , 'm^2/s^2'   , 'mt' )
      call ncinfo( xytVars(ctrxyt+ 6,:), 'vpwp'     , 'Turbulent mom. flux'        , 'm^2/s^2'   , 'mt' )
      call ncinfo( xytVars(ctrxyt+ 7,:), 'upvp'     , 'Turbulent mom. flux'        , 'm^2/s^2'   , 'tt' )
      call ncinfo( xytVars(ctrxyt+ 8,:), 'uw'       , 'Dispersive mom. flux'       , 'm^2/s^2'   , 'mt' )
      call ncinfo( xytVars(ctrxyt+ 9,:), 'vw'       , 'Dispersive mom. flux'       , 'm^2/s^2'   , 'mt' )
      call ncinfo( xytVars(ctrxyt+10,:), 'uv'       , 'Dispersive mom. flux'       , 'm^2/s^2'   , 'tt' )
      call ncinfo( xytVars(ctrxyt+11,:), 'uu'       , 'Dispersive mom. flux'       , 'm^2/s^2'   , 'tt' )
      call ncinfo( xytVars(ctrxyt+12,:), 'vv'       , 'Dispersive mom. flux'       , 'm^2/s^2'   , 'tt' )
      call ncinfo( xytVars(ctrxyt+13,:), 'ww'       , 'Dispersive mom. flux'       , 'm^2/s^2'   , 'mt' )
      call ncinfo( xytVars(ctrxyt+14,:), 'upup'     , 'u variance - cell centered' , 'm^2/s^2'   , 'tt' )
      call ncinfo( xytVars(ctrxyt+15,:), 'vpvp'     , 'v variance - cell centered' , 'm^2/s^2'   , 'tt' )
      call ncinfo( xytVars(ctrxyt+16,:), 'wpwp'     , 'w variance - cell centered' , 'm^2/s^2'   , 'tt' )
      call ncinfo( xytVars(ctrxyt+17,:), 'tke'      , 'TKE - cell centered'        , 'm^2/s^2'   , 'tt' )
      call ncinfo( xytVars(ctrxyt+18,:), 'usgs'     , 'SGS mom. flux'              , 'm^2/s^2'   , 'mt' )
      call ncinfo( xytVars(ctrxyt+19,:), 'vsgs'     , 'SGS mom. flux'              , 'm^2/s^2'   , 'mt' )
      call ncinfo( xytVars(ctrxyt+20,:), 'wsgs'     , 'SGS normal stress'          , 'm^2/s^2'   , 'tt' )
      call ncinfo( xytVars(ctrxyt+21,:), 'pabs'     , 'Hydrostatic absolute pressure', 'Pa'      , 'tt' )
      ctrxyt = ctrxyt+21
    end subroutine stats_init_xytavg_vel

    subroutine stats_init_xytavg_temp
      implicit none
      allocate(thlxyt(kb:ke+kh))
      allocate(tempxyt(kb:ke+kh))
      allocate(wpthlpxytk(kb:ke+kh))
      allocate(wthlxytk(kb:ke+kh))
      allocate(thlpthlpxyt(kb:ke+kh))
      allocate(thlsgsxyt(kb:ke+kh))
      call ncinfo( xytVars(ctrxyt+ 1,:), 'thl'      , 'Liquid water potential temperature', 'K'         , 'tt' )
      call ncinfo( xytVars(ctrxyt+ 2,:), 'wpthlp'   , 'Turbulent heat flux'      , 'K m/s'     , 'mt' )
      call ncinfo( xytVars(ctrxyt+ 3,:), 'wthl'     , 'Dispersive heat flux'     , 'K m/s'     , 'mt' )
      call ncinfo( xytVars(ctrxyt+ 4,:), 'thlpthlp' , 'Temp. variance'           , 'K^2'       , 'tt' )
      call ncinfo( xytVars(ctrxyt+ 5,:), 'thlsgs'   , 'SGS heat flux'            , 'K m/s'     , 'mt' )
      call ncinfo( xytVars(ctrxyt+ 6,:), 'tha'      , 'Air temperature'          , 'K'         , 'tt' )
      ctrxyt = ctrxyt+6
    end subroutine stats_init_xytavg_temp

    subroutine stats_init_xytavg_moist
      implicit none
      allocate(qtxyt(kb:ke+kh))
      allocate(qlxyt(kb:ke+kh))
      allocate(wpqtpxytk(kb:ke+kh))
      allocate(wqtxytk(kb:ke+kh))
      allocate(qtpqtpxyt(kb:ke+kh))
      allocate(qtsgsxyt(kb:ke+kh))
      call ncinfo( xytVars(ctrxyt+ 1,:), 'qt'       , 'Total water specific humidity', 'kg/kg'     , 'tt' )
      call ncinfo( xytVars(ctrxyt+ 2,:), 'wpqtp'    , 'Turbulent moisture flux'      , 'kg m/kg s' , 'mt' )
      call ncinfo( xytVars(ctrxyt+ 3,:), 'wqt'      , 'Dispersive moisture flux'     , 'kg m/kg s' , 'mt' )
      call ncinfo( xytVars(ctrxyt+ 4,:), 'qtpqtp'   , 'Moisture variance'            , 'kg^2/kg^2' , 'tt' )
      call ncinfo( xytVars(ctrxyt+ 5,:), 'qtsgs'    , 'SGS moisture flux'            , 'kg m/kg s' , 'mt' )
      call ncinfo( xytVars(ctrxyt+ 6,:), 'ql'       , 'Liquid-water specific humidity', 'kg/kg'    , 'tt' )
      ctrxyt = ctrxyt+6
    end subroutine stats_init_xytavg_moist

    subroutine stats_init_xytavg_relative_humidity
      implicit none
      allocate(rhxyt(kb:ke+kh))
      call ncinfo(xytVars(ctrxyt+1,:), 'rh', 'Relative humidity', '%', 'tt')
      ctrxyt = ctrxyt+1
    end subroutine stats_init_xytavg_relative_humidity

    subroutine stats_createnc_xytavg
      implicit none
      filenamexyt = 'stats_xyt.xxx.nc'
      filenamexyt(11:13) = cexpnr

      nrecxyt = 0
      if (myid==0) then
        call open_nc(filenamexyt, ncidxyt, nrecxyt, n3=zdim)
        if (nrecxyt==0) then
          call define_nc(ncidxyt, 1,  timeVar)
          call writestat_dims_nc(ncidxyt)
        end if
        call define_nc(ncidxyt, xytVarsCount, xytVars)
      end if
    end subroutine stats_createnc_xytavg


    !! ## %% y and x averaging initialization routines
    subroutine stats_init_xyavg_vel
      implicit none
      allocate(uxy(kb:ke+kh))
      allocate(vxy(kb:ke+kh))
      allocate(wxy(kb:ke+kh))
      allocate(pxy(kb:ke+kh))
      allocate(upwpxyik(kb:ke+kh))
      allocate(vpwpxyjk(kb:ke+kh))
      allocate(upvpxyij(kb:ke+kh))
      allocate(uwxyik(kb:ke+kh))
      allocate(uxyik(kb:ke+kh))
      allocate(wxyik(kb:ke+kh))
      allocate(vwxyjk(kb:ke+kh))
      allocate(vxyjk(kb:ke+kh))
      allocate(wxyjk(kb:ke+kh))
      allocate(uvxyij(kb:ke+kh))
      allocate(uxyij(kb:ke+kh))
      allocate(vxyij(kb:ke+kh))
      allocate(uuxyi(kb:ke+kh))
      allocate(vvxyj(kb:ke+kh))
      allocate(wwxyk(kb:ke+kh))
      allocate(usgsxy(kb:ke+kh))
      allocate(vsgsxy(kb:ke+kh))
      allocate(wsgsxy(kb:ke+kh))

      call ncinfo( xyVars(ctrxy+ 1,:), 'u'        , 'Streamwise velocity'      , 'm/s'       , 'tt' )
      call ncinfo( xyVars(ctrxy+ 2,:), 'v'        , 'Spanwise velocity'        , 'm/s'       , 'tt' )
      call ncinfo( xyVars(ctrxy+ 3,:), 'w'        , 'Vertical velocity'        , 'm/s'       , 'mt' )
      call ncinfo( xyVars(ctrxy+ 4,:), 'p'        , 'Kinematic Pressure'       , 'm^2/s^2'   , 'tt' )
      call ncinfo( xyVars(ctrxy+ 5,:), 'upwp'     , 'Turbulent mom. flux'      , 'm^2/s^2'   , 'mt' )
      call ncinfo( xyVars(ctrxy+ 6,:), 'vpwp'     , 'Turbulent mom. flux'      , 'm^2/s^2'   , 'mt' )
      call ncinfo( xyVars(ctrxy+ 7,:), 'upvp'     , 'Turbulent mom. flux'      , 'm^2/s^2'   , 'tt' )
      call ncinfo( xyVars(ctrxy+ 8,:), 'uw'       , 'Advective mom. flux'      , 'm^2/s^2'   , 'mt' )
      call ncinfo( xyVars(ctrxy+ 9,:), 'vw'       , 'Advective mom. flux'      , 'm^2/s^2'   , 'mt' )
      call ncinfo( xyVars(ctrxy+10,:), 'uv'       , 'Advective mom. flux'      , 'm^2/s^2'   , 'tt' )
      call ncinfo( xyVars(ctrxy+11,:), 'uu'       , 'Advective mom. flux'      , 'm^2/s^2'   , 'tt' )
      call ncinfo( xyVars(ctrxy+12,:), 'vv'       , 'Advective mom. flux'      , 'm^2/s^2'   , 'tt' )
      call ncinfo( xyVars(ctrxy+13,:), 'ww'       , 'Advective mom. flux'      , 'm^2/s^2'   , 'mt' )
      call ncinfo( xyVars(ctrxy+14,:), 'usgs'     , 'SGS mom. flux'            , 'm^2/s^2'   , 'mt' )
      call ncinfo( xyVars(ctrxy+15,:), 'vsgs'     , 'SGS mom. flux'            , 'm^2/s^2'   , 'mt' )
      call ncinfo( xyVars(ctrxy+16,:), 'wsgs'     , 'SGS normal stress'        , 'm^2/s^2'   , 'tt' )
      call ncinfo( xyVars(ctrxy+17,:), 'pabs'     , 'Hydrostatic absolute pressure', 'Pa'      , 'tt' )
      ctrxy = ctrxy+17
    end subroutine stats_init_xyavg_vel

    subroutine stats_init_xyavg_temp
      implicit none
      allocate(thlxy(kb:ke+kh))
      allocate(tempxy(kb:ke+kh))
      allocate(wpthlpxyk(kb:ke+kh))
      allocate(wthlxyk(kb:ke+kh))
      allocate(thlxyk(kb:ke+kh))
      allocate(thlsgsxy(kb:ke+kh))
      call ncinfo( xyVars(ctrxy+ 1,:), 'thl'      , 'Liquid water potential temperature', 'K'         , 'tt' )
      call ncinfo( xyVars(ctrxy+ 2,:), 'wpthlp'   , 'Turbulent heat flux'      , 'K m/s'     , 'mt' )
      call ncinfo( xyVars(ctrxy+ 3,:), 'wthl'     , 'Advective heat flux'      , 'K m/s'     , 'mt' )
      call ncinfo( xyVars(ctrxy+ 4,:), 'thlsgs'   , 'SGS heat flux'            , 'K m/s'     , 'mt' )
      call ncinfo( xyVars(ctrxy+ 5,:), 'tha'      , 'Air temperature'          , 'K'         , 'tt' )
      ctrxy = ctrxy+5
    end subroutine stats_init_xyavg_temp

    subroutine stats_init_xyavg_moist
      implicit none
      allocate(qtxy(kb:ke+kh))
      allocate(qlxy(kb:ke+kh))
      allocate(wpqtpxyk(kb:ke+kh))
      allocate(wqtxyk(kb:ke+kh))
      allocate(qtxyk(kb:ke+kh))
      allocate(qtsgsxy(kb:ke+kh))
      call ncinfo( xyVars(ctrxy+ 1,:), 'qt'       , 'Total water specific humidity', 'kg/kg'     , 'tt' )
      call ncinfo( xyVars(ctrxy+ 2,:), 'wpqtp'    , 'Turbulent moisture flux'      , 'kg m/kg s' , 'mt' )
      call ncinfo( xyVars(ctrxy+ 3,:), 'wqt'      , 'Advective moisture flux'      , 'kg m/kg s' , 'mt' )
      call ncinfo( xyVars(ctrxy+ 4,:), 'qtsgs'    , 'SGS moisture flux'            , 'kg m/kg s' , 'mt' )
      call ncinfo( xyVars(ctrxy+ 5,:), 'ql'       , 'Liquid-water specific humidity', 'kg/kg'    , 'tt' )
      ctrxy = ctrxy+5
    end subroutine stats_init_xyavg_moist

    subroutine stats_init_xyavg_relative_humidity
      implicit none
      allocate(rhxy(kb:ke+kh))
      call ncinfo(xyVars(ctrxy+1,:), 'rh', 'Relative humidity', '%', 'tt')
      ctrxy = ctrxy+1
    end subroutine stats_init_xyavg_relative_humidity

    subroutine stats_createnc_xyavg
      implicit none
      filenamexy = 'stats_xy.xxx.nc'
      filenamexy(10:12) = cexpnr

      nrecxy = 0
      if (myid==0) then
        call open_nc(filenamexy, ncidxy, nrecxy, n3=zdim)
        if (nrecxy==0) then
          call define_nc(ncidxy, 1,  timeVar)
          call writestat_dims_nc(ncidxy)
        end if
        call define_nc(ncidxy, xyVarsCount, xyVars)
      end if
    end subroutine stats_createnc_xyavg


    !! ## %% Time and y averaging initialization routines
    subroutine stats_init_ytavg_vel
      implicit none
      allocate(uyt(ib:ie,kb:ke))
      allocate(vyt(ib:ie,kb:ke))
      allocate(wyt(ib:ie,kb:ke))
      allocate(pyt(ib:ie,kb:ke))
      allocate(upwpytik(ib:ie,kb:ke))
      allocate(uwytik(ib:ie,kb:ke))
      allocate(upupytc(ib:ie,kb:ke))
      allocate(vpvpytc(ib:ie,kb:ke))
      allocate(wpwpytc(ib:ie,kb:ke))
      allocate(usgsyt(ib:ie,kb:ke))
      allocate(wsgsyt(ib:ie,kb:ke))

      call ncinfo( ytVars(ctryt+ 1,:), 'u'        , 'Streamwise velocity'        , 'm/s'       , 'm0tt' )
      call ncinfo( ytVars(ctryt+ 2,:), 'v'        , 'Spanwise velocity'          , 'm/s'       , 't0tt' )
      call ncinfo( ytVars(ctryt+ 3,:), 'w'        , 'Vertical velocity'          , 'm/s'       , 't0mt' )
      call ncinfo( ytVars(ctryt+ 4,:), 'p'        , 'Kinematic Pressure'         , 'm^2/s^2'   , 't0tt' )
      call ncinfo( ytVars(ctryt+ 5,:), 'upwp'     , 'Turbulent mom. flux'        , 'm^2/s^2'   , 'm0mt' )
      call ncinfo( ytVars(ctryt+ 6,:), 'uw'       , 'Dispersive mom. flux'       , 'm^2/s^2'   , 'm0mt' )
      call ncinfo( ytVars(ctryt+ 7,:), 'upup'     , 'u variance - cell centered' , 'm^2/s^2'   , 't0tt' )
      call ncinfo( ytVars(ctryt+ 8,:), 'vpvp'     , 'v variance - cell centered' , 'm^2/s^2'   , 't0tt' )
      call ncinfo( ytVars(ctryt+ 9,:), 'wpwp'     , 'w variance - cell centered' , 'm^2/s^2'   , 't0tt' )
      call ncinfo( ytVars(ctryt+10,:), 'usgs'     , 'SGS mom. flux'              , 'm^2/s^2'   , 'm0mt' )
      call ncinfo( ytVars(ctryt+11,:), 'wsgs'     , 'SGS normal stress'          , 'm^2/s^2'   , 't0tt' )
      call ncinfo( ytVars(ctryt+12,:), 'pabs'     , 'Hydrostatic absolute pressure', 'Pa'      , 't0tt' )
      ctryt = ctryt+12
    end subroutine stats_init_ytavg_vel

    subroutine stats_init_ytavg_temp
      implicit none
      allocate(thlyt(ib:ie,kb:ke))
      allocate(tempyt(ib:ie,kb:ke))
      allocate(wpthlpytk(ib:ie,kb:ke))
      allocate(wthlytk(ib:ie,kb:ke))
      allocate(thlpthlpyt(ib:ie,kb:ke))
      allocate(thlsgsyt(ib:ie,kb:ke))
      call ncinfo( ytVars(ctryt+ 1,:), 'thl'      , 'Liquid water potential temperature', 'K'         , 't0tt' )
      call ncinfo( ytVars(ctryt+ 2,:), 'wpthlp'   , 'Turbulent heat flux'      , 'K m/s'     , 't0mt' )
      call ncinfo( ytVars(ctryt+ 3,:), 'wthl'     , 'Dispersive heat flux'     , 'K m/s'     , 't0mt' )
      call ncinfo( ytVars(ctryt+ 4,:), 'thlpthlp' , 'Temp. variance'           , 'K^2'       , 't0tt' )
      call ncinfo( ytVars(ctryt+ 5,:), 'thlsgs'   , 'SGS heat flux'            , 'K m/s'     , 't0mt' )
      call ncinfo( ytVars(ctryt+ 6,:), 'tha'      , 'Air temperature'          , 'K'         , 't0tt' )
      ctryt = ctryt+6
    end subroutine stats_init_ytavg_temp

    subroutine stats_init_ytavg_moist
      implicit none
      allocate(qtyt(ib:ie,kb:ke))
      allocate(qlyt(ib:ie,kb:ke))
      allocate(wpqtpytk(ib:ie,kb:ke))
      allocate(wqtytk(ib:ie,kb:ke))
      allocate(qtpqtpyt(ib:ie,kb:ke))
      allocate(qtsgsyt(ib:ie,kb:ke))
      call ncinfo( ytVars(ctryt+ 1,:), 'qt'       , 'Total water specific humidity', 'kg/kg'     , 't0tt' )
      call ncinfo( ytVars(ctryt+ 2,:), 'wpqtp'    , 'Turbulent moisture flux'      , 'kg m/kg s' , 't0mt' )
      call ncinfo( ytVars(ctryt+ 3,:), 'wqt'      , 'Dispersive moisture flux'     , 'kg m/kg s' , 't0mt' )
      call ncinfo( ytVars(ctryt+ 4,:), 'qtpqtp'   , 'Moisture variance'            , 'kg^2/kg^2' , 't0tt' )
      call ncinfo( ytVars(ctryt+ 5,:), 'qtsgs'    , 'SGS moisture flux'            , 'kg m/kg s' , 't0mt' )
      call ncinfo( ytVars(ctryt+ 6,:), 'ql'       , 'Liquid-water specific humidity', 'kg/kg'    , 't0tt' )
      ctryt = ctryt+6
    end subroutine stats_init_ytavg_moist

    subroutine stats_init_ytavg_relative_humidity
      implicit none
      allocate(rhyt(ib:ie,kb:ke))
      call ncinfo(ytVars(ctryt+1,:), 'rh', 'Relative humidity', '%', 't0tt')
      ctryt = ctryt+1
    end subroutine stats_init_ytavg_relative_humidity

    subroutine stats_init_ytavg_scalar
      integer :: n
      character(2) :: sid
      allocate(svytname(nsv))
      allocate(wpsvpytname(nsv))
      allocate(wsvytname(nsv))
      allocate(svpsvpytname(nsv))
      allocate(svsgsytname(nsv))
      allocate(svyt(ib:ie,kb:ke,nsv))
      allocate(wpsvpytk(ib:ie,kb:ke,nsv))
      allocate(wsvytk(ib:ie,kb:ke,nsv))
      allocate(svpsvpyt(ib:ie,kb:ke,nsv))
      allocate(svsgsyt(ib:ie,kb:ke,nsv))
      do n = 1, nsv
        write (sid, '(I0)') n
        svytname(n)     = 's'//trim(sid)                        ! s1       at n = 1
        wpsvpytname(n)  = 'wps'//trim(sid)//'p'                 ! wps1p    at n = 1
        wsvytname(n)    = 'ws'//trim(sid)                       ! ws1      at n = 1
        svpsvpytname(n) = 's'//trim(sid)//'ps'//trim(sid)//'p'  ! s1ps1p   at n = 1
        svsgsytname(n)  = 's'//trim(sid)//'sgs'                 ! s1sgs    at n = 1
        call ncinfo(ytVars(ctryt+n,:)      , trim(svytname(n))    , 'Concentration field '//trim(sid)   , 'g/m^3'  , 't0tt' )
        call ncinfo(ytVars(ctryt+nsv+n,:)  , trim(wpsvpytname(n)) , 'Turbulent scalar flux '//trim(sid) , 'g/m^2s' , 't0mt' )
        call ncinfo(ytVars(ctryt+2*nsv+n,:), trim(wsvytname(n))   , 'Dispersive scalar flux '//trim(sid), 'g/m^2s' , 't0mt' )
        call ncinfo(ytVars(ctryt+3*nsv+n,:), trim(svpsvpytname(n)), 'Concentration variance '//trim(sid), 'g^2/m^6', 't0tt' )
        call ncinfo(ytVars(ctryt+4*nsv+n,:), trim(svsgsytname(n)) , 'SGS scalar flux '//trim(sid)       , 'g/m^2s' , 't0mt' )
      end do
      ctryt = ctryt+5*nsv
    end subroutine stats_init_ytavg_scalar

    subroutine stats_createnc_ytavg
      implicit none
      filenameyt = 'stats_yt.xxx.xxx.nc'
      filenameyt(10:12)  = cmyidx
      filenameyt(14:16) = cexpnr

      nrecyt = 0
      if (myidy==0) then
        call open_nc(filenameyt, ncidyt, nrecyt, n1=xdim, n3=zdim)
        if (nrecyt==0) then
          call define_nc(ncidyt, 1,  timeVar)
          call writestat_dims_nc(ncidyt)
        end if
        call define_nc(ncidyt, ytVarsCount, ytVars)
      end if
    end subroutine stats_createnc_ytavg


    !! ## %% y averaging initialization routines
    subroutine stats_init_yavg_vel
      implicit none
      allocate(uy(ib:ie,kb:ke))
      allocate(vy(ib:ie,kb:ke))
      allocate(wy(ib:ie,kb:ke))
      allocate(py(ib:ie,kb:ke))
      allocate(upwpyik(ib:ie,kb:ke))
      allocate(uwyik(ib:ie,kb:ke))
      allocate(uyik(ib:ie,kb:ke))
      allocate(wyik(ib:ie,kb:ke))
      allocate(usgsy(ib:ie,kb:ke))
      allocate(wsgsy(ib:ie,kb:ke))
      call ncinfo( yVars(ctry+ 1,:), 'u'        , 'Streamwise velocity'      , 'm/s'       , 'm0tt' )
      call ncinfo( yVars(ctry+ 2,:), 'v'        , 'Spanwise velocity'        , 'm/s'       , 't0tt' )
      call ncinfo( yVars(ctry+ 3,:), 'w'        , 'Vertical velocity'        , 'm/s'       , 't0mt' )
      call ncinfo( yVars(ctry+ 4,:), 'p'        , 'Kinematic Pressure'       , 'm^2/s^2'   , 't0tt' )
      call ncinfo( yVars(ctry+ 5,:), 'upwp'     , 'Turbulent mom. flux'      , 'm^2/s^2'   , 'm0mt' )
      call ncinfo( yVars(ctry+ 6,:), 'uw'       , 'Advective mom. flux'      , 'm^2/s^2'   , 'm0mt' )
      call ncinfo( yVars(ctry+ 7,:), 'usgs'     , 'SGS mom. flux'            , 'm^2/s^2'   , 'm0mt' )
      call ncinfo( yVars(ctry+ 8,:), 'wsgs'     , 'SGS normal stress'        , 'm^2/s^2'   , 't0tt' )
      call ncinfo( yVars(ctry+ 9,:), 'pabs'     , 'Hydrostatic absolute pressure', 'Pa'      , 't0tt' )
      ctry = ctry+9
    end subroutine stats_init_yavg_vel

    subroutine stats_init_yavg_temp
      implicit none
      allocate(thly(ib:ie,kb:ke))
      allocate(tempy(ib:ie,kb:ke))
      allocate(wpthlpyk(ib:ie,kb:ke))
      allocate(wthlyk(ib:ie,kb:ke))
      allocate(thlyk(ib:ie,kb:ke))
      allocate(thlsgsy(ib:ie,kb:ke))
      call ncinfo( yVars(ctry+ 1,:), 'thl'      , 'Liquid water potential temperature', 'K'         , 't0tt' )
      call ncinfo( yVars(ctry+ 2,:), 'wpthlp'   , 'Turbulent heat flux'      , 'K m/s'     , 't0mt' )
      call ncinfo( yVars(ctry+ 3,:), 'wthl'     , 'Advective heat flux'      , 'K m/s'     , 't0mt' )
      call ncinfo( yVars(ctry+ 4,:), 'thlsgs'   , 'SGS heat flux'            , 'K m/s'     , 't0mt' )
      call ncinfo( yVars(ctry+ 5,:), 'tha'      , 'Air temperature'          , 'K'         , 't0tt' )
      ctry = ctry+5
    end subroutine stats_init_yavg_temp

    subroutine stats_init_yavg_moist
      implicit none
      allocate(qty(ib:ie,kb:ke))
      allocate(qly(ib:ie,kb:ke))
      allocate(wpqtpyk(ib:ie,kb:ke))
      allocate(wqtyk(ib:ie,kb:ke))
      allocate(qtyk(ib:ie,kb:ke))
      allocate(qtsgsy(ib:ie,kb:ke))
      call ncinfo( yVars(ctry+ 1,:), 'qt'       , 'Total water specific humidity', 'kg/kg'     , 't0tt' )
      call ncinfo( yVars(ctry+ 2,:), 'wpqtp'    , 'Turbulent moisture flux'      , 'kg m/kg s' , 't0mt' )
      call ncinfo( yVars(ctry+ 3,:), 'wqt'      , 'Advective moisture flux'      , 'kg m/kg s' , 't0mt' )
      call ncinfo( yVars(ctry+ 4,:), 'qtsgs'    , 'SGS moisture flux'            , 'kg m/kg s' , 't0mt' )
      call ncinfo( yVars(ctry+ 5,:), 'ql'       , 'Liquid-water specific humidity', 'kg/kg'    , 't0tt' )
      ctry = ctry+5
    end subroutine stats_init_yavg_moist

    subroutine stats_init_yavg_relative_humidity
      implicit none
      allocate(rhy(ib:ie,kb:ke))
      call ncinfo(yVars(ctry+1,:), 'rh', 'Relative humidity', '%', 't0tt')
      ctry = ctry+1
    end subroutine stats_init_yavg_relative_humidity

    subroutine stats_init_yavg_scalar
      integer :: n
      character(2) :: sid
      allocate(svyname(nsv))
      allocate(wpsvpyname(nsv))
      allocate(wsvyname(nsv))
      allocate(svsgsyname(nsv))
      allocate(svy(ib:ie,kb:ke,nsv))
      allocate(wpsvpyk(ib:ie,kb:ke,nsv))
      allocate(wsvyk(ib:ie,kb:ke,nsv))
      allocate(svyk(ib:ie,kb:ke,nsv))
      allocate(svsgsy(ib:ie,kb:ke,nsv))
      do n = 1, nsv
        write (sid, '(I0)') n
        svyname(n)     = 's'//trim(sid)                      ! s1       at n = 1
        wpsvpyname(n)  = 'wps'//trim(sid)//'p'               ! wps1p    at n = 1
        wsvyname(n)    = 'ws'//trim(sid)                     ! ws1      at n = 1
        svsgsyname(n)  = 's'//trim(sid)//'sgs'               ! s1sgs    at n = 1
        call ncinfo(yVars(ctry+n,:)      , trim(svyname(n))    , 'Concentration field '//trim(sid)   , 'g/m^3'  , 't0tt' )
        call ncinfo(yVars(ctry+nsv+n,:)  , trim(wpsvpyname(n)) , 'Turbulent scalar flux '//trim(sid) , 'g/m^2s' , 't0mt' )
        call ncinfo(yVars(ctry+2*nsv+n,:), trim(wsvyname(n))   , 'Advective scalar flux '//trim(sid) , 'g/m^2s' , 't0mt' )
        call ncinfo(yVars(ctry+3*nsv+n,:), trim(svsgsyname(n)) , 'SGS scalar flux '//trim(sid)       , 'g/m^2s' , 't0mt' )
      end do
      ctry = ctry+4*nsv
    end subroutine stats_init_yavg_scalar

    subroutine stats_createnc_yavg
      implicit none
      filenamey = 'stats_y.xxx.xxx.nc'
      filenamey(9:11)  = cmyidx
      filenamey(13:15) = cexpnr
      
      nrecy = 0
      if (myidy==0) then
        call open_nc(filenamey, ncidy, nrecy, n1=xdim, n3=zdim)
        if (nrecy==0) then
          call define_nc(ncidy, 1,  timeVar)
          call writestat_dims_nc(ncidy)
        end if
        call define_nc(ncidy, yVarsCount, yVars)
      end if
    end subroutine stats_createnc_yavg


    !! ## %% time averaging tree data initialization routines
    subroutine stats_init_tree_vel
      implicit none
      allocate(tr_ut(ib:ie,jb:je,kb:ke))     ; tr_ut     = 0.;
      allocate(tr_vt(ib:ie,jb:je,kb:ke))     ; tr_vt     = 0.;
      allocate(tr_wt(ib:ie,jb:je,kb:ke))     ; tr_wt     = 0.;
      call ncinfo( treeVars(ctrtree+ 1,:), 'tr_u'      , 'Drag in x'            , 'm/s^2'   , 'mttt' )
      call ncinfo( treeVars(ctrtree+ 2,:), 'tr_v'      , 'Drag in y'            , 'm/s^2'   , 'tmtt' )
      call ncinfo( treeVars(ctrtree+ 3,:), 'tr_w'      , 'Drag in z'            , 'm/s^2'   , 'ttmt' )
      ctrtree = ctrtree+3
    end subroutine stats_init_tree_vel

    subroutine stats_init_tree_temp
      implicit none
      allocate(tr_thlt(ib:ie,jb:je,kb:ke))   ; tr_thlt   = 0.;
      call ncinfo( treeVars(ctrtree+ 1,:), 'tr_thl'    , 'Temp source/ sink'    , 'K/s'     , 'tttt' )
      ctrtree = ctrtree+1
    end subroutine stats_init_tree_temp

    subroutine stats_init_tree_moist
      implicit none
      allocate(tr_qtt(ib:ie,jb:je,kb:ke))    ; tr_qtt    = 0.;
      allocate(tr_qtRt(ib:ie,jb:je,kb:ke))   ; tr_qtRt   = 0.;
      allocate(tr_qtAt(ib:ie,jb:je,kb:ke))   ; tr_qtAt   = 0.;
      allocate(tr_omegat(ib:ie,jb:je,kb:ke)) ; tr_omegat = 0.;
      call ncinfo( treeVars(ctrtree+ 1,:), 'tr_qt'     , 'Moisture source sink' , '1/s'     , 'tttt' )
      call ncinfo( treeVars(ctrtree+ 2,:), 'tr_qtR'    , 'Moisture source sink' , '1/s'     , 'tttt' )
      call ncinfo( treeVars(ctrtree+ 3,:), 'tr_qtA'    , 'Moisture source sink' , '1/s'     , 'tttt' )
      call ncinfo( treeVars(ctrtree+ 4,:), 'tr_omega'  , 'Decoupling factor'    , '-'       , 'tttt' )
      ctrtree = ctrtree+4
    end subroutine stats_init_tree_moist

    subroutine stats_init_tree_scalar
      implicit none
      integer :: n
      character(2) :: sid
      allocate(svtreename(nsv))
      allocate(tr_svt(ib:ie,jb:je,kb:ke,nsv)); tr_svt = 0.;
      do n = 1, nsv
        write (sid, '(I0)') n
        svtreename(n) = 'tr_sv'//trim(sid)         ! tr_sv1       at n = 1
        call ncinfo( treeVars(ctrtree+ n,:), trim(svtreename(n)) , 'Scalar source sink '//trim(sid) , 'kg/m^3s' , 'tttt' )
      end do
      ctrtree = ctrtree+nsv
    end subroutine stats_init_tree_scalar

    subroutine stats_createnc_tree
      implicit none
      filenametree = 'stats_tree.xxx.xxx.nc'
      filenametree(12:14) = cmyidx
      filenametree(16:18) = cexpnr

      nrectree = 0
      if (myidy==0) then
        call open_nc(filenametree, ncidtree, nrectree, n1=xdim, n2=jtot, n3=zdim)
        if (nrectree==0) then
          call define_nc(ncidtree, 1, timeVar)
          call writestat_dims_nc(ncidtree)
        end if
        call define_nc(ncidtree, treeVarsCount, treeVars)
      end if

      allocate(tr_now(ib:ie,jb:je,kb:ke))

    end subroutine stats_createnc_tree

    subroutine stats_reset_tree_vel
      implicit none
      tr_ut = 0.; tr_vt = 0.; tr_wt = 0.
    end subroutine stats_reset_tree_vel

    subroutine stats_reset_tree_temp
      implicit none
      tr_thlt = 0.
    end subroutine stats_reset_tree_temp

    subroutine stats_reset_tree_moist
      implicit none
      tr_qtt = 0.; tr_qtRt = 0.; tr_qtAt = 0.; tr_omegat = 0.
    end subroutine stats_reset_tree_moist

    subroutine stats_reset_tree_scalar
      implicit none
      tr_svt = 0.
    end subroutine stats_reset_tree_scalar


    !! ## %% Interpolate variables at cell faces and compute sgs fluxes
    subroutine stats_interpolate_and_sgs_vel
      implicit none
      integer :: i, j, k

      !> Perform required interpolations to cell faces and centers
      call stats_interpolate_k(uik, um(ib:ie,jb:je,kb-kh:ke+kh))
      call stats_interpolate_i(wik, wm(ib-ih:ie,jb:je,kb:ke+kh))
      call stats_interpolate_k(vjk, vm(ib:ie,jb:je,kb-kh:ke+kh))
      call stats_interpolate_j(wjk, wm(ib:ie,jb-jh:je,kb:ke+kh))
      call stats_interpolate_j(uij, um(ib:ie,jb-jh:je,kb:ke+kh))
      call stats_interpolate_i(vij, vm(ib-ih:ie,jb:je,kb:ke+kh))
      do k=kb,ke+kh
        do j=jb,je
          do i=ib,ie
            uc (i,j,k) = 0.5*        (um(i+1,j,k)        + um(i,j,k))
            vc (i,j,k) = 0.5*        (vm(i,j+1,k)        + vm(i,j,k))
            if (k==ke+kh) then
              wc(i,j,k) = wc(i,j,k-1)
            else
              wc(i,j,k) = 0.5*        (wm(i,j,k+1)        + wm(i,j,k))
            end if 
          end do
        end do
      end do

      call stats_sgs_momentum(usgs, vsgs, wsgs)
    end subroutine stats_interpolate_and_sgs_vel

    subroutine stats_interpolate_and_sgs_temp
      implicit none
      call stats_interpolate_i(thli, thlm(ib-ih:ie,jb:je,kb:ke+kh))
      call stats_interpolate_j(thlj, thlm(ib:ie,jb-jh:je,kb:ke+kh))
      call stats_interpolate_k(thlk, thlm(ib:ie,jb:je,kb-kh:ke+kh))
      call stats_compute_sgs(thlsgs, thlm(ib:ie,jb:je,kb-kh:ke+kh), ekh(ib:ie,jb:je,kb-kh:ke+kh))
    end subroutine stats_interpolate_and_sgs_temp

    subroutine stats_interpolate_and_sgs_moist
      implicit none
      call stats_interpolate_k(qtk, qtm(ib:ie,jb:je,kb-kh:ke+kh))
      call stats_compute_sgs(qtsgs, qtm(ib:ie,jb:je,kb-kh:ke+kh), ekh(ib:ie,jb:je,kb-kh:ke+kh))
    end subroutine stats_interpolate_and_sgs_moist

    subroutine stats_interpolate_and_sgs_scalar
      implicit none
      integer :: n
      do n = 1, nsv
        call stats_interpolate_i(svi(:,:,:,n), svm(ib-ih:ie,jb:je,kb:ke+kh,n))
        call stats_interpolate_j(svj(:,:,:,n), svm(ib:ie,jb-jh:je,kb:ke+kh,n))
        call stats_interpolate_k(svk(:,:,:,n), svm(ib:ie,jb:je,kb-kh:ke+kh,n))
        call stats_compute_sgs(svsgs(:,:,:,n), svm(ib:ie,jb:je,kb-kh:ke+kh,n), ekh(ib:ie,jb:je,kb-kh:ke+kh))
      end do
    end subroutine stats_interpolate_and_sgs_scalar


    !! Low level routines
    subroutine stats_interpolate_i(vari,varm)
      implicit none
      real, intent(inout) :: vari(ib:ie,jb:je,kb:ke+kh)
      real, intent(in)    :: varm(ib-ih:ie,jb:je,kb:ke+kh)
      integer :: i
      do i=ib,ie
        vari(i,:,:) = 0.5*dxhi(i)*(varm(i,:,:)*dxf(i-1) + varm(i-1,:,:)*dxf(i))
      end do
    end subroutine stats_interpolate_i

    subroutine stats_interpolate_j(varj,varm)
      implicit none
      real, intent(inout) :: varj(ib:ie,jb:je,kb:ke+kh)
      real, intent(in)    :: varm(ib:ie,jb-jh:je,kb:ke+kh)
      integer :: j
      do j=jb,je
        varj(:,j,:) = 0.5*(varm(:,j,:) + varm(:,j-1,:))
      end do
    end subroutine stats_interpolate_j

    subroutine stats_interpolate_k(vark,varm)
      implicit none
      real, intent(inout) :: vark(ib:ie,jb:je,kb:ke+kh)
      real, intent(in)    :: varm(ib:ie,jb:je,kb-kh:ke+kh)
      integer :: k
      do k=kb,ke+kh
        vark(:,:,k) = 0.5*dzhi(k)*(varm(:,:,k)*dzf(k-1) + varm(:,:,k-1)*dzf(k))
      end do
    end subroutine stats_interpolate_k

    !> SGS flux of a scalar at the w-levels, -K_h dphi/dz with K_h interpolated
    !! to the w-level as in modsubgrid (diffc), so that resolved + SGS fluxes add
    !! up and a down-gradient flux is negative. Filled kb..ke+kh: the top level
    !! is read by the ke+kh averages.
    subroutine stats_compute_sgs(varsgs,varm,ekvar)
      implicit none
      real, intent(out) :: varsgs(ib:ie,jb:je,kb:ke+kh)
      real, intent(in)  :: varm(ib:ie,jb:je,kb-kh:ke+kh)
      real, intent(in)  :: ekvar(ib:ie,jb:je,kb-kh:ke+kh)
      integer :: k
      varsgs = 0.
      do k=kb,ke+kh
        varsgs(:,:,k) = -0.5 * (dzf(k-1)*ekvar(:,:,k) + dzf(k)*ekvar(:,:,k-1)) &
                             * (varm(:,:,k)-varm(:,:,k-1)) * dzh2i(k)
      end do
    end subroutine stats_compute_sgs

    !> SGS momentum fluxes with the solver's stencils and sign (down-gradient is
    !! negative). usgs and vsgs are the shear stresses tau_13 and tau_23 at the
    !! uw and vw cell corners (w-levels); wsgs is the normal stress
    !! tau_33 = -2 K_m dw/dz, which lives at the cell centre (filled kb..ke,
    !! zero at ke+kh).
    subroutine stats_sgs_momentum(usgs_o, vsgs_o, wsgs_o)
      implicit none
      real, intent(out) :: usgs_o(ib:ie,jb:je,kb:ke+kh)
      real, intent(out) :: vsgs_o(ib:ie,jb:je,kb:ke+kh)
      real, intent(out) :: wsgs_o(ib:ie,jb:je,kb:ke+kh)
      integer :: i, j, k
      real    :: emom

      usgs_o = 0.; vsgs_o = 0.; wsgs_o = 0.
      do k=kb,ke+kh
        do j=jb,je
          do i=ib,ie
            ! interps ekm to cell corner (uw)
            emom = ( dzf(k-1) * ( ekm(i,j,k)*dxf(i-1)  + ekm(i-1,j,k)*dxf(i) )  + &
                     dzf(k)   * ( ekm(i,j,k-1)*dxf(i-1) + ekm(i-1,j,k-1)*dxf(i) ) )*dxhi(i) * dzhiq(k)
            usgs_o(i,j,k) = -emom * ( (um(i,j,k)-um(i,j,k-1)) *dzhi(k) &
                                     +(wm(i,j,k)-wm(i-1,j,k)) *dxhi(i))

            ! interps ekm to cell corner (vw)
            emom = ( dzf(k-1) * ( ekm(i,j,k)   + ekm(i,j-1,k) )  + &
                     dzf(k)   * ( ekm(i,j,k-1) + ekm(i,j-1,k-1) ) ) * dzhiq(k)
            vsgs_o(i,j,k) = -emom * ( (vm(i,j,k)-vm(i,j,k-1)) *dzhi(k) &
                                     +(wm(i,j,k)-wm(i,j-1,k)) *dyi)
          end do
        end do
      end do

      do k=kb,ke
        do j=jb,je
          do i=ib,ie
            wsgs_o(i,j,k) = -2. * ekm(i,j,k) * (wm(i,j,k+1)-wm(i,j,k)) * dzfi(k)
          end do
        end do
      end do
    end subroutine stats_sgs_momentum

    !> All SGS fluxes the statistics write, from the current um/vm/wm/thlm/qtm
    !! and ekm/ekh, into caller-provided arrays. Public so the in-solver test
    !! (tests_sgs_statistics) can check them against the tendencies of
    !! modsubgrid without going through the statistics files. thlsgs/qtsgs are
    !! zero when ltempeq/lmoist is off.
    subroutine stats_sgs_fluxes(usgs_o, vsgs_o, wsgs_o, thlsgs_o, qtsgs_o)
      implicit none
      real, intent(out) :: usgs_o(ib:ie,jb:je,kb:ke+kh)
      real, intent(out) :: vsgs_o(ib:ie,jb:je,kb:ke+kh)
      real, intent(out) :: wsgs_o(ib:ie,jb:je,kb:ke+kh)
      real, intent(out) :: thlsgs_o(ib:ie,jb:je,kb:ke+kh)
      real, intent(out) :: qtsgs_o(ib:ie,jb:je,kb:ke+kh)

      call stats_sgs_momentum(usgs_o, vsgs_o, wsgs_o)
      thlsgs_o = 0.
      qtsgs_o  = 0.
      if (ltempeq) call stats_compute_sgs(thlsgs_o, thlm(ib:ie,jb:je,kb-kh:ke+kh), ekh(ib:ie,jb:je,kb-kh:ke+kh))
      if (lmoist)  call stats_compute_sgs(qtsgs_o,  qtm(ib:ie,jb:je,kb-kh:ke+kh),  ekh(ib:ie,jb:je,kb-kh:ke+kh))
    end subroutine stats_sgs_fluxes


    !! ## %% Time averaging computations routines
    subroutine stats_compute_tavg_vel
      implicit none 
      call stats_compute_tavg(ut, um(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(vt, vm(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(wt, wm(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(pt, pres0(ib:ie,jb:je,kb:ke+kh))

      call stats_compute_tavg(utik , uik)
      call stats_compute_tavg(wtik , wik)
      call stats_compute_tavg(uwtik, wik*uik)

      call stats_compute_tavg(vtjk , vjk)
      call stats_compute_tavg(wtjk , wjk)
      call stats_compute_tavg(vwtjk, vjk*wjk)

      call stats_compute_tavg(utij , uij)
      call stats_compute_tavg(vtij , vij)
      call stats_compute_tavg(uvtij, uij*vij)

      call stats_compute_tavg(utc , uc(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(vtc , vc(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(wtc , wc(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(uutc, uc(ib:ie,jb:je,kb:ke+kh)*uc(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(vvtc, vc(ib:ie,jb:je,kb:ke+kh)*vc(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(wwtc, wc(ib:ie,jb:je,kb:ke+kh)*wc(ib:ie,jb:je,kb:ke+kh))

      call stats_compute_tavg(usgst,  usgs)
      call stats_compute_tavg(vsgst,  vsgs)
      call stats_compute_tavg(wsgst,  wsgs)
    end subroutine stats_compute_tavg_vel

    subroutine stats_compute_tavg_pedestrian_wind
      implicit none
      integer :: h

      do h = 1, size(wind_heights)
        if (.not. ws_local_available(h)) cycle
        call stats_horizontal_speed_at_height(ws_local_klo(h), ws_local_khi(h), ws_local_weight(h), &
                                              ws_local_valid(:,:,h), ws_now)
        call stats_compute_tavg(ws_localt(:,:,h), ws_now)
      end do

      if (ws_10_available) then
        call stats_horizontal_speed_at_height(ws_10_klo, ws_10_khi, ws_10_weight, &
                                              ws_10_valid, ws_now)
        call stats_compute_tavg(ws_10t, ws_now)
      end if
    end subroutine stats_compute_tavg_pedestrian_wind

    subroutine stats_horizontal_speed_at_height(klo, khi, weight, valid, speed)
      implicit none
      integer, intent(in)  :: klo, khi
      real,    intent(in)  :: weight
      logical, intent(in)  :: valid(ib:ie,jb:je)
      real,    intent(out) :: speed(ib:ie,jb:je)
      integer :: i, j
      real    :: uheight, vheight

      speed = 0.
      do j = jb, je
        do i = ib, ie
          if (.not. valid(i,j)) cycle
          if (klo == khi) then
            uheight = uc(i,j,klo)
            vheight = vc(i,j,klo)
          else
            uheight = (1.-weight)*uc(i,j,klo) + weight*uc(i,j,khi)
            vheight = (1.-weight)*vc(i,j,klo) + weight*vc(i,j,khi)
          end if
          speed(i,j) = sqrt(uheight*uheight + vheight*vheight)
        end do
      end do
    end subroutine stats_horizontal_speed_at_height

    subroutine stats_compute_tavg_temp
      implicit none
      call stats_compute_tavg(thlt   , thlm(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(tempt  , tempnow)
      call stats_compute_tavg(thlti  , thli)
      call stats_compute_tavg(thltj  , thlj)
      call stats_compute_tavg(thltk  , thlk)
      call stats_compute_tavg(uthlti , um(ib:ie,jb:je,kb:ke+kh)*thli)
      call stats_compute_tavg(vthltj , vm(ib:ie,jb:je,kb:ke+kh)*thlj)
      call stats_compute_tavg(wthltk , wm(ib:ie,jb:je,kb:ke+kh)*thlk)
      call stats_compute_tavg(thlthlt, thlm(ib:ie,jb:je,kb:ke+kh)*thlm(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(thlsgst, thlsgs)
    end subroutine stats_compute_tavg_temp

    subroutine stats_compute_tavg_moist
      implicit none
      call stats_compute_tavg(qtt   , qtm(ib:ie,jb:je,kb:ke+kh) )
      call stats_compute_tavg(qlt   , ql0(ib:ie,jb:je,kb:ke+kh) )
      call stats_compute_tavg(qttk  , qtk)
      call stats_compute_tavg(wqttk , wm(ib:ie,jb:je,kb:ke+kh)*qtk)
      call stats_compute_tavg(qtqtt , qtm(ib:ie,jb:je,kb:ke+kh)*qtm(ib:ie,jb:je,kb:ke+kh))
      call stats_compute_tavg(qtsgst, qtsgs)
    end subroutine stats_compute_tavg_moist

    subroutine stats_compute_tavg_relative_humidity
      implicit none
      call stats_compute_tavg(rht, rhnow)
    end subroutine stats_compute_tavg_relative_humidity

    subroutine stats_compute_tavg_scalar
      implicit none
      integer :: n
      do n = 1, nsv
        call stats_compute_tavg(svt(:,:,:,n)   , svm(ib:ie,jb:je,kb:ke+kh,n) )
        call stats_compute_tavg(svti(:,:,:,n)  , svi(:,:,:,n) )
        call stats_compute_tavg(svtj(:,:,:,n)  , svj(:,:,:,n) )
        call stats_compute_tavg(svtk(:,:,:,n)  , svk(:,:,:,n) )
        call stats_compute_tavg(usvti(:,:,:,n) , um(ib:ie,jb:je,kb:ke+kh)*svi(:,:,:,n) )
        call stats_compute_tavg(vsvtj(:,:,:,n) , vm(ib:ie,jb:je,kb:ke+kh)*svj(:,:,:,n) )
        call stats_compute_tavg(wsvtk(:,:,:,n) , wm(ib:ie,jb:je,kb:ke+kh)*svk(:,:,:,n) )
        call stats_compute_tavg(svsvt(:,:,:,n) , svm(ib:ie,jb:je,kb:ke+kh,n)*svm(ib:ie,jb:je,kb:ke+kh,n) )
        call stats_compute_tavg(svsgst(:,:,:,n), svsgs(:,:,:,n) )
      end do
    end subroutine stats_compute_tavg_scalar

    subroutine stats_compute_tavg_PSS
      implicit none
      integer :: i, j, k
      do k=kb,ke
        do j=jb,je
          do i=ib,ie
            if ((ABS(svm(i,j,k,2)) .gt. 1.e-40) .and. (IIc(i,j,k)==1)) then
              PSS(i,j,k) = ( ( (k1*(svm(i,j,k,1)/30.)*(svm(i,j,k,3)/48.))/(JNO2*(svm(i,j,k,2)/46.)) ) - 1 ) * 100
            end if
          end do
        end do
      end do
      call stats_compute_tavg(PSSt, PSS)
    end subroutine stats_compute_tavg_PSS

    !! Low level tavg routines
    subroutine stats_compute_tavg_1D(vart,var)
      implicit none
      real, intent(inout) :: vart(:)
      real, intent(in)    :: var(:)
      vart = ( vart*(tstatsdumpp-tsamplep) + var*tsamplep )*tstatsdumppi
    end subroutine stats_compute_tavg_1D
    subroutine stats_compute_tavg_2D(vart,var)
      implicit none
      real, intent(inout) :: vart(:,:)
      real, intent(in)    :: var(:,:)
      vart = ( vart*(tstatsdumpp-tsamplep) + var*tsamplep )*tstatsdumppi
    end subroutine stats_compute_tavg_2D
    subroutine stats_compute_tavg_3D(vart,var)
      implicit none
      real, intent(inout) :: vart(:,:,:)
      real, intent(in)    :: var(:,:,:)
      vart = ( vart*(tstatsdumpp-tsamplep) + var*tsamplep )*tstatsdumppi
    end subroutine stats_compute_tavg_3D


    !! ## %% Time, y and x averaging computations routines
    subroutine stats_compute_xytavg_vel
      implicit none
      !> Means
      call spatial_avg(uxyt,ut(ib:ie,jb:je,kb:ke+kh),kb,ke,IIu(ib:ie,jb:je,kb:ke+kh),IIus(kb:ke+kh),.false.)
      call spatial_avg(vxyt,vt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIv(ib:ie,jb:je,kb:ke+kh),IIvs(kb:ke+kh),.false.)
      call spatial_avg(wxyt,wt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
      call spatial_avg(pxyt,pt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)

      !> Turbulent fluxes
      call spatial_avg(upwpxytik,uwtik(ib:ie,jb:je,kb:ke+kh)-utik(ib:ie,jb:je,kb:ke+kh)*wtik(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuw(ib:ie,jb:je,kb:ke+kh),IIuws(kb:ke+kh),.true.)
      call spatial_avg(vpwpxytjk,vwtjk(ib:ie,jb:je,kb:ke+kh)-vtjk(ib:ie,jb:je,kb:ke+kh)*wtjk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIvw(ib:ie,jb:je,kb:ke+kh),IIvws(kb:ke+kh),.true.)
      call spatial_avg(upvpxytij,uvtij(ib:ie,jb:je,kb:ke+kh)-utij(ib:ie,jb:je,kb:ke+kh)*vtij(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuv(ib:ie,jb:je,kb:ke+kh),IIuvs(kb:ke+kh),.true.)

      !> Dispersive fluxes
      call spatial_avg(uwxytik,utik(ib:ie,jb:je,kb:ke+kh)*wtik(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuw(ib:ie,jb:je,kb:ke+kh),IIuws(kb:ke+kh),.true.)
      call spatial_avg(vwxytjk,vtjk(ib:ie,jb:je,kb:ke+kh)*wtjk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIvw(ib:ie,jb:je,kb:ke+kh),IIvws(kb:ke+kh),.true.)
      call spatial_avg(uvxytij,utij(ib:ie,jb:je,kb:ke+kh)*vtij(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuv(ib:ie,jb:je,kb:ke+kh),IIuvs(kb:ke+kh),.true.)
      call spatial_avg(uuxyti,ut(ib:ie,jb:je,kb:ke+kh)*ut(ib:ie,jb:je,kb:ke+kh),kb,ke,IIu(ib:ie,jb:je,kb:ke+kh),IIus(kb:ke+kh),.false.)
      call spatial_avg(vvxytj,vt(ib:ie,jb:je,kb:ke+kh)*vt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIv(ib:ie,jb:je,kb:ke+kh),IIvs(kb:ke+kh),.false.)
      call spatial_avg(wwxytk,wt(ib:ie,jb:je,kb:ke+kh)*wt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)

      !> Variances and TKE
      call spatial_avg(upupxytc,uutc(ib:ie,jb:je,kb:ke+kh)-utc(ib:ie,jb:je,kb:ke+kh)*utc(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(vpvpxytc,vvtc(ib:ie,jb:je,kb:ke+kh)-vtc(ib:ie,jb:je,kb:ke+kh)*vtc(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(wpwpxytc,wwtc(ib:ie,jb:je,kb:ke+kh)-wtc(ib:ie,jb:je,kb:ke+kh)*wtc(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(tkexytc,0.5*((wwtc(ib:ie,jb:je,kb:ke+kh)-wtc(ib:ie,jb:je,kb:ke+kh)*wtc(ib:ie,jb:je,kb:ke+kh))+(vvtc(ib:ie,jb:je,kb:ke+kh)-vtc(ib:ie,jb:je,kb:ke+kh)*vtc(ib:ie,jb:je,kb:ke+kh))+(uutc(ib:ie,jb:je,kb:ke+kh)-utc(ib:ie,jb:je,kb:ke+kh)*utc(ib:ie,jb:je,kb:ke+kh))),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)

      !> SGS fluxes
      call spatial_avg(usgsxyt,usgst(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuw(ib:ie,jb:je,kb:ke+kh),IIuws(kb:ke+kh),.true.)
      call spatial_avg(vsgsxyt,vsgst(ib:ie,jb:je,kb:ke+kh),kb,ke,IIvw(ib:ie,jb:je,kb:ke+kh),IIvws(kb:ke+kh),.true.)
      call spatial_avg(wsgsxyt,wsgst(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
    end subroutine stats_compute_xytavg_vel

    subroutine stats_compute_xytavg_temp
      implicit none
      call spatial_avg(thlxyt,thlt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(tempxyt,tempt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(wpthlpxytk,wthltk(ib:ie,jb:je,kb:ke+kh)-wt(ib:ie,jb:je,kb:ke+kh)*thltk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
      call spatial_avg(wthlxytk,wt(ib:ie,jb:je,kb:ke+kh)*thltk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
      call spatial_avg(thlpthlpxyt,thlthlt(ib:ie,jb:je,kb:ke+kh)-thlt(ib:ie,jb:je,kb:ke+kh)*thlt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(thlsgsxyt,thlsgst(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
    end subroutine stats_compute_xytavg_temp

    subroutine stats_compute_xytavg_moist
      implicit none
      call spatial_avg(qtxyt,qtt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(qlxyt,qlt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(wpqtpxytk,wqttk(ib:ie,jb:je,kb:ke+kh)-wt(ib:ie,jb:je,kb:ke+kh)*qttk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
      call spatial_avg(wqtxytk,wt(ib:ie,jb:je,kb:ke+kh)*qttk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
      call spatial_avg(qtpqtpxyt,qtqtt(ib:ie,jb:je,kb:ke+kh)-qtt(ib:ie,jb:je,kb:ke+kh)*qtt(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(qtsgsxyt,qtsgst(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
    end subroutine stats_compute_xytavg_moist

    subroutine stats_compute_xytavg_relative_humidity
      implicit none
      call spatial_avg(rhxyt,rht(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
    end subroutine stats_compute_xytavg_relative_humidity


    !! ## %% y and x averaging computations routines
    subroutine stats_compute_xyavg_vel
      implicit none
      !> Mean
      call spatial_avg(uxy,um(ib:ie,jb:je,kb:ke+kh),kb,ke,IIu(ib:ie,jb:je,kb:ke+kh),IIus(kb:ke+kh),.false.)
      call spatial_avg(vxy,vm(ib:ie,jb:je,kb:ke+kh),kb,ke,IIv(ib:ie,jb:je,kb:ke+kh),IIvs(kb:ke+kh),.false.)
      call spatial_avg(wxy,wm(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
      call spatial_avg(pxy,pres0(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)

      !> Advective fluxes and some necesseary mean
      call spatial_avg(uwxyik,uik(ib:ie,jb:je,kb:ke+kh)*wik(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuw(ib:ie,jb:je,kb:ke+kh),IIuws(kb:ke+kh),.true.)
      call spatial_avg(uxyik,uik(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuw(ib:ie,jb:je,kb:ke+kh),IIuws(kb:ke+kh),.true.)
      call spatial_avg(wxyik,wik(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuw(ib:ie,jb:je,kb:ke+kh),IIuws(kb:ke+kh),.true.)
      call spatial_avg(vwxyjk,vjk(ib:ie,jb:je,kb:ke+kh)*wjk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIvw(ib:ie,jb:je,kb:ke+kh),IIvws(kb:ke+kh),.true.)
      call spatial_avg(vxyjk,vjk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIvw(ib:ie,jb:je,kb:ke+kh),IIvws(kb:ke+kh),.true.)
      call spatial_avg(wxyjk,wjk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIvw(ib:ie,jb:je,kb:ke+kh),IIvws(kb:ke+kh),.true.)
      call spatial_avg(uvxyij,uij(ib:ie,jb:je,kb:ke+kh)*vij(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuv(ib:ie,jb:je,kb:ke+kh),IIuvs(kb:ke+kh),.true.)
      call spatial_avg(uxyij,uij(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuv(ib:ie,jb:je,kb:ke+kh),IIuvs(kb:ke+kh),.true.)
      call spatial_avg(vxyij,vij(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuv(ib:ie,jb:je,kb:ke+kh),IIuvs(kb:ke+kh),.true.)

      call spatial_avg(uuxyi,um(ib:ie,jb:je,kb:ke+kh)*um(ib:ie,jb:je,kb:ke+kh),kb,ke,IIu(ib:ie,jb:je,kb:ke+kh),IIus(kb:ke+kh),.true.)
      call spatial_avg(vvxyj,vm(ib:ie,jb:je,kb:ke+kh)*vm(ib:ie,jb:je,kb:ke+kh),kb,ke,IIv(ib:ie,jb:je,kb:ke+kh),IIvs(kb:ke+kh),.true.)
      call spatial_avg(wwxyk,wm(ib:ie,jb:je,kb:ke+kh)*wm(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)

      !> Turbulent fluxes (masked where the corner mask has no fluid point, e.g. kb)
      upwpxyik = uwxyik - uxyik*wxyik
      vpwpxyjk = vwxyjk - vxyjk*wxyjk
      upvpxyij = uvxyij - uxyij*vxyij
      where (IIuws(kb:ke+kh)==0) upwpxyik = -999.
      where (IIvws(kb:ke+kh)==0) vpwpxyjk = -999.
      where (IIuvs(kb:ke+kh)==0) upvpxyij = -999.

      !> SGS fluxes
      call spatial_avg(usgsxy,usgs(ib:ie,jb:je,kb:ke+kh),kb,ke,IIuw(ib:ie,jb:je,kb:ke+kh),IIuws(kb:ke+kh),.true.)
      call spatial_avg(vsgsxy,vsgs(ib:ie,jb:je,kb:ke+kh),kb,ke,IIvw(ib:ie,jb:je,kb:ke+kh),IIvws(kb:ke+kh),.true.)
      call spatial_avg(wsgsxy,wsgs(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
    end subroutine stats_compute_xyavg_vel

    subroutine stats_compute_xyavg_temp
      implicit none
      call spatial_avg(thlxy,thlm(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(tempxy,tempnow,kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(wthlxyk,wm(ib:ie,jb:je,kb:ke+kh)*thlk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
      call spatial_avg(thlxyk,thlk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
      wpthlpxyk = wthlxyk - wxy*thlxyk
      where (IIws(kb:ke+kh)==0) wpthlpxyk = -999.
      call spatial_avg(thlsgsxy,thlsgs(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
    end subroutine stats_compute_xyavg_temp

    subroutine stats_compute_xyavg_moist
      implicit none
      call spatial_avg(qtxy,qtm(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(qlxy,ql0(ib:ie,jb:je,kb:ke+kh),kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
      call spatial_avg(wqtxyk,wm(ib:ie,jb:je,kb:ke+kh)*qtk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
      call spatial_avg(qtxyk,qtk(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
      wpqtpxyk = wqtxyk - wxy*qtxyk
      where (IIws(kb:ke+kh)==0) wpqtpxyk = -999.
      call spatial_avg(qtsgsxy,qtsgs(ib:ie,jb:je,kb:ke+kh),kb,ke,IIw(ib:ie,jb:je,kb:ke+kh),IIws(kb:ke+kh),.true.)
    end subroutine stats_compute_xyavg_moist

    subroutine stats_compute_xyavg_relative_humidity
      implicit none
      call spatial_avg(rhxy,rhnow,kb,ke,IIc(ib:ie,jb:je,kb:ke+kh),IIcs(kb:ke+kh),.false.)
    end subroutine stats_compute_xyavg_relative_humidity


    !! ## %% Time and y averaging computations routines
    subroutine stats_compute_ytavg_vel
      implicit none
      !> Mean
      call spatial_avg(uyt,ut(ib:ie,jb:je,kb:ke),IIu(ib:ie,jb:je,kb:ke),IIut)
      call spatial_avg(vyt,vt(ib:ie,jb:je,kb:ke),IIv(ib:ie,jb:je,kb:ke),IIvt)
      call spatial_avg(wyt,wt(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
      call spatial_avg(pyt,pt(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)

      !> Turbulent fluxes
      call spatial_avg(upwpytik,uwtik(ib:ie,jb:je,kb:ke)-utik(ib:ie,jb:je,kb:ke)*wtik(ib:ie,jb:je,kb:ke),IIuw(ib:ie,jb:je,kb:ke),IIuwt)
      
      !> Dispersive fluxes
      call spatial_avg(uwytik,utik(ib:ie,jb:je,kb:ke)*wtik(ib:ie,jb:je,kb:ke),IIuw(ib:ie,jb:je,kb:ke),IIuwt)

      !> Variances
      call spatial_avg(upupytc,uutc(ib:ie,jb:je,kb:ke)-utc(ib:ie,jb:je,kb:ke)*utc(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(vpvpytc,vvtc(ib:ie,jb:je,kb:ke)-vtc(ib:ie,jb:je,kb:ke)*vtc(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(wpwpytc,wwtc(ib:ie,jb:je,kb:ke)-wtc(ib:ie,jb:je,kb:ke)*wtc(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)

      !> SGS fluxes
      call spatial_avg(usgsyt,usgst(ib:ie,jb:je,kb:ke),IIuw(ib:ie,jb:je,kb:ke),IIuwt)
      call spatial_avg(wsgsyt,wsgst(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
    end subroutine stats_compute_ytavg_vel

    subroutine stats_compute_ytavg_temp
      implicit none
      call spatial_avg(thlyt,thlt(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(tempyt,tempt(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(wpthlpytk,wthltk(ib:ie,jb:je,kb:ke)-wt(ib:ie,jb:je,kb:ke)*thltk(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
      call spatial_avg(wthlytk,wt(ib:ie,jb:je,kb:ke)*thltk(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
      call spatial_avg(thlpthlpyt,thlthlt(ib:ie,jb:je,kb:ke)-thlt(ib:ie,jb:je,kb:ke)*thlt(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(thlsgsyt,thlsgst(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
    end subroutine stats_compute_ytavg_temp

    subroutine stats_compute_ytavg_moist
      implicit none
      call spatial_avg(qtyt,qtt(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(qlyt,qlt(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(wpqtpytk,wqttk(ib:ie,jb:je,kb:ke)-wt(ib:ie,jb:je,kb:ke)*qttk(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
      call spatial_avg(wqtytk,wt(ib:ie,jb:je,kb:ke)*qttk(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
      call spatial_avg(qtpqtpyt,qtqtt(ib:ie,jb:je,kb:ke)-qtt(ib:ie,jb:je,kb:ke)*qtt(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(qtsgsyt,qtsgst(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
    end subroutine stats_compute_ytavg_moist

    subroutine stats_compute_ytavg_relative_humidity
      implicit none
      call spatial_avg(rhyt,rht(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
    end subroutine stats_compute_ytavg_relative_humidity

    subroutine stats_compute_ytavg_scalar
      implicit none
      integer :: n
      do n = 1, nsv
        call spatial_avg(svyt(:,:,n),svt(ib:ie,jb:je,kb:ke,n),IIc(ib:ie,jb:je,kb:ke),IIct)
        call spatial_avg(wpsvpytk(:,:,n),wsvtk(ib:ie,jb:je,kb:ke,n)-wt(ib:ie,jb:je,kb:ke)*svtk(ib:ie,jb:je,kb:ke,n),IIw(ib:ie,jb:je,kb:ke),IIwt)
        call spatial_avg(wsvytk(:,:,n),wt(ib:ie,jb:je,kb:ke)*svtk(ib:ie,jb:je,kb:ke,n),IIw(ib:ie,jb:je,kb:ke),IIwt)
        call spatial_avg(svpsvpyt(:,:,n),svsvt(ib:ie,jb:je,kb:ke,n)-svt(ib:ie,jb:je,kb:ke,n)*svt(ib:ie,jb:je,kb:ke,n),IIc(ib:ie,jb:je,kb:ke),IIct)
        call spatial_avg(svsgsyt(:,:,n),svsgst(ib:ie,jb:je,kb:ke,n),IIw(ib:ie,jb:je,kb:ke),IIwt)
      end do
    end subroutine stats_compute_ytavg_scalar


    !! ## %% y averaging computations routines
    subroutine stats_compute_yavg_vel
      implicit none
      !> Mean
      call spatial_avg(uy,um(ib:ie,jb:je,kb:ke),IIu(ib:ie,jb:je,kb:ke),IIut)
      call spatial_avg(vy,vm(ib:ie,jb:je,kb:ke),IIv(ib:ie,jb:je,kb:ke),IIvt)
      call spatial_avg(wy,wm(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
      call spatial_avg(py,pres0(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)

      !> Advective fluxes and some necesseary mean
      call spatial_avg(uwyik,uik(ib:ie,jb:je,kb:ke)*wik(ib:ie,jb:je,kb:ke),IIuw(ib:ie,jb:je,kb:ke),IIuwt)
      call spatial_avg(uyik,uik(ib:ie,jb:je,kb:ke),IIuw(ib:ie,jb:je,kb:ke),IIuwt)
      call spatial_avg(wyik,wik(ib:ie,jb:je,kb:ke),IIuw(ib:ie,jb:je,kb:ke),IIuwt)

      !> Turbulent fluxes
      upwpyik = uwyik - uyik*wyik
      where (IIuwt==0)
        upwpyik    = -999.0
      endwhere

      !> SGS fluxes
      call spatial_avg(usgsy,usgs(ib:ie,jb:je,kb:ke),IIuw(ib:ie,jb:je,kb:ke),IIuwt)
      call spatial_avg(wsgsy,wsgs(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
    end subroutine stats_compute_yavg_vel

    subroutine stats_compute_yavg_temp
      implicit none
      call spatial_avg(thly,thlm(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(tempy,tempnow(:,:,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(wthlyk,wm(ib:ie,jb:je,kb:ke)*thlk(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
      call spatial_avg(thlyk,thlk(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
      
      wpthlpyk = wthlyk - wy*thlyk
      where (IIwt==0)
        wpthlpyk  = -999.0
      endwhere
      
      call spatial_avg(thlsgsy,thlsgs(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
    end subroutine stats_compute_yavg_temp

    subroutine stats_compute_yavg_moist
      implicit none
      call spatial_avg(qty,qtm(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(qly,ql0(ib:ie,jb:je,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
      call spatial_avg(wqtyk,wm(ib:ie,jb:je,kb:ke)*qtk(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
      call spatial_avg(qtyk,qtk(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
      
      wpqtpyk = wqtyk - wy*qtyk
      where (IIwt==0)
        wpqtpyk  = -999.0
      endwhere

      call spatial_avg(qtsgsy,qtsgs(ib:ie,jb:je,kb:ke),IIw(ib:ie,jb:je,kb:ke),IIwt)
    end subroutine stats_compute_yavg_moist

    subroutine stats_compute_yavg_relative_humidity
      implicit none
      call spatial_avg(rhy,rhnow(:,:,kb:ke),IIc(ib:ie,jb:je,kb:ke),IIct)
    end subroutine stats_compute_yavg_relative_humidity

    subroutine stats_compute_yavg_scalar
      implicit none
      integer :: n
      do n = 1, nsv
        call spatial_avg(svy(:,:,n),svm(ib:ie,jb:je,kb:ke,n),IIc(ib:ie,jb:je,kb:ke),IIct)

        call spatial_avg(wsvyk(:,:,n),wm(ib:ie,jb:je,kb:ke)*svk(ib:ie,jb:je,kb:ke,n),IIw(ib:ie,jb:je,kb:ke),IIwt)
        call spatial_avg(svyk(:,:,n),svk(ib:ie,jb:je,kb:ke,n),IIw(ib:ie,jb:je,kb:ke),IIwt)

        wpsvpyk(:,:,n) = wsvyk(:,:,n) - wy*svyk(:,:,n)
        where (IIwt==0)
          wpsvpyk(:,:,n)  = -999.0
        endwhere

        call spatial_avg(svsgsy(:,:,n),svsgs(ib:ie,jb:je,kb:ke,n),IIw(ib:ie,jb:je,kb:ke),IIwt)
      end do
    end subroutine stats_compute_yavg_scalar


    !! ## %% Time averaging tree data computations routines
    subroutine stats_compute_tree_vel
      implicit none
      if (npts_u > 0) then
        call veg_to_3d_face(npts_u, ijk_u, veg_up, tr_now)
      else
        tr_now = 0.
      end if
      call stats_compute_tavg(tr_ut, tr_now)

      if (npts_v > 0) then
        call veg_to_3d_face(npts_v, ijk_v, veg_vp, tr_now)
      else
        tr_now = 0.
      end if
      call stats_compute_tavg(tr_vt, tr_now)

      if (npts_w > 0) then
        call veg_to_3d_face(npts_w, ijk_w, veg_wp, tr_now)
      else
        tr_now = 0.
      end if
      call stats_compute_tavg(tr_wt, tr_now)
    end subroutine stats_compute_tree_vel

    subroutine stats_compute_tree_temp
      implicit none
      call veg_to_3d_cell(vegp%thl, tr_now)
      call stats_compute_tavg(tr_thlt, tr_now)
    end subroutine stats_compute_tree_temp

    subroutine stats_compute_tree_moist
      implicit none 
      call veg_to_3d_cell(vegp%qt, tr_now)
      call stats_compute_tavg(tr_qtt, tr_now)

      call veg_to_3d_cell(vegp%qtR, tr_now)
      call stats_compute_tavg(tr_qtRt, tr_now)

      call veg_to_3d_cell(vegp%qtA, tr_now)
      call stats_compute_tavg(tr_qtAt, tr_now)

      call veg_to_3d_cell(vegp%omega, tr_now)
      call stats_compute_tavg(tr_omegat, tr_now)
    end subroutine stats_compute_tree_moist

    subroutine stats_compute_tree_scalar
      implicit none
      integer :: n
      do n = 1, nsv
        call veg_to_3d_sv(n, tr_now)
        call stats_compute_tavg(tr_svt(:,:,:,n), tr_now)
      end do
    end subroutine stats_compute_tree_scalar

    !> Expand a sparse face-staggered vegetation field into a full 3D array.
    !! Takes explicit npts/ijk so it can be used for u-, v- or w-faces.
    subroutine veg_to_3d_face(npts, ijk, field_sparse, field_3d)
      implicit none
      integer, intent(in)  :: npts
      integer, intent(in)  :: ijk(npts,3)
      real,    intent(in)  :: field_sparse(npts)
      real,    intent(out) :: field_3d(ib:ie,jb:je,kb:ke)
      integer :: m, i, j, k

      field_3d = 0.
      do m = 1, npts
        i = ijk(m,1)
        j = ijk(m,2)
        k = ijk(m,3)
        field_3d(i,j,k) = field_sparse(m)
      end do
    end subroutine veg_to_3d_face

    !> Expand a sparse cell-centred vegetation field into a full 3D array
    !! using the vegetation module's point list.
    subroutine veg_to_3d_cell(field_sparse, field_3d)
      implicit none
      real, intent(in)  :: field_sparse(:)
      real, intent(out) :: field_3d(ib:ie,jb:je,kb:ke)
      integer :: m, i, j, k

      field_3d = 0.
      do m = 1, veg%npts
        i = veg%ijk(m,1)
        j = veg%ijk(m,2)
        k = veg%ijk(m,3)
        field_3d(i,j,k) = field_sparse(m)
      end do
    end subroutine veg_to_3d_cell

    !> Expand one scalar component of the vegetation tendency array into a
    !! full 3D field for output.
    subroutine veg_to_3d_sv(component, field_3d)
      implicit none
      integer, intent(in)  :: component
      real,    intent(out) :: field_3d(ib:ie,jb:je,kb:ke)
      integer :: m, i, j, k

      field_3d = 0.
      do m = 1, veg%npts
        i = veg%ijk(m,1)
        j = veg%ijk(m,2)
        k = veg%ijk(m,3)
        field_3d(i,j,k) = vegp%sv(m,component)
      end do
    end subroutine veg_to_3d_sv


    !! ## %% Time averaged statistics writing routines 
    !> Fill fld with the time-averaged quantity `name` of the variable table,
    !> evaluated from the accumulators. The one place holding every expression,
    !> used by the 3-D writer and by the slice writers so that a slice is an
    !> exact sub-array of stats_t.
    subroutine stats_tavg_field(name, fld)
      implicit none
      character(*), intent(in)  :: name
      real,         intent(out) :: fld(ib:ie, jb:je, kb:ke)
      integer :: n, k

      select case (name)
      case ('u');        fld = ut(:,:,kb:ke)
      case ('v');        fld = vt(:,:,kb:ke)
      case ('w');        fld = wt(:,:,kb:ke)
      case ('p');        fld = pt(:,:,kb:ke)
      case ('pabs')
        do k = kb, ke
          fld(:,:,k) = presf(k)
        end do
      case ('upwp');     fld = uwtik(:,:,kb:ke) - utik(:,:,kb:ke)*wtik(:,:,kb:ke)
      case ('vpwp');     fld = vwtjk(:,:,kb:ke) - vtjk(:,:,kb:ke)*wtjk(:,:,kb:ke)
      case ('upvp');     fld = uvtij(:,:,kb:ke) - utij(:,:,kb:ke)*vtij(:,:,kb:ke)
      case ('upup');     fld = uutc(:,:,kb:ke) - utc(:,:,kb:ke)*utc(:,:,kb:ke)
      case ('vpvp');     fld = vvtc(:,:,kb:ke) - vtc(:,:,kb:ke)*vtc(:,:,kb:ke)
      case ('wpwp');     fld = wwtc(:,:,kb:ke) - wtc(:,:,kb:ke)*wtc(:,:,kb:ke)
      case ('tke');      fld = 0.5*( (uutc(:,:,kb:ke)-utc(:,:,kb:ke)*utc(:,:,kb:ke)) &
                                 + (vvtc(:,:,kb:ke)-vtc(:,:,kb:ke)*vtc(:,:,kb:ke)) &
                                 + (wwtc(:,:,kb:ke)-wtc(:,:,kb:ke)*wtc(:,:,kb:ke)) )
      case ('usgs');     fld = usgst(:,:,kb:ke)
      case ('vsgs');     fld = vsgst(:,:,kb:ke)
      case ('wsgs');     fld = wsgst(:,:,kb:ke)
      case ('thl');      fld = thlt(:,:,kb:ke)
      case ('tha');      fld = tempt(:,:,kb:ke)
      case ('upthlp');   fld = uthlti(:,:,kb:ke) - ut(:,:,kb:ke)*thlti(:,:,kb:ke)
      case ('vpthlp');   fld = vthltj(:,:,kb:ke) - vt(:,:,kb:ke)*thltj(:,:,kb:ke)
      case ('wpthlp');   fld = wthltk(:,:,kb:ke) - wt(:,:,kb:ke)*thltk(:,:,kb:ke)
      case ('thlpthlp'); fld = thlthlt(:,:,kb:ke) - thlt(:,:,kb:ke)*thlt(:,:,kb:ke)
      case ('thlsgs');   fld = thlsgst(:,:,kb:ke)
      case ('qt');       fld = qtt(:,:,kb:ke)
      case ('ql');       fld = qlt(:,:,kb:ke)
      case ('rh');       fld = rht(:,:,kb:ke)
      case ('wpqtp');    fld = wqttk(:,:,kb:ke) - wt(:,:,kb:ke)*qttk(:,:,kb:ke)
      case ('qtpqtp');   fld = qtqtt(:,:,kb:ke) - qtt(:,:,kb:ke)*qtt(:,:,kb:ke)
      case ('qtsgs');    fld = qtsgst(:,:,kb:ke)
      case ('PSS');      fld = PSSt(:,:,kb:ke)
      case default
        do n = 1, nsv
          if (name == trim(svtname(n))) then
            fld = svt(:,:,kb:ke,n);                                        return
          else if (name == trim(upsvptname(n))) then
            fld = usvti(:,:,kb:ke,n) - ut(:,:,kb:ke)*svti(:,:,kb:ke,n);    return
          else if (name == trim(vpsvptname(n))) then
            fld = vsvtj(:,:,kb:ke,n) - vt(:,:,kb:ke)*svtj(:,:,kb:ke,n);    return
          else if (name == trim(wpsvptname(n))) then
            fld = wsvtk(:,:,kb:ke,n) - wt(:,:,kb:ke)*svtk(:,:,kb:ke,n);    return
          else if (name == trim(svpsvptname(n))) then
            fld = svsvt(:,:,kb:ke,n) - svt(:,:,kb:ke,n)*svt(:,:,kb:ke,n);  return
          else if (name == trim(svsgsname(n))) then
            fld = svsgst(:,:,kb:ke,n)
            where (IIw(ib:ie,jb:je,kb:ke)==0) fld = -999.
            return
          end if
        end do
        write(0,*) 'ERROR stats_tavg_field: unknown time-averaged variable ', name
        stop 1
      end select
    end subroutine stats_tavg_field

    !> Full 3-D time averages: stats_t.xxx.xxx.nc
    subroutine stats_write_tavg
      implicit none
      integer :: n
      real, allocatable :: fld(:,:,:)
      allocate(fld(ib:ie, jb:je, kb:ke))
      do n = 1, tVarsCount
        call stats_tavg_field(trim(tVars(n,1)), fld)
        call writeoffset(ncidt, trim(tVars(n,1)), fld, nrect, xdim, ydim, zdim)
      end do
      deallocate(fld)

      call stats_write_pedestrian_wind(ncidt, nrect)
    end subroutine stats_write_tavg

    subroutine stats_write_pedestrian_wind(ncid, record)
      implicit none
      integer, intent(in) :: ncid, record
      real, allocatable :: fld2d(:,:), fld3d(:,:,:)

      if (size(wind_heights) == 1) then
        allocate(fld2d(ib:ie,jb:je))
        fld2d = ws_localt(:,:,1)
        where (.not. ws_local_valid(:,:,1)) fld2d = nc_fillvalue
        call writeoffset_2d(ncid, 'ws_local', fld2d, record, xdim, ydim)
        deallocate(fld2d)
      else
        allocate(fld3d(ib:ie,jb:je,1:size(wind_heights)))
        fld3d = ws_localt
        where (.not. ws_local_valid) fld3d = nc_fillvalue
        call writeoffset(ncid, 'ws_local', fld3d, record, xdim, ydim, size(wind_heights))
        deallocate(fld3d)
      end if

      allocate(fld2d(ib:ie,jb:je))
      fld2d = ws_10t
      where (.not. ws_10_valid) fld2d = nc_fillvalue
      call writeoffset_2d(ncid, 'ws_10', fld2d, record, xdim, ydim)
      deallocate(fld2d)
    end subroutine stats_write_pedestrian_wind

    !> Time averages on the yz-planes islice(1:nislice): stats_tislice.xxx.xxx.nc, one file
    !> per x-block that contains at least one plane, written by its myidy == 0 rank.
    subroutine stats_write_tavg_islice
      implicit none
      integer :: n, i, m
      real, allocatable :: fld(:,:,:), tmp(:,:,:)
      if (local_ntislice > 0) then   ! this rank holds at least one plane of this orientation
        allocate(fld(ib:ie, jb:je, kb:ke), tmp(local_ntislice, jb:je, kb:ke))
        if (myidy == 0) call writestat_nc(ncidtis, 'time', timee, nrectis, .true.)
        do n = 1, tVarsCount
          call stats_tavg_field(trim(tVars(n,1)), fld)
          m = 0
          do i = 1, nislice
            if (islice(i) >= zstart(1) .and. islice(i) <= zend(1)) then
              m = m + 1
              tmp(m,:,:) = fld(islice(i) - zstart(1) + 1, :, :)
            end if
          end do
          call writeoffset(ncidtis, trim(tVars(n,1)), tmp, nrectis, local_ntislice, ydim, zdim)
        end do
        deallocate(fld, tmp)
      end if
    end subroutine stats_write_tavg_islice

    !> Time averages on the xz-planes jslice(1:njslice): stats_tjslice.xxx.xxx.nc, one file
    !> per y-block that contains at least one plane, written by its myidx == 0 rank.
    subroutine stats_write_tavg_jslice
      implicit none
      integer :: n, j, m
      real, allocatable :: fld(:,:,:), tmp(:,:,:)
      if (local_ntjslice > 0) then   ! this rank holds at least one plane of this orientation
        allocate(fld(ib:ie, jb:je, kb:ke), tmp(ib:ie, local_ntjslice, kb:ke))
        if (myidx == 0) call writestat_nc(ncidtjs, 'time', timee, nrectjs, .true.)
        do n = 1, tVarsCount
          call stats_tavg_field(trim(tVars(n,1)), fld)
          m = 0
          do j = 1, njslice
            if (jslice(j) >= zstart(2) .and. jslice(j) <= zend(2)) then
              m = m + 1
              tmp(:,m,:) = fld(:, jslice(j) - zstart(2) + 1, :)
            end if
          end do
          call writeoffset_1dx(ncidtjs, trim(tVars(n,1)), tmp, nrectjs, xdim, local_ntjslice, zdim)
        end do
        deallocate(fld, tmp)
      end if
    end subroutine stats_write_tavg_jslice

    !> Time averages on the xy-planes kslice(1:nkslice): stats_tkslice.xxx.xxx.nc, one file
    !> per x-block, written by its myidy == 0 rank.
    subroutine stats_write_tavg_kslice
      implicit none
      integer :: n, k
      real, allocatable :: fld(:,:,:), tmp(:,:,:)
      allocate(fld(ib:ie, jb:je, kb:ke), tmp(ib:ie, jb:je, nkslice))
      if (myidy == 0) call writestat_nc(ncidtks, 'time', timee, nrectks, .true.)
      do n = 1, tVarsCount
        call stats_tavg_field(trim(tVars(n,1)), fld)
        do k = 1, nkslice
          tmp(:,:,k) = fld(:, :, kslice(k))
        end do
        call writeoffset(ncidtks, trim(tVars(n,1)), tmp, nrectks, xdim, ydim, nkslice)
      end do
      deallocate(fld, tmp)
      call stats_write_pedestrian_wind(ncidtks, nrectks)
    end subroutine stats_write_tavg_kslice

    !> File creation for the time-averaged slices; same layout and coordinate
    !> conventions as the instantaneous ins_[ijk]slice files.
    subroutine stats_createnc_tislice
      implicit none
      local_ntislice = count(islice(1:nislice) >= zstart(1) .and. islice(1:nislice) <= zend(1))
      if (local_ntislice > 0 .and. myidy == 0) then
        filenametis = 'stats_tislice.xxx.xxx.nc'
        filenametis(15:17) = cmyidx
        filenametis(19:21) = cexpnr
        nrectis = 0
        call open_nc(filenametis, ncidtis, nrectis, n1=local_ntislice, n2=jtot, n3=zdim)
        if (nrectis == 0) then
          call define_nc(ncidtis, 1, timeVar)
          call writestat_dims_nc(ncidtis)
          call stats_write_islice_xcoord(ncidtis)
        end if
        call define_nc(ncidtis, tVarsCount, tVars)
      end if
    end subroutine stats_createnc_tislice

    subroutine stats_createnc_tjslice
      implicit none
      local_ntjslice = count(jslice(1:njslice) >= zstart(2) .and. jslice(1:njslice) <= zend(2))
      if (local_ntjslice > 0 .and. myidx == 0) then
        filenametjs = 'stats_tjslice.xxx.xxx.nc'
        filenametjs(15:17) = cmyidy
        filenametjs(19:21) = cexpnr
        nrectjs = 0
        call open_nc(filenametjs, ncidtjs, nrectjs, n1=itot, n2=local_ntjslice, n3=zdim)
        if (nrectjs == 0) then
          call define_nc(ncidtjs, 1, timeVar)
          call writestat_dims_nc(ncidtjs)
          call stats_write_jslice_ycoord(ncidtjs)
        end if
        call define_nc(ncidtjs, tVarsCount, tVars)
      end if
    end subroutine stats_createnc_tjslice

    subroutine stats_createnc_tkslice
      implicit none
      if (myidy == 0) then
        filenametks = 'stats_tkslice.xxx.xxx.nc'
        filenametks(15:17) = cmyidx
        filenametks(19:21) = cexpnr
        nrectks = 0
        call open_nc(filenametks, ncidtks, nrectks, n1=xdim, n2=jtot, n3=nkslice)
        if (nrectks == 0) then
          call define_nc(ncidtks, 1, timeVar)
          call writestat_dims_nc(ncidtks)
          call stats_write_kslice_zcoord(ncidtks)
        end if
        call define_nc(ncidtks, tVarsCount, tVars)
        call stats_define_pedestrian_wind(ncidtks)
      end if
    end subroutine stats_createnc_tkslice

    !> Slice coordinates: the x/y/z dimension of a slice file is the list of plane
    !> positions on this rank; the global indices are kept as an attribute.
    subroutine stats_write_islice_xcoord(ncid)
      implicit none
      integer, intent(in) :: ncid
      integer :: varid, ierr, i, m
      real    :: xcf(local_ntislice), xch(local_ntislice)
      integer :: idx(local_ntislice)
      m = 0
      do i = 1, nislice
        if (islice(i) >= zstart(1) .and. islice(i) <= zend(1)) then
          m = m + 1
          xcf(m) = xf(islice(i)); xch(m) = xh(islice(i)); idx(m) = islice(i)
        end if
      end do
      ierr = nf90_inq_varid(ncid, 'xt', varid)
      if (ierr == nf90_noerr) then
        ierr = nf90_redef(ncid)
        ierr = nf90_put_att(ncid, varid, 'islice_indices', idx)
        ierr = nf90_put_att(ncid, varid, 'long_name', 'x-coordinate of i-slices (cell center)')
        ierr = nf90_enddef(ncid)
        ierr = nf90_put_var(ncid, varid, xcf)
      end if
      ierr = nf90_inq_varid(ncid, 'xm', varid)
      if (ierr == nf90_noerr) then
        ierr = nf90_redef(ncid)
        ierr = nf90_put_att(ncid, varid, 'islice_indices', idx)
        ierr = nf90_put_att(ncid, varid, 'long_name', 'x-coordinate of i-slices (cell edge)')
        ierr = nf90_enddef(ncid)
        ierr = nf90_put_var(ncid, varid, xch)
      end if
    end subroutine stats_write_islice_xcoord

    subroutine stats_write_jslice_ycoord(ncid)
      implicit none
      integer, intent(in) :: ncid
      integer :: varid, ierr, j, m
      real    :: ycf(local_ntjslice), ych(local_ntjslice)
      integer :: idx(local_ntjslice)
      m = 0
      do j = 1, njslice
        if (jslice(j) >= zstart(2) .and. jslice(j) <= zend(2)) then
          m = m + 1
          ycf(m) = yf(jslice(j)); ych(m) = yh(jslice(j)); idx(m) = jslice(j)
        end if
      end do
      ierr = nf90_inq_varid(ncid, 'yt', varid)
      if (ierr == nf90_noerr) then
        ierr = nf90_redef(ncid)
        ierr = nf90_put_att(ncid, varid, 'jslice_indices', idx)
        ierr = nf90_put_att(ncid, varid, 'long_name', 'y-coordinate of j-slices (cell center)')
        ierr = nf90_enddef(ncid)
        ierr = nf90_put_var(ncid, varid, ycf)
      end if
      ierr = nf90_inq_varid(ncid, 'ym', varid)
      if (ierr == nf90_noerr) then
        ierr = nf90_redef(ncid)
        ierr = nf90_put_att(ncid, varid, 'jslice_indices', idx)
        ierr = nf90_put_att(ncid, varid, 'long_name', 'y-coordinate of j-slices (cell edge)')
        ierr = nf90_enddef(ncid)
        ierr = nf90_put_var(ncid, varid, ych)
      end if
    end subroutine stats_write_jslice_ycoord

    subroutine stats_write_kslice_zcoord(ncid)
      implicit none
      integer, intent(in) :: ncid
      integer :: varid, ierr, k
      real    :: zcf(nkslice), zch(nkslice)
      do k = 1, nkslice
        zcf(k) = zf(kslice(k)); zch(k) = zh(kslice(k))
      end do
      ierr = nf90_inq_varid(ncid, 'zt', varid)
      if (ierr == nf90_noerr) then
        ierr = nf90_redef(ncid)
        ierr = nf90_put_att(ncid, varid, 'kslice_indices', kslice(1:nkslice))
        ierr = nf90_put_att(ncid, varid, 'long_name', 'z-coordinate of k-slices (cell center)')
        ierr = nf90_enddef(ncid)
        ierr = nf90_put_var(ncid, varid, zcf)
      end if
      ierr = nf90_inq_varid(ncid, 'zm', varid)
      if (ierr == nf90_noerr) then
        ierr = nf90_redef(ncid)
        ierr = nf90_put_att(ncid, varid, 'kslice_indices', kslice(1:nkslice))
        ierr = nf90_put_att(ncid, varid, 'long_name', 'z-coordinate of k-slices (cell edge)')
        ierr = nf90_enddef(ncid)
        ierr = nf90_put_var(ncid, varid, zch)
      end if
    end subroutine stats_write_kslice_zcoord

    subroutine stats_validate_slice_inputs(slice_enabled, n_slice, slice_array, slice_name)
      implicit none
      logical,          intent(in) :: slice_enabled
      integer,          intent(in) :: n_slice
      integer,          intent(in) :: slice_array(:)
      character(len=*), intent(in) :: slice_name
      if (.not. slice_enabled) return
      if (n_slice <= 0) then
        write(0, *) 'ERROR: lt', trim(slice_name), 'dump=.true. but n', trim(slice_name), '=', n_slice, ' (must be > 0)'
        stop 1
      end if
      if (count(slice_array(1:n_slice) > 0) /= n_slice) then
        write(0, *) 'ERROR: n', trim(slice_name), '=', n_slice, ' but only', count(slice_array(1:n_slice) > 0), &
                    ' valid (>0) entries found in ', trim(slice_name), ' array'
        stop 1
      end if
    end subroutine stats_validate_slice_inputs


    !! ## %% Time, y and x averaged statistics writing routines 
    subroutine stats_write_xytavg_vel
      implicit none
      call writestat_nc(ncidxyt, 'u'       , uxyt(kb:ke)       , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'v'       , vxyt(kb:ke)       , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'w'       , wxyt(kb:ke)       , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'p'       , pxyt(kb:ke)       , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'pabs'    , presf(kb:ke)      , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'upwp'    , upwpxytik(kb:ke)  , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'vpwp'    , vpwpxytjk(kb:ke)  , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'upvp'    , upvpxytij(kb:ke)  , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'uw'      , uwxytik(kb:ke)    , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'vw'      , vwxytjk(kb:ke)    , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'uv'      , uvxytij(kb:ke)    , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'uu'      , uuxyti(kb:ke)     , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'vv'      , vvxytj(kb:ke)     , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'ww'      , wwxytk(kb:ke)     , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'upup'    , upupxytc(kb:ke)   , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'vpvp'    , vpvpxytc(kb:ke)   , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'wpwp'    , wpwpxytc(kb:ke)   , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'tke'     , tkexytc(kb:ke)    , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'usgs'    , usgsxyt(kb:ke)    , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'vsgs'    , vsgsxyt(kb:ke)    , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'wsgs'    , wsgsxyt(kb:ke)    , nrecxyt, zdim)
    end subroutine stats_write_xytavg_vel
    
    subroutine stats_write_xytavg_temp
      implicit none
      call writestat_nc(ncidxyt, 'thl'     , thlxyt(kb:ke)     , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'tha'     , tempxyt(kb:ke)    , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'wpthlp'  , wpthlpxytk(kb:ke) , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'wthl'    , wthlxytk(kb:ke)   , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'thlpthlp', thlpthlpxyt(kb:ke), nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'thlsgs'  , thlsgsxyt(kb:ke)  , nrecxyt, zdim)
    end subroutine stats_write_xytavg_temp
    
    subroutine stats_write_xytavg_moist
      implicit none
      call writestat_nc(ncidxyt, 'qt'      , qtxyt(kb:ke)      , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'wpqtp'   , wpqtpxytk(kb:ke)  , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'wqt'     , wqtxytk(kb:ke)    , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'qtpqtp'  , qtpqtpxyt(kb:ke)  , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'qtsgs'   , qtsgsxyt(kb:ke)   , nrecxyt, zdim)
      call writestat_nc(ncidxyt, 'ql'      , qlxyt(kb:ke)      , nrecxyt, zdim)
    end subroutine stats_write_xytavg_moist

    subroutine stats_write_xytavg_relative_humidity
      implicit none
      call writestat_nc(ncidxyt, 'rh', rhxyt(kb:ke), nrecxyt, zdim)
    end subroutine stats_write_xytavg_relative_humidity


    !! ## %% y and x averaged statistics writing routines 
    subroutine stats_write_xyavg_vel
      implicit none
      call writestat_nc(ncidxy, 'u'       , uxy(kb:ke)       , nrecxy, zdim)
      call writestat_nc(ncidxy, 'v'       , vxy(kb:ke)       , nrecxy, zdim)
      call writestat_nc(ncidxy, 'w'       , wxy(kb:ke)       , nrecxy, zdim)
      call writestat_nc(ncidxy, 'p'       , pxy(kb:ke)       , nrecxy, zdim)
      call writestat_nc(ncidxy, 'pabs'    , presf(kb:ke)     , nrecxy, zdim)
      call writestat_nc(ncidxy, 'upwp'    , upwpxyik(kb:ke)  , nrecxy, zdim)
      call writestat_nc(ncidxy, 'vpwp'    , vpwpxyjk(kb:ke)  , nrecxy, zdim)
      call writestat_nc(ncidxy, 'upvp'    , upvpxyij(kb:ke)  , nrecxy, zdim)
      call writestat_nc(ncidxy, 'uw'      , uwxyik(kb:ke)    , nrecxy, zdim)
      call writestat_nc(ncidxy, 'vw'      , vwxyjk(kb:ke)    , nrecxy, zdim)
      call writestat_nc(ncidxy, 'uv'      , uvxyij(kb:ke)    , nrecxy, zdim)
      call writestat_nc(ncidxy, 'uu'      , uuxyi(kb:ke)     , nrecxy, zdim)
      call writestat_nc(ncidxy, 'vv'      , vvxyj(kb:ke)     , nrecxy, zdim)
      call writestat_nc(ncidxy, 'ww'      , wwxyk(kb:ke)     , nrecxy, zdim)
      call writestat_nc(ncidxy, 'usgs'    , usgsxy(kb:ke)    , nrecxy, zdim)
      call writestat_nc(ncidxy, 'vsgs'    , vsgsxy(kb:ke)    , nrecxy, zdim)
      call writestat_nc(ncidxy, 'wsgs'    , wsgsxy(kb:ke)    , nrecxy, zdim)
    end subroutine stats_write_xyavg_vel

    subroutine stats_write_xyavg_temp
      implicit none
      call writestat_nc(ncidxy, 'thl'     , thlxy(kb:ke)     , nrecxy, zdim)
      call writestat_nc(ncidxy, 'tha'     , tempxy(kb:ke)    , nrecxy, zdim)
      call writestat_nc(ncidxy, 'wpthlp'  , wpthlpxyk(kb:ke) , nrecxy, zdim)
      call writestat_nc(ncidxy, 'wthl'    , wthlxyk(kb:ke)   , nrecxy, zdim)
      call writestat_nc(ncidxy, 'thlsgs'  , thlsgsxy(kb:ke)  , nrecxy, zdim)
    end subroutine stats_write_xyavg_temp

    subroutine stats_write_xyavg_moist
      implicit none
      call writestat_nc(ncidxy, 'qt'      , qtxy(kb:ke)      , nrecxy, zdim)
      call writestat_nc(ncidxy, 'wpqtp'   , wpqtpxyk(kb:ke)  , nrecxy, zdim)
      call writestat_nc(ncidxy, 'wqt'     , wqtxyk(kb:ke)    , nrecxy, zdim)
      call writestat_nc(ncidxy, 'qtsgs'   , qtsgsxy(kb:ke)   , nrecxy, zdim)
      call writestat_nc(ncidxy, 'ql'      , qlxy(kb:ke)      , nrecxy, zdim)
    end subroutine stats_write_xyavg_moist

    subroutine stats_write_xyavg_relative_humidity
      implicit none
      call writestat_nc(ncidxy, 'rh', rhxy(kb:ke), nrecxy, zdim)
    end subroutine stats_write_xyavg_relative_humidity


    !! ## %% Time and y averaged statistics writing routines 
    subroutine stats_write_ytavg_vel
      implicit none
      call writestat_nc(ncidyt, 'u'    , uyt     , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'v'    , vyt     , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'w'    , wyt     , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'p'    , pyt     , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'pabs' , spread(presf(kb:ke), 1, xdim), nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'upwp' , upwpytik, nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'uw'   , uwytik  , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'upup' , upupytc , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'vpvp' , vpvpytc , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'wpwp' , wpwpytc , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'usgs' , usgsyt  , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'wsgs' , wsgsyt  , nrecyt, xdim, zdim)
    end subroutine stats_write_ytavg_vel

    subroutine stats_write_ytavg_temp
      implicit none
      call writestat_nc(ncidyt, 'thl'     , thlyt     , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'tha'     , tempyt    , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'wpthlp'  , wpthlpytk , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'wthl'    , wthlytk   , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'thlpthlp', thlpthlpyt, nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'thlsgs'  , thlsgsyt  , nrecyt, xdim, zdim)
    end subroutine stats_write_ytavg_temp

    subroutine stats_write_ytavg_moist
      implicit none
      call writestat_nc(ncidyt, 'qt'     , qtyt     , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'wpqtp'  , wpqtpytk , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'wqt'    , wqtytk   , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'qtpqtp' , qtpqtpyt , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'qtsgs'  , qtsgsyt  , nrecyt, xdim, zdim)
      call writestat_nc(ncidyt, 'ql'     , qlyt     , nrecyt, xdim, zdim)
    end subroutine stats_write_ytavg_moist

    subroutine stats_write_ytavg_relative_humidity
      implicit none
      call writestat_nc(ncidyt, 'rh', rhyt, nrecyt, xdim, zdim)
    end subroutine stats_write_ytavg_relative_humidity

    subroutine stats_write_ytavg_scalar
      implicit none
      integer :: n
      do n = 1, nsv
        call writestat_nc(ncidyt, trim(svytname(n))    , svyt(:,:,n)     , nrecyt, xdim, zdim)
        call writestat_nc(ncidyt, trim(wpsvpytname(n)) , wpsvpytk(:,:,n) , nrecyt, xdim, zdim)
        call writestat_nc(ncidyt, trim(wsvytname(n))   , wsvytk(:,:,n)   , nrecyt, xdim, zdim)
        call writestat_nc(ncidyt, trim(svpsvpytname(n)), svpsvpyt(:,:,n) , nrecyt, xdim, zdim)
        call writestat_nc(ncidyt, trim(svsgsytname(n)) , svsgsyt(:,:,n)  , nrecyt, xdim, zdim)
      end do
    end subroutine stats_write_ytavg_scalar


    !! ## %% y averaged statistics writing routines 
    subroutine stats_write_yavg_vel
      implicit none
      call writestat_nc(ncidy, 'u'    , uy     , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'v'    , vy     , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'w'    , wy     , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'p'    , py     , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'pabs' , spread(presf(kb:ke), 1, xdim), nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'upwp' , upwpyik, nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'uw'   , uwyik  , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'usgs' , usgsy  , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'wsgs' , wsgsy  , nrecy, xdim, zdim)
    end subroutine stats_write_yavg_vel

    subroutine stats_write_yavg_temp
      implicit none
      call writestat_nc(ncidy, 'thl'     , thly     , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'tha'     , tempy    , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'wpthlp'  , wpthlpyk , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'wthl'    , wthlyk   , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'thlsgs'  , thlsgsy  , nrecy, xdim, zdim)
    end subroutine stats_write_yavg_temp

    subroutine stats_write_yavg_moist
      implicit none
      call writestat_nc(ncidy, 'qt'     , qty     , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'wpqtp'  , wpqtpyk , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'wqt'    , wqtyk   , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'qtsgs'  , qtsgsy  , nrecy, xdim, zdim)
      call writestat_nc(ncidy, 'ql'     , qly     , nrecy, xdim, zdim)
    end subroutine stats_write_yavg_moist

    subroutine stats_write_yavg_relative_humidity
      implicit none
      call writestat_nc(ncidy, 'rh', rhy, nrecy, xdim, zdim)
    end subroutine stats_write_yavg_relative_humidity

    subroutine stats_write_yavg_scalar
      implicit none
      integer :: n
      do n = 1, nsv
        call writestat_nc(ncidy, trim(svyname(n))    , svy(:,:,n)     , nrecy, xdim, zdim)
        call writestat_nc(ncidy, trim(wpsvpyname(n)) , wpsvpyk(:,:,n) , nrecy, xdim, zdim)
        call writestat_nc(ncidy, trim(wsvyname(n))   , wsvyk(:,:,n)   , nrecy, xdim, zdim)
        call writestat_nc(ncidy, trim(svsgsyname(n)) , svsgsy(:,:,n)  , nrecy, xdim, zdim)
      end do
    end subroutine stats_write_yavg_scalar


    !! ## %% Time averaged tree data statistics writing routines 
    subroutine stats_write_tree_vel
      implicit none
      call writeoffset(ncidtree, 'tr_u'    , tr_ut    , nrectree, xdim, ydim, zdim)
      call writeoffset(ncidtree, 'tr_v'    , tr_vt    , nrectree, xdim, ydim, zdim)
      call writeoffset(ncidtree, 'tr_w'    , tr_wt    , nrectree, xdim, ydim, zdim)
    end subroutine stats_write_tree_vel

    subroutine stats_write_tree_temp
      implicit none
      call writeoffset(ncidtree, 'tr_thl'  , tr_thlt  , nrectree, xdim, ydim, zdim)
    end subroutine stats_write_tree_temp

    subroutine stats_write_tree_moist
      implicit none
      call writeoffset(ncidtree, 'tr_qt'   , tr_qtt   , nrectree, xdim, ydim, zdim)
      call writeoffset(ncidtree, 'tr_qtR'  , tr_qtRt  , nrectree, xdim, ydim, zdim)
      call writeoffset(ncidtree, 'tr_qtA'  , tr_qtAt  , nrectree, xdim, ydim, zdim)
      call writeoffset(ncidtree, 'tr_omega', tr_omegat, nrectree, xdim, ydim, zdim)
    end subroutine stats_write_tree_moist

    subroutine stats_write_tree_scalar
      implicit none
      integer :: n
      do n = 1, nsv
        call writeoffset(ncidtree, trim(svtreename(n)), tr_svt(:,:,:,n), nrectree, xdim, ydim, zdim)
      end do
    end subroutine stats_write_tree_scalar


    subroutine stats_exit
      use modstat_nc, only : exitstat_nc
      implicit none
      if(.not.(lstatsdump .or. ltreedump)) return
      if(.not. lstatsprepared) return

      if (lstatsdump) then
        deallocate(uik,wik,vjk,wjk,uij,vij,uc,vc,wc,usgs,vsgs,wsgs)
        if (ltempeq) deallocate(tempnow,thli,thlj,thlk,thlsgs)
        if (lmoist)  deallocate(qtk,qtsgs)
        if (lrh)     deallocate(rhnow)
      end if
      if (ltavg3d .or. lytdump .or. lydump) then
        if (nsv>0)   deallocate(svi,svj,svk,svsgs)
      end if

      if (lstatstavgdump) then
        deallocate(ut,vt,wt,pt)
        deallocate(utc,vtc,wtc,uutc,vvtc,wwtc)
        deallocate(utik,wtik,uwtik,vtjk,wtjk,vwtjk,utij,vtij,uvtij)
        deallocate(usgst,vsgst,wsgst)
        if (ltempeq) deallocate(tempt,thlt,thlti,thltj,thltk,uthlti,vthltj,wthltk,thlthlt,thlsgst)
        if (lmoist)  deallocate(qtt,qlt,qttk,wqttk,qtqtt,qtsgst)
        if (lrh)     deallocate(rht)
      end if
      if (ltdump .or. ltkslicedump) then
        deallocate(ws_localt,ws_10t,ws_now,ws_local_valid,ws_10_valid,wind_heights, &
                   ws_local_klo,ws_local_khi,ws_local_weight,ws_local_available)
      end if
      if (ltavg3d .or. lytdump) then
        if (nsv>0)   deallocate(svt,svti,svtj,svtk,usvti,vsvtj,wsvtk,svsvt,svsgst)
      end if
      if (ltavg3d) then
        if (nsv>0)   deallocate(svtname,upsvptname,vpsvptname,wpsvptname,svpsvptname,svsgsname)
        if ((lchem) .and. (nsv>2)) deallocate(PSS,PSSt)
      end if

      if (ltdump) then
        if (myidy==0) call exitstat_nc(ncidt)
      end if
      if (ltislicedump .and. local_ntislice > 0 .and. myidy == 0) call exitstat_nc(ncidtis)
      if (ltjslicedump .and. local_ntjslice > 0 .and. myidx == 0) call exitstat_nc(ncidtjs)
      if (ltkslicedump .and. myidy == 0) call exitstat_nc(ncidtks)
      if (ltavg3d) deallocate(tVars)

      if (lxytdump) then
        deallocate(uxyt,vxyt,wxyt,pxyt,usgsxyt,vsgsxyt,wsgsxyt)
        deallocate(upwpxytik,vpwpxytjk,upvpxytij,upupxytc,vpvpxytc,wpwpxytc,tkexytc)
        deallocate(uwxytik,vwxytjk,uvxytij,uuxyti,vvxytj,wwxytk)
        if (ltempeq) deallocate(tempxyt,thlxyt,wpthlpxytk,wthlxytk,thlpthlpxyt,thlsgsxyt)
        if (lmoist)  deallocate(qtxyt,qlxyt,wpqtpxytk,wqtxytk,qtpqtpxyt,qtsgsxyt)
        if (lrh)     deallocate(rhxyt)
        if (myid==0) call exitstat_nc(ncidxyt)
      end if

      if (lxydump) then
        deallocate(uxy,vxy,wxy,pxy,usgsxy,vsgsxy,wsgsxy)
        deallocate(upwpxyik,vpwpxyjk,upvpxyij)
        deallocate(uwxyik,uxyik,wxyik,vwxyjk,vxyjk,wxyjk,uvxyij,uxyij,vxyij,uuxyi,vvxyj,wwxyk)
        if (ltempeq) deallocate(tempxy,thlxy,wpthlpxyk,wthlxyk,thlxyk,thlsgsxy)
        if (lmoist)  deallocate(qtxy,qlxy,wpqtpxyk,wqtxyk,qtxyk,qtsgsxy)
        if (lrh)     deallocate(rhxy)
        if (myid==0) call exitstat_nc(ncidxy)
      end if

      if (lytdump) then
        deallocate(uyt,vyt,wyt,pyt,usgsyt,wsgsyt)
        deallocate(upwpytik,uwytik,upupytc,vpvpytc,wpwpytc)
        if (ltempeq) deallocate(tempyt,thlyt,wpthlpytk,wthlytk,thlpthlpyt,thlsgsyt)
        if (lmoist)  deallocate(qtyt,qlyt,wpqtpytk,wqtytk,qtpqtpyt,qtsgsyt)
        if (lrh)     deallocate(rhyt)
        if (nsv>0)   deallocate(svytname,wpsvpytname,wsvytname,svpsvpytname,svsgsytname,svyt,wpsvpytk,wsvytk,svpsvpyt,svsgsyt)
        if (myidy==0) call exitstat_nc(ncidyt)
      end if

      if (lydump) then
        deallocate(uy,vy,wy,py,usgsy,wsgsy)
        deallocate(upwpyik,uwyik,uyik,wyik)
        if (ltempeq) deallocate(tempy,thly,wpthlpyk,wthlyk,thlyk,thlsgsy)
        if (lmoist)  deallocate(qty,qly,wpqtpyk,wqtyk,qtyk,qtsgsy)
        if (lrh)     deallocate(rhy)
        if (nsv>0)   deallocate(svyname,wpsvpyname,wsvyname,svsgsyname,svy,wpsvpyk,wsvyk,svyk,svsgsy)
        if (myidy==0) call exitstat_nc(ncidy)
      end if

      if (ltreedump) then
        deallocate(tr_ut,tr_vt,tr_wt,tr_now)
        if (ltempeq) deallocate(tr_thlt)
        if (lmoist)  deallocate(tr_qtt,tr_qtRt,tr_qtAt,tr_omegat)
        if (nsv>0)   deallocate(svtreename,tr_svt)
        if (myidy==0) call exitstat_nc(ncidtree)
      end if
    end subroutine stats_exit
end module stats