!-------------------------------------- LICENCE BEGIN ------------------------------------
!Environment Canada - Atmospheric Science and Technology License/Disclaimer,
!                     version 3; Last Modified: May 7, 2008.
!This is free but copyrighted software; you can use/redistribute/modify it under the terms
!of the Environment Canada - Atmospheric Science and Technology License/Disclaimer
!version 3 or (at your option) any later version that should be found at:
!http://collaboration.cmc.ec.gc.ca/science/rpn.comm/license.html
!
!This software 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 above mentioned License/Disclaimer for more details.
!You should have received a copy of the License/Disclaimer along with this software;
!if not, you can write to: EC-RPN COMM Group, 2121 TransCanada, suite 500, Dorval (Quebec),
!CANADA, H9P 1J3; or send e-mail to service.rpn@ec.gc.ca
!-------------------------------------- LICENCE END --------------------------------------
!
C
C  X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X
C

      subroutine stdev_low(pgd,klevmin,klevmax) 6
*
*Author: Luc Fillion - 9 Apr 2009. Apply reduction in the layer between model top and level klev.
!
!revision:
! Arguments:
*           
*
      IMPLICIT NONE
*implicits
#include "taglam4d.cdk"
#include "comdim.cdk"
#include "comlun.cdk"
#include "comgrd_param.cdk"
*
      integer klevmin,klevmax
      real*8 pgd(ni,nflev,nj)
!
      integer ji,jj,jk,imin,imax
      real*8 zfac,zsign
!
!!
      write(nulout,*) 'stdev_low active'
!
!     Apply reduction within vertical layer
!
      zfac = 1./8.
      imin = max(1,klevmin-1)
      imax = min(nflev,klevmax)
      write(nulout,*) 'stdev_low: klevmin,klevmax=',klevmin,klevmax
      write(nulout,*) 'stdev_low: imin,imax=',imin,imax
      zsign = -1.0
      if(pgd(ni/2,imin,nj/2).gt.pgd(ni/2,imax,nj/2)) zsign = 1.0 ! assume same behavior elsewhere horizontally...
      zfac = zsign*zfac
      do ji=1,ni
      do jj=1,nj
        do jk = imin,imax
      if((ji.eq.ni/2).and.(jj.eq.nj/2)) write(nulout,*) 'Level = ',jk
      if((ji.eq.ni/2).and.(jj.eq.nj/2)) write(nulout,*) 'Before:', pgd(ji,jk,jj)
          pgd(ji,jk,jj) = pgd(ji,klevmax,jj)
!          pgd(ji,jk,jj) = pgd(ji,jk,jj) - zfac*(pgd(ji,jk,jj)-pgd(ji,klevmax,jj))
      if((ji.eq.ni/2).and.(jj.eq.nj/2)) write(nulout,*) 'After:', pgd(ji,jk,jj)
        enddo
      enddo
      enddo
!
      return
      end