!-------------------------------------- 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 --------------------------------------
!

subroutine vintgd(pprofo,plevo,klevo,pprofi,plevi,klevi,ini,inj) 1

! s/r vintgd  - Vertical interpolation of pressure defined profile
!
!
!Author  : M. Buehner, January 2013 (based on vintprof.ftn)
!
!     Purpose:  -Interpolate vertically the contents of input pressure
!                defined field on a grid to  another set of pressures.
!                A linear interpolation in ln(p) is performed.
!
!Arguments
!     Output:
!            pprofo: vector of output profiles
!     Input :
!            plevo  : pressure values of output profiles
!            klevo  : number of output levels
!            pprofi : vector of input profiles
!            plevi  : pressure values of input profiles
!            klevi  : number of input levels
!            ini,inj: horizontal dimensions of fields

implicit none
integer :: klevo,klevi,ini,inj
real*8  :: pprofo(ini,inj,klevo),plevo(ini,inj,klevo)
real*8  :: pprofi(ini,inj,klevi),plevi(ini,inj,klevi)

integer :: jlevo,jlevi,jlat,jlon
real*8 :: zwb,zwt

do jlat = 1, inj
  do jlon = 1, ini
    jlevi = 1
    do jlevo = 1, klevo
      jlevi = jlevi + 1
      do while(plevo(jlon,jlat,jlevo).gt.plevi(jlon,jlat,jlevi)  &
               .and.jlevi.lt.klevi)
        jlevi = jlevi + 1
      enddo
      jlevi = jlevi - 1
      zwb = log(plevo(jlon,jlat,jlevo)/plevi(jlon,jlat,jlevi))  &
           /log(plevi(jlon,jlat,jlevi+1)/plevi(jlon,jlat,jlevi))
      zwt = 1.d0 - zwb
      pprofo(jlon,jlat,jlevo) = zwb*pprofi(jlon,jlat,jlevi+1) + zwt &
                                   *pprofi(jlon,jlat,jlevi)
    enddo
  enddo
enddo

end subroutine vintgd