!= 大規模凝結 (非対流性凝結)
!
!= Large scale condensation (non-convective condensation)
!
! Authors::   Yoshiyuki O. Takahashi, Yasuhiro MORIKAWA, Yukiko YAMADA, Satoshi NODA
! Version::   $Id: lscond.F90,v 1.1 2010/12/15 06:55:06 noda Exp $ 
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2008. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module lscond
  !
  != 大規模凝結 (非対流性凝結)
  !
  != Large scale condensation (non-convective condensation)
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  ! 大規模凝結過程によって温度と比湿を調節します. 
  !
  ! Adjust temperature and specific humidity by 
  ! a large scale condensation process.
  !
  !== Procedures List
  ! 
  ! LScaleCond    :: 温度と比湿の調節
  ! ------------  :: ------------
  ! LScaleCond    :: Adjust temperature and specific humidity
  !
  !== NAMELIST
  !
  ! NAMELIST#lscond_nml
  !

  ! モジュール引用 ; USE statements
  !

! testing
  use cudafor

  ! 格子点設定
  ! Grid points settings
  !
  use gridset, only: imax, & ! 経度格子点数. 
                             ! Number of grid points in longitude
    &                jmax, & ! 緯度格子点数. 
                             ! Number of grid points in latitude
    &                kmax    ! 鉛直層数. 
                             ! Number of vertical level

  ! 種別型パラメタ
  ! Kind type parameter
  !
  use dc_types, only: DP, &      ! 倍精度実数型. Double precision. 
    &                 STRING     ! 文字列.       Strings. 

  ! メッセージ出力
  ! Message output
  !
  use dc_message, only: MessageNotify

  ! 宣言文 ; Declaration statements
  !
  implicit none
  private

  ! 公開手続き
  ! Public procedure
  !
  public:: LScaleCond

  ! 公開変数
  ! Public variables
  !
  logical, save, public:: lscond_inited = .false.
                              ! 初期設定フラグ. 
                              ! Initialization flag

  ! 非公開変数
  ! Private variables
  !
  real(DP), save:: CrtlRH
                              ! 臨界相対湿度. 
                              ! Critical relative humidity
  integer, save:: ItrtMax
                              ! イテレーション回数. 
                              ! Number of iteration
  logical, save:: FlagUse
                              ! 使用フラグ
                              ! flag for use of this scheme

  character(*), parameter:: module_name = 'lscond'
                              ! モジュールの名称. 
                              ! Module name
  character(*), parameter:: version = &
    & '$Name:  $' // &
    & '$Id: lscond.F90,v 1.1 2010/12/15 06:55:06 noda Exp $'
                              ! モジュールのバージョン
                              ! Module version

contains

  subroutine LScaleCond( &
    & xyz_Temp, xyz_QVap, xy_Rain, &  ! (inout)
    & xyz_DTempDt, xyz_DQVapDt, &     ! (inout)
    & xyz_Press, xyr_Press, &         ! (in)
    & xyz_DDelLWDtLSC &               ! (out) optional
    & )
    !
    ! 大規模凝結スキームにより, 温度と比湿を調節します. 
    !
    ! Adjust temperature and specific humidity by 
    ! large scale condensation scheme. 
    !

    ! モジュール引用 ; USE statements
    !

    ! 物理定数設定
    ! Physical constants settings
    !
    use constants, only: &
      & Grav, & 
                              ! $ g $ [m s-2]. 
                              ! 重力加速度. 
                              ! Gravitational acceleration
      & CpDry, &
                              ! $ C_p $ [J kg-1 K-1]. 
                              ! 乾燥大気の定圧比熱. 
                              ! Specific heat of air at constant pressure
      & LatentHeat, &
                              ! $ L $ [J kg-1] . 
                              ! 凝結の潜熱. 
                              ! Latent heat of condensation
! testing
      & EpsV, GasRWet, GasRUniv

    ! 時刻管理
    ! Time control
    !
    use timeset, only: &
      & DelTime, &            ! $ \Delta t $
      & TimeN, &              ! ステップ $ t $ の時刻. Time of step $ t $. 
      & TimesetClockStart, TimesetClockStop

    ! ヒストリデータ出力
    ! History data output
    !
    use gtool_historyauto, only: HistoryAutoPut

    ! 飽和比湿の算出
    ! Evaluate saturation specific humidity
    !
    use saturate, only: xyz_CalcQVapSat, xyz_CalcDQVapSatDTemp


    ! 宣言文 ; Declaration statements
    !
    implicit none

    real(DP), intent(inout):: xyz_Temp (0:imax-1, 1:jmax, 1:kmax)
                              ! $ T $ .     温度. Temperature
    real(DP), intent(inout):: xyz_QVap (0:imax-1, 1:jmax, 1:kmax)
                              ! $ q $ .     比湿. Specific humidity
    real(DP), intent(inout):: xy_Rain (0:imax-1, 1:jmax)
                              ! 降水量. 
                              ! Precipitation
    real(DP), intent(inout):: xyz_DTempDt (0:imax-1, 1:jmax, 1:kmax)
                              ! 温度変化率. 
                              ! Temperature tendency
    real(DP), intent(inout):: xyz_DQVapDt (0:imax-1, 1:jmax, 1:kmax)
                              ! 比湿変化率. 
                              ! Specific humidity tendency
    real(DP), intent(in):: xyz_Press (0:imax-1, 1:jmax, 1:kmax)
                              ! $ p $ . 気圧 (整数レベル). 
                              ! Air pressure (full level)
    real(DP), intent(in):: xyr_Press (0:imax-1, 1:jmax, 0:kmax)
                              ! $ \hat{p} $ . 気圧 (半整数レベル). 
                              ! Air pressure (half level)
    real(DP), intent(out), optional :: xyz_DDelLWDtLSC(0:imax-1,1:jmax,1:kmax)
                              ! Production rate of liquid water in the layer 
                              ! due to condensation (kg m-2 s-1)

    ! 作業変数
    ! Work variables
    !
    real(DP):: xy_RainLsc (0:imax-1, 1:jmax)
                              ! 降水量. 
                              ! Precipitation
    real(DP):: xyz_DTempDtLsc (0:imax-1, 1:jmax, 1:kmax)
                              ! 温度変化率. 
                              ! Temperature tendency
    real(DP):: xyz_DQVapDtLsc (0:imax-1, 1:jmax, 1:kmax)
                              ! 比湿変化率. 
                              ! Specific humidity tendency

    real(DP):: xyz_QVapB (0:imax-1, 1:jmax, 1:kmax)
                              ! 調節前の比湿. 
                              ! Specific humidity before adjust. 
    real(DP):: xyz_TempB (0:imax-1, 1:jmax, 1:kmax)
                              ! 調節前の温度. 
                              ! Temperature before adjust. 
                              !
    real(DP):: xyz_QVapSat      (0:imax-1, 1:jmax, 1:kmax)
                              ! 飽和比湿. 
                              ! Saturation specific humidity. 
    real(DP):: xyz_DQVapSatDTemp(0:imax-1, 1:jmax, 1:kmax)
                              ! $ \DD{q_{\rm{sat}}}{T} $
    real(DP):: DelTemp
                              ! 調節による温度変化量. 
                              ! Temperature variation by adjustment

    integer:: i               ! 経度方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in longitude
    integer:: j               ! 緯度方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in latitude
    integer:: k               ! 鉛直方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in vertical direction
    integer:: itr             ! イテレーション方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in iteration direction

    real(DP):: xyz_RainLSC(0:imax-1, 1:jmax, 1:kmax)

    real(DP):: TempBefAdj
    real(DP):: QVapBefAdj

! testing
    real(8), device :: d_xyz_Press(0:imax-1, 1:jmax, 1:kmax)
    real(8), device :: d_xyz_Temp(0:imax-1, 1:jmax, 1:kmax)
    real(8), device :: d_xyz_QVap(0:imax-1, 1:jmax, 1:kmax)
    real(8), device :: d_xyz_QVapSat(0:imax-1, 1:jmax, 1:kmax)
    real(8), device :: d_xyz_DQVapSatDTemp(0:imax-1, 1:jmax, 1:kmax)

    integer :: istat


    ! 実行文 ; Executable statement
    !

    ! 計算時間計測開始
    ! Start measurement of computation time
    !
    call TimesetClockStart( module_name )

    ! 初期化
    ! Initialization
    !
    if ( .not. lscond_inited ) call LSCondInit

    if ( .not. FlagUse ) return

    ! 調節前 "QVap", "Temp" の保存
    ! Store "QVap", "Temp" before adjustment
    !
!    xyz_QVapB  = xyz_QVap
!    xyz_TempB  = xyz_Temp


    ! 調節
    ! Adjustment
    !

    ! 飽和比湿計算
    ! Calculate saturation specific humidity 
    !
!    xyz_QVapSat = xyz_CalcQVapSat( xyz_Temp, xyz_Press )

!    do k = 1, kmax
!      do j = 1, jmax
!        do i = 0, imax-1

!          if ( ( xyz_QVap(i,j,k) / xyz_QVapSat(i,j,k) ) >= CrtlRH ) then
!!            xyz_FlagSaturated(i,j,k) = .true.
!            xyz_FlagSaturated(i,j,k) = 1
!          else
!!            xyz_FlagSaturated(i,j,k) = .false.
!            xyz_FlagSaturated(i,j,k) = 0
!          end if

!        end do
!      end do
!    end do


! testing
    d_xyz_Temp = xyz_Temp
    d_xyz_Press = xyz_Press
    d_xyz_QVap = xyz_QVap
    d_xyz_QVapSat = xyz_QVapSat
    d_xyz_DQVapSatDTemp = xyz_DQVapSatDTemp
    
    call LScaleCondCUDA<<<(imax*jmax*kmax)/128, 128>>>( &
      imax, jmax, kmax, ItrtMax, LatentHeat, CpDry, EpsV, GasRWet, GasRUniv, &
      CtrlRH, &
      d_xyz_Press, d_xyz_Temp, d_xyz_QVap, d_xyz_QVapSat, d_xyz_DQVapSatDTemp &
      )
    istat = cudathreadsynchronize()

    xyz_Temp = d_xyz_Temp
    xyz_QVap = d_xyz_QVap


!    do itr = 1, ItrtMax

      ! 飽和比湿計算
      ! Calculate saturation specific humidity
      !
!      xyz_QVapSat       = xyz_CalcQVapSat      ( xyz_Temp, xyz_Press   )
!      xyz_DQVapSatDTemp = xyz_CalcDQVapSatDTemp( xyz_Temp, xyz_QVapSat )
    

!      do k = 1, kmax
!        do j = 1, jmax
!          do i = 0, imax-1

            ! 飽和していたら, 温度と比湿の変化を計算
            ! Calculate tendency of temperature and humidity 
            ! if moist is saturation. 
            !
!            if ( xyz_FlagSaturated(i,j,k) ) then

              ! 温度の変化分をニュートン法で求める
              ! Calculate variation of temperature
              !

!              DelTemp = &
!                & LatentHeat * ( xyz_QVap(i,j,k) - xyz_QVapSat(i,j,k) ) &
!                &    / ( CpDry + LatentHeat * xyz_DQVapSatDTemp(i,j,k) )

              !=========
              ! check routine
              !---------
!!$              TempBefAdj = xyz_Temp(i,j,k)
!!$              QVapBefAdj = xyz_QVap(i,j,k)
              !=========

              ! 温度と比湿の調節
              ! Adjust temperature and specific humidity
              !
!              xyz_Temp(i,j,k) = xyz_Temp(i,j,k) + DelTemp
!              xyz_QVap(i,j,k) = xyz_QVapSat(i,j,k) + xyz_DQVapSatDTemp(i,j,k) * DelTemp

              !=========
              ! check routine
              !---------
!!$              write( 6, * ) '====='
!!$              write( 6, * ) 'Energy difference before and after adjustment and each energy'
!!$              write( 6, * ) &
!!$                &     CpDry * TempBefAdj      + LatentHeat * QVapBefAdj            &
!!$                & - ( CpDry * xyz_Temp(i,j,k) + LatentHeat * xyz_QVap(i,j,k) ),    &
!!$                &     CpDry * TempBefAdj      + LatentHeat * QVapBefAdj,           &
!!$                &   ( CpDry * xyz_Temp(i,j,k) + LatentHeat * xyz_QVap(i,j,k) )
              !=========


!            end if

!          end do
!        end do
!      end do

!    end do

    ! 比湿変化率, 温度変化率, 降水量の算出
    ! Calculate specific humidity tendency, temperature tendency, 
    ! precipitation
    !
    xyz_DQVapDtLsc = ( xyz_QVap - xyz_QVapB ) / ( 2.0_DP * DelTime )

    xyz_DTempDtLsc = ( xyz_Temp - xyz_TempB ) / ( 2.0_DP * DelTime )

    ! OLD CODE TO BE DELETED
    !
!!$    xy_RainLsc     = 0.
!!$    do k = kmax, 1, -1
!!$      xy_RainLsc = xy_RainLsc &
!!$        & + ( xyz_Temp(:,:,k) - xyz_TempB(:,:,k) ) &
!!$        &     * CpDry / ( 2.0_DP * DelTime ) &
!!$        &     * ( xyr_Press(:,:,k-1) - xyr_Press(:,:,k) ) / Grav &
!!$        &     / LatentHeat
!!$    end do

!!$    i = 0
!!$    j = jmax/2+1
!!$    write( 6, * ) xy_RainLsc(i,j)

    xy_RainLsc     = 0.0d0
    do k = kmax, 1, -1
      xy_RainLsc = xy_RainLsc                                     &
        & + ( xyr_Press(:,:,k-1) - xyr_Press(:,:,k) ) / Grav      &
        &   * ( xyz_QVapB(:,:,k) - xyz_QVap(:,:,k) )
    end do
    xy_RainLsc = xy_RainLsc / ( 2.0_DP * DelTime )

!!$    i = 0
!!$    j = jmax/2+1
!!$    write( 6, * ) xy_RainLsc(i,j)
!!$    write( 6, * ) '---'


    xy_Rain     = xy_Rain     + xy_RainLsc
    xyz_DTempDt = xyz_DTempDt + xyz_DTempDtLsc
    xyz_DQVapDt = xyz_DQVapDt + xyz_DQVapDtLsc

    ! ヒストリデータ出力
    ! History data output
    !
    call HistoryAutoPut( TimeN, 'RainLsc',    xy_RainLsc * LatentHeat )
    call HistoryAutoPut( TimeN, 'DTempDtLsc', xyz_DTempDtLsc )
    call HistoryAutoPut( TimeN, 'DQVapDtLsc', xyz_DQVapDtLsc )


    if ( present( xyz_DDelLWDtLSC ) ) then
      do k = 1, kmax
        xyz_DDelLWDtLSC(:,:,k) = &
          & - xyz_DQVapDtLsc(:,:,k) * ( xyr_Press(:,:,k-1) - xyr_Press(:,:,k) ) / Grav
      end do
    end if


    ! 計算時間計測一時停止
    ! Pause measurement of computation time
    !
    call TimesetClockStop( module_name )

  end subroutine LScaleCond

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

  attributes(global) subroutine LScaleCondCUDA( &
    imax, jmax, kmax, ItrtMax, LatentHeat, CpDry, EpsV, GasRWet, GasRUniv, &
    CtrlRH, &
    xyz_Press, xyz_Temp, xyz_QVap, xyz_QVapSat, xyz_DQVapSatDTemp &
    )
    
    real(8), dimension(*) :: xyz_Press, xyz_Temp, xyz_QVap, &
      xyz_QVapSat, xyz_DQVapSatDTemp
    real(8), value :: LatentHeat, CpDry, EpsV, GasRWet, GasRUniv, CtrlRH

#ifdef LIB_SATURATE_NHA1992
    real(8), parameter:: LatHeat_nha1992 = 43655
    real(8), parameter:: P0 = 1.4e+11
#elif LIB_SATURATE_T1930
    real(8), parameter :: Es0 = 611.0_DP
#else
    real(8), parameter :: Es0 = 611.0_DP
#endif

    real(8), shared :: DelTemp(128), DQVapSatDTemp(128), FlagSaturated(128), &
      Press(128), Temp(128), QVap(128), TempB(128), QVapB(128), QVapSat(128)
    integer, value :: imax, jmax, kmax, ItrtMax, i,j,k,itr, ii, tix

    ii = (blockidx%x - 1) * blockdim%x + threadidx%x
    tix = threadidx%x

! shared memory に格納
    Press(tix) = xyz_Press(ii)
    QVap(tix) = xyz_QVap(ii)
    Temp(tix) = xyz_Temp(ii)


    ! 調節前 "QVap", "Temp" の保存
    ! Store "QVap", "Temp" before adjustment
    !
!    xyz_QVapB  = xyz_QVap
!    xyz_TempB  = xyz_Temp

    QVapB(tix) = QVap(tix)
    TempB(tix) = Temp(tix)


    ! 調節
    ! Adjustment
    !

    ! 飽和比湿計算
    ! Calculate saturation specific humidity 
    !
!    xyz_QVapSat = xyz_CalcQVapSat( xyz_Temp, xyz_Press )

    QVapSat(tix) = CalcQVapSatCUDA(EpsV, P0, Press(tix), LatHeat_nha1992, GasRUniv, Temp(tix))

!    do k = 1, kmax
!      do j = 1, jmax
!        do i = 0, imax-1
!          if ( ( xyz_QVap(i,j,k) / xyz_QVapSat(i,j,k) ) >= CrtlRH ) then
!!            xyz_FlagSaturated(i,j,k) = .true.
!            xyz_FlagSaturated(i,j,k) = 1
!          else
!!            xyz_FlagSaturated(i,j,k) = .false.
!            xyz_FlagSaturated(i,j,k) = 0
!          end if
!        end do
!      end do
!    end do

    if ( ( QVap(tix) / QVapSat(tix) ) >= CtrlRH ) then
      FlagSaturated(tix) = 1
    else
      FlagSaturated(tix) = 0
    end if



    do itr = 1, ItrtMax

      !    xyz_QVapSat       = xyz_CalcQVapSat      ( xyz_Temp, xyz_Press   )
      !    xyz_DQVapSatDTemp = xyz_CalcDQVapSatDTemp( xyz_Temp, xyz_QVapSat )

#ifdef LIB_SATURATE_NHA1992
      QVapSat(tix)       =  EpsV * ( P0 / Press(tix) ) &
        & * exp ( - LatHeat_nha1992 / ( GasRUniv * Temp(tix) ) )
      DQVapSatDTemp(tix) = LatHeat_nha1992 * QVapSat(tix) / ( GasRUniv * Temp(tix)**2 )
#elif LIB_SATURATE_T1930
      QVapSat(tix)       = EpsV * Es0 * &
        & exp( LatentHeat / GasRWet * ( 1./273. - 1./Temp(tix) ) ) / Press(tix)
      DQVapSatDTemp(tix) = LatentHeat * QVapSat(tix) / ( GasRWet * Temp(tix)**2 )
#else
      QVapSat(tix)       = EpsV * Es0 * &
        & exp( LatentHeat / GasRWet * ( 1./273. - 1./Temp(tix) ) ) / Press(tix)
      DQVapSatDTemp(tix) = LatentHeat * QVapSat(tix) / ( GasRWet * Temp(tix)**2 )
#endif

      DelTemp(tix) = &
        & LatentHeat * ( QVap(tix) - QVapSat(tix) ) &
        &    / ( CpDry + LatentHeat * DQVapSatDTemp(tix) )
    
      DelTemp(tix) = DelTemp(tix) * FlagSaturated(tix)
    
      Temp(tix) = Temp(tix) + DelTemp(tix)
      QVap(tix) = &
        (1 - FlagSaturated(tix)) * QVap(tix) &
        + FlagSaturated(tix) * ( QVapSat(tix) + DQVapSatDTemp(tix) * DelTemp(tix) )
    end do

    xyz_Temp(ii) = Temp(tix)
    xyz_QVap(ii) = QVap(tix)

! debug (for single thread)
!!$    do k = 1, kmax
!!$      do j = 1, jmax
!!$        do i = 1, imax
!!$          ii = i + (j-1)*imax + (k-1)*imax*jmax
!!$
!!$          if ( xyz_FlagSaturated( ii ) .eq. 1 ) then
!!$            DelTemp = &
!!$              & LatentHeat * ( xyz_QVap(ii) - xyz_QVapSat(ii) ) &
!!$              &    / ( CpDry + LatentHeat * xyz_DQVapSatDTemp(ii) )
!!$
!!$            xyz_Temp(ii) = xyz_Temp(ii) + DelTemp
!!$            xyz_QVap(ii) = xyz_QVapSat(ii) + xyz_DQVapSatDTemp(ii) * DelTemp
!!$          end if
!!$
!!$        end do
!!$      end do
!!$    end do



  contains

    function CalcQVapSatCUDA(EpsV, P0, Press, LatHeat_nha1992, GasRUniv, Temp)

      CalcQVapSatCUDA  =  EpsV * ( P0 / Press ) &
        & * exp ( - LatHeat_nha1992 / ( GasRUniv * Temp ) )

    end function CalcQVapSatCUDA

  end subroutine LScaleCondCUDA

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

