!-------------------------------------- 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 vfilt(pfld,knbmod,cdfilt) 16,2
*
***s/r vfilt  - Performs a vertical normal mode filtering of input field.
*
*Author  : Luc Fillion - 25 Nov. 2008.
*Revision:
*  Luc Fillion - 11 Feb. 2009 - Extend to allow filtering of large or small vertical scales via cdfilt.
*
*     -------------------
**    Purpose: Used for LAM4D analysis
*
*Arguments
*
* IN/Out:
*     pfld    = Vertically filtered field
*
      implicit none
!
      character*1 cdfilt
      integer knbmod
      real*8 pfld(ni,nflev,nj)
!
#include "taglam4d.cdk"
#include "comdim.cdk"
#include "comcst.cdk"
#include "comlun.cdk"
#include "comode.cdk"
#include "comin.cdk"
!
!
      integer ji,jj,jk
      real*8 zw3d(ni,nflev,nj)
      real*8 zw3dp(ni,nflev,nj)
!
!!
!      write(nulout,*) 'VFILT BEGINS'
!
      zw3d(:,:,:) = 0.0
      zw3dp(:,:,:) = 0.0

      call vproj(zw3d,pfld,knbmod)
      call viproj(zw3dp,zw3d,knbmod)
!
      if(cdfilt.eq.'L') then  ! filters first knbmod vertical modes
        do jj=1,nj
          do jk=1,nflev
            do ji=1,ni
              pfld(ji,jk,jj) = pfld(ji,jk,jj) - zw3dp(ji,jk,jj)
            enddo
          enddo
        enddo
      else      ! keep only first knbmod vertical modes         
        do jj=1,nj
          do jk=1,nflev
            do ji=1,ni
              pfld(ji,jk,jj) = zw3dp(ji,jk,jj)
            enddo
          enddo
        enddo
      endif
!
      return
      end