module convection

  use vtype_module

  implicit none

  public :: CalcMoistConvDTempDLogPress

contains

  !------------------------------------------------------------------------------

  subroutine CalcMoistConvDTempDLogPress( &
    & FlagMoistConvection, &
    & Press, MeanMolWt, Temp, &
    & DTempDLogPress &
    & )

    use constants0, only : GasRUniv
    use rad_planetconst, only : Cp

    use saturation_simple, only : &
      & CalcPressH2OVapSat, &
      & CalcDPressH2OVapSatDTemp

    implicit none

    logical , intent(in ) :: FlagMoistConvection
    real(DP), intent(in ) :: Press
    real(DP), intent(in ) :: MeanMolWt
    real(DP), intent(in ) :: Temp
    real(DP), intent(out) :: DTempDLogPress


    ! Local variables
    !
    real(DP), parameter :: LatentHeat = 2.5d6    ! J kg-1
    real(DP), parameter :: CpH2OVap   = 1810.0d0 ! J K-1 kg-1
    real(DP), parameter :: MolWtH2O   = 18.0d-3  ! kg mol-1

    real(DP) :: CPPerMol
    real(DP) :: CpH2OVapPerMol
    real(DP) :: CPTotPerMol
    real(DP) :: LatentHeatPerMol
    real(DP) :: PressH2OVapSat
    real(DP) :: DPressH2OVapSatDTemp
    real(DP) :: VMRSat



    LatentHeatPerMol = LatentHeat * MolWtH2O
    CpH2OVapPerMol   = CpH2OVap * MolWtH2O


    CpPerMol = Cp * MeanMolWt
    if ( FlagMoistConvection ) then
      PressH2OVapSat       = CalcPressH2OVapSat( LatentHeatPerMol, Temp )
      DPressH2OVapSatDTemp = CalcDPressH2OVapSatDTemp( LatentHeatPerMol, Temp )
    else
      PressH2OVapSat       = 0.0d0
      DPressH2OVapSatDTemp = 0.0d0
    end if
    VMRSat = PressH2OVapSat / Press
    CpTotPerMol = CpPerMol * ( 1.0d0 - VMRSat ) + CpH2OVapPerMol * VMRSat
    DTempDLogPress = ( GasRUniv * Temp + LatentHeatPerMol * VMRSat ) &
      & / ( CPTotPerMol + LatentHeatPerMol / Press * DPressH2OVapSatDTemp )

    DTempDLogPress = - DTempDLogPress


  end subroutine CalcMoistConvDTempDLogPress

  !----------------------------------------------------------------------------

end module convection