!!$  attributes(device) function CalcQVapSatCUDA(Temp, Press, EpsV, LatHeat, GasRWet, GasRUniv)
!!$    real(8) :: CalcQVapSatCUDA, Temp, Press, EpsV, LatHeat, GasRWet, GasRUniv
!!$
!!$#ifdef LIB_SATURATE_NHA1992
!!$    CalcQVapSatCUDA = CalcQVapSat_nha1992(Temp, Press, EpsV, GasRUniv)
!!$#elif LIB_SATURATE_T1930
!!$    CalcQVapSatCUDA = CalcQVapSat_t1930(Temp, Press, EpsV, LatHeat, GasRWet)
!!$#else
!!$    CalcQVapSatCUDA = CalcQVapSat_t1930(Temp, Press, EpsV, LatHeat, GasRWet)
!!$#endif
!!$
!!$  end function CalcQVapSatCUDA
!!$
!!$
!!$  attributes(device) function CalcDQVapSatDTempCUDA(Temp, QVapSat, LatHeat, GasRWet, GasRUniv)
!!$    real(8) :: CalcDQVapSatDTempCUDA, Temp, QVapSat, EpsV, LatHeat, GasRWet, GasRUniv
!!$
!!$#ifdef LIB_SATURATE_NHA1992
!!$    CalcDQVapSatDTempCUDA = CalcDQVapSatDTemp_nha1992(Temp, QVapSat, GasRUniv)
!!$#elif LIB_SATURATE_T1930
!!$    CalcDQVapSatDTempCUDA = CalcDQVapSatDTemp_t1930(Temp, QVapSat, LatHeat, GasRWet)
!!$#else
!!$    CalcDQVapSatDTempCUDA = CalcDQVapSatDTemp_t1930(Temp, QVapSat, LatHeat, GasRWet)
!!$#endif
!!$
!!$  end function CalcDQVapSatDTempCUDA
!!$
!!$  !-------------------------------------------------------------------
!!$
!!$  attributes(device) function CalcQVapSat_t1930(Temp, Press, EpsV, LatHeat, GasRWet)
!!$    real(8), value :: CalcQVapSat_t1930, Temp, Press, EpsV, LatHeat, GasRWet
!!$    real(8), parameter :: Es0 = 611.0_DP
!!$
!!$    CalcQVapSat_t1930 = &
!!$      & EpsV * Es0 &
!!$      &  * exp( LatHeat / GasRWet * ( 1./273. - 1./Temp ) ) / Press
!!$
!!$  end function CalcQVapSat_t1930
!!$
!!$  attributes(device) function CalcDQVapSatDTemp_t1930(Temp, QVapSat, LatHeat, GasRWet)
!!$    real(8), value :: CalcDQVapSatDTemp_t1930, Temp, QVapSat, EpsV, LatHeat, GasRWet
!!$
!!$    CalcDQVapSatDTemp_t1930 = &
!!$      & LatHeat * QVapSat / ( GasRWet * Temp**2 )
!!$
!!$  end function CalcDQVapSatDTemp_t1930
!!$
!!$  !-------------------------------------------------------------------
!!$
!!$  attributes(device) function CalcQVapSat_nha1992(Temp, Press, EpsV, GasRUniv)
!!$    real(8), value :: CalcQVapSat_nha1992, Temp, Press, EpsV, GasRUniv
!!$    real(8), parameter:: LatHeat = 43655
!!$    real(8), parameter:: P0 = 1.4e+11
!!$
!!$    CalcQVapSat_nha1992 = &
!!$      & EpsV * ( P0 / Press ) &
!!$      &   * exp ( - LatHeat / ( GasRUniv * Temp ) )
!!$
!!$  end function CalcQVapSat_nha1992
!!$
!!$  attributes(device) function CalcDQVapSatDTemp_nha1992(Temp, QVapSat, GasRUniv)
!!$    real(8), value :: CalcDQVapSatDTemp_nha1992, Temp, QVapSat, GasRUniv
!!$    real(8), parameter:: LatHeat = 43655
!!$    real(8), parameter:: P0 = 1.4e+11
!!$
!!$    CalcDQVapSatDTemp_nha1992 = QVapSat * LatHeat / ( GasRUniv * Temp**2 )
!!$
!!$  end function CalcDQVapSatDTemp_nha1992

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

  subroutine LSCondInit
    !
    ! lscond モジュールの初期化を行います. 
    ! NAMELIST#lscond_nml の読み込みはこの手続きで行われます. 
    !
    ! "lscond" module is initialized. 
    ! "NAMELIST#lscond_nml" is loaded in this procedure. 
    !

    ! モジュール引用 ; USE statements
    !

    ! NAMELIST ファイル入力に関するユーティリティ
    ! Utilities for NAMELIST file input
    !
    use namelist_util, only: namelist_filename, NmlutilMsg, NmlutilAryValid

    ! ファイル入出力補助
    ! File I/O support
    !
    use dc_iounit, only: FileOpen

    ! 種別型パラメタ
    ! Kind type parameter
    !
    use dc_types, only: STDOUT ! 標準出力の装置番号. Unit number of standard output

    ! 文字列操作
    ! Character handling
    !
    use dc_string, only: StoA

    ! ヒストリデータ出力
    ! History data output
    !
    use gtool_historyauto, only: HistoryAutoAddVariable

    ! 宣言文 ; Declaration statements
    !
    implicit none

    integer:: unit_nml        ! NAMELIST ファイルオープン用装置番号. 
                              ! Unit number for NAMELIST file open
    integer:: iostat_nml      ! NAMELIST 読み込み時の IOSTAT. 
                              ! IOSTAT of NAMELIST read

    ! NAMELIST 変数群
    ! NAMELIST group name
    !
    namelist /lscond_nml/ &
      & CrtlRH, ItrtMax, FlagUse
          !
          ! デフォルト値については初期化手続 "lscond#LSCondInit" 
          ! のソースコードを参照のこと. 
          !
          ! Refer to source codes in the initialization procedure
          ! "lscond#LSCondInit" for the default values. 
          !

    ! 実行文 ; Executable statement
    !

    if ( lscond_inited ) return
    call InitCheck

    ! デフォルト値の設定
    ! Default values settings
    !
    CrtlRH  = 1.0_DP
    ItrtMax = 3
    FlagUse = .true.

    ! NAMELIST の読み込み
    ! NAMELIST is input
    !
    if ( trim(namelist_filename) /= '' ) then
      call FileOpen( unit_nml, &          ! (out)
        & namelist_filename, mode = 'r' ) ! (in)

      rewind( unit_nml )
      read( unit_nml, &         ! (in)
        & nml = lscond_nml, &   ! (out)
        & iostat = iostat_nml ) ! (out)
      close( unit_nml )

      call NmlutilMsg( iostat_nml, module_name ) ! (in)
      if ( iostat_nml == 0 ) write( STDOUT, nml = lscond_nml )
    end if

    ! ヒストリデータ出力のためのへの変数登録
    ! Register of variables for history data output
    !
    call HistoryAutoAddVariable( 'RainLsc', &
      & (/ 'lon ', 'lat ', 'time' /), &
      & 'precipitation by large scale condensation', 'W m-2' )
    call HistoryAutoAddVariable( 'DTempDtLsc', &
      & (/ 'lon ', 'lat ', 'sig ', 'time' /), &
      & 'large-scale condensation heating', 'K s-1' )
    call HistoryAutoAddVariable( 'DQVapDtLsc', &
      & (/ 'lon ', 'lat ', 'sig ', 'time' /), &
      & 'large-scale condensation moistening', 'kg kg-1 s-1' )

    ! 印字 ; Print
    !
    call MessageNotify( 'M', module_name, '----- Initialization Messages -----' )
    call MessageNotify( 'M', module_name, '  FlagUse = %b', l = (/ FlagUse /) )
    call MessageNotify( 'M', module_name, '  CrtlRH  = %f', d = (/ CrtlRH /) )
    call MessageNotify( 'M', module_name, '  ItrtMax = %d', i = (/ ItrtMax /) )
    call MessageNotify( 'M', module_name, '' )
    call MessageNotify( 'M', module_name, '-- version = %c', c1 = trim(version) )

    lscond_inited = .true.
  end subroutine LSCondInit

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

  subroutine InitCheck
    !
    ! 依存モジュールの初期化チェック
    !
    ! Check initialization of dependency modules

    ! モジュール引用 ; USE statements
    !

    ! NAMELIST ファイル入力に関するユーティリティ
    ! Utilities for NAMELIST file input
    !
    use namelist_util, only: namelist_util_inited

    ! 格子点設定
    ! Grid points settings
    !
    use gridset, only: gridset_inited

    ! 物理定数設定
    ! Physical constants settings
    !
    use constants, only: constants_inited

    ! 座標データ設定
    ! Axes data settings
    !
    use axesset, only: axesset_inited

    ! 時刻管理
    ! Time control
    !
    use timeset, only: timeset_inited

    ! 実行文 ; Executable statement
    !

    if ( .not. namelist_util_inited ) &
      & call MessageNotify( 'E', module_name, '"namelist_util" module is not initialized.' )

    if ( .not. gridset_inited ) &
      & call MessageNotify( 'E', module_name, '"gridset" module is not initialized.' )

    if ( .not. constants_inited ) &
      & call MessageNotify( 'E', module_name, '"constants" module is not initialized.' )

    if ( .not. axesset_inited ) &
      & call MessageNotify( 'E', module_name, '"axesset" module is not initialized.' )

    if ( .not. timeset_inited ) &
      & call MessageNotify( 'E', module_name, '"timeset" module is not initialized.' )

  end subroutine InitCheck

end module lscond
