!= 大規模凝結
!
!= Large scale condensation
!
! Authors::   Yukiko YAMADA, Yasuhiro MORIKAWA
! Version::   $Id: phy_lscond.f90,v 1.9 2008-06-08 15:38:47 morikawa Exp $
! Tag Name::  $Name: dcpam4-20080609-1 $
! Copyright:: Copyright (C) GFD Dennou Club, 2007. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]   
!

module phy_lscond
  !
  != 大規模凝結
  !
  != Large scale condensation
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  ! 大規模凝結過程によって温度と比湿を調節します. 
  ! 飽和比湿の計算には Nakajima et al. (1992) を用いています. 
  ! 詳しくは phy_saturate_nha92 を参照してください. 
  !
  ! Adjust temperature and specific humidity by 
  ! a large scale condensation process.
  ! Nakajima et al. (1992) is used for calculation of 
  ! saturation specific humidity. 
  ! For details, see "phy_saturate_nha92". 
  !
  !== Procedures List
  !
  ! Create        :: PHYLSC 型変数の初期設定
  ! LScaleCond    :: 温度と比湿の調節
  ! Close         :: PHYLSC 型変数の終了処理
  ! PutLine       :: PHYLSC 型変数に格納されている情報の印字
  ! initialized   :: PHYLSC 型変数が初期設定されているか否か
  ! ------------  :: ------------
  ! Create        :: Constructor of "PHYLSC"
  ! LScaleCond    :: Adjust temperature and specific humidity
  ! Close         :: Deconstructor of "PHYLSC"
  ! PutLine       :: Print information of "PHYLSC"
  ! initialized   :: Check initialization of "PHYLSC"
  !
  !== Usage
  !
  ! 始めに, PHYLSC 型の変数を定義し, Create で初期設定を行います.
  ! LScaleCond を用いて温度と湿度の調節を行います. 
  ! PHYLSC 型の変数の終了処理には Close を用いてください.
  !
  ! First, initialize "PHYLSC" by "Create".
  ! In order to adjust temperature and specific humidity, use "LScaleCond". 
  ! In order to terminate "PHYLSC", use "Close".
  !

  use dc_types, only: DP, TOKEN
!!$  use phy_saturate_nha92, only: PHYSATNHA
  implicit none
  private
  public:: PHYLSC, Create, Close, PutLine, initialized, LScaleCond

  type PHYLSC
    !
    ! まず, Create で "PHYLSC" 型の変数を初期設定して下さい.
    ! 初期設定された "PHYLSC" 型の変数を再度利用する際には,
    ! Close によって終了処理を行ってください.
    !
    ! Initialize "PHYLSC" variable by "Create" before usage.
    ! If you reuse "PHYLSC" variable again for another application, 
    ! terminate by "Close".
    !
    logical:: initialized = .false.     ! 初期設定フラグ. 
                                        ! Initialization flag
    integer:: imax ! 経度格子点数. 
                   ! Number of grid points in longitude
    integer:: jmax ! 緯度格子点数. 
                   ! Number of grid points in latitude
    integer:: kmax ! 鉛直層数. 
                   ! Number of vertical level
    real(DP):: Grav      ! $ g $ .      重力加速度.     Gravitational acceleration
    real(DP):: Cp        ! $ C_p $ .    大気定圧比熱.   Specific heat of air at constant pressure

    real(DP):: DelTime    ! $ \Delta t $ . タイムステップ. Time step

    real(DP):: CrtlRH
                              ! 臨界相対湿度. 
                              ! Critical relative humidity
    integer:: IterationMax
                              ! イテレーション回数. 
                              ! Number of iteration
    integer :: dummy0         ! 8 ビット境界用のダミー変数.      Dummy variable for 8 bit boundary

    !-----------------------------------
    !  飽和比湿の計算に用いられる情報
    !  Information for calculation of saturation specific humidity
    real(DP):: EL        ! $ L $ .      水の凝結の潜熱. Latent heat of condensation of water vapor
    real(DP):: RVap      ! $ R_v $ .    水蒸気気体定数. Gas constant of water vapor
    real(DP):: EpsV      ! $ \epsilon_v $ .        水蒸気分子量比. Molecular weight ratio of water vapor

!!$    real(DP):: ES0 = 611.0_DP
    real(DP):: ES0
                              ! $ e^{*} $ (273K) . 
                              ! 0 ℃での飽和蒸気圧. Saturation vapor pressure at 0 degrees C

    real(DP):: RUniv = 8.314_DP
                              ! $ R $ [J mol-1 K-1].
                              ! 普遍気体定数. Universal gas constant
    real(DP):: LatHeat = 43655_DP
                              ! $ l $ [J mol-1].
                              ! 水の凝結の潜熱. Latent heat of condensation of water vapor
    real(DP):: P0 = 1.4e+11_DP
                              ! $ p_0^{*} $ [Pa].
                              ! 水蒸気飽和曲線の定数. constant for water vapor saturation curve

!!$    !-----------------------------------
!!$    !  飽和比湿計算用オブジェクト
!!$    !  Object for calculation of saturation specific humidity
!!$    type(PHYSATNHA):: phy_sat

  end type PHYLSC

  character(*), parameter:: version = &
    & '$Name: dcpam4-20080609-1 $' // &
    & '$Id: phy_lscond.f90,v 1.9 2008-06-08 15:38:47 morikawa Exp $'

  interface Create
    module procedure PhyLSCondCreate
  end interface

  interface Close
    module procedure PhyLSCondClose
  end interface

  interface PutLine
    module procedure PhyLSCondPutLine
  end interface

  interface initialized
    module procedure PhyLSCondInitialized
  end interface

  interface NmlRead
    module procedure PhyLSCondNmlRead
  end interface

  interface LScaleCond
    module procedure PhyLSCondLScaleCond
  end interface

!!$  interface Sample
!!$    module procedure PhyLSCondSample
!!$  end interface

contains

  subroutine PhyLSCondCreate( phy_lsc, &
    & imax, jmax, kmax, &
    & Grav, Cp, EL, RVap, EpsV, ES0, &
    & DelTime, &
    & nmlfile, err )
    !
    ! PHYLSC 型の変数の初期設定を行います.
    ! 他のサブルーチンを使用する前に必ずこのサブルーチンによって
    ! PHYLSC 型の変数を初期設定してください.
    !
    ! なお, 与えられた *phy_lsc* が既に初期設定されている場合,
    ! プログラムはエラーを発生させます.
    !
    ! NAMELIST を利用する場合には引数 *nmlfile* に NAMELIST ファイル名
    ! を与えてください. NAMELIST 変数群の詳細に関しては 
    ! NAMELIST#phy_lscond_nml を参照してください. 
    !
    ! Constructor of "PHYLSC".
    ! Initialize *phy_lsc* by this subroutine, 
    ! before other procedures are used, 
    !
    ! Note that if *phy_lsc* is already initialized 
    ! by this procedure, error is occurred.
    !
    ! In order to use NAMELIST, specify a NAMELIST filename to 
    ! argument *nmlfile*. See "NAMELIST#phy_lscond_nml"
    ! for details about a NAMELIST group.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_string, only: PutLine, Printf
    use dc_types, only: DP, STRING, TOKEN, STDOUT
    use dc_present, only: present_and_not_empty, present_and_true
    use dc_message, only: MessageNotify
    use dc_error, only: StoreError, DC_NOERR, DC_EALREADYINIT, &
      & DC_EARGLACK, DC_ENEGATIVE, DC_ENOFILEREAD
!!$    use phy_saturate_nha92, only: PhySatNhaCreate
    implicit none
    type(PHYLSC), intent(inout):: phy_lsc
    integer, intent(in):: imax ! 経度格子点数. 
                   ! Number of grid points in longitude
    integer, intent(in):: jmax ! 緯度格子点数. 
                   ! Number of grid points in latitude
    integer, intent(in):: kmax ! 鉛直層数. 
                   ! Number of vertical level
    real(DP), intent(in):: Grav      ! $ g $ .      重力加速度.     Gravitational acceleration
    real(DP), intent(in):: Cp        ! $ C_p $ .    大気定圧比熱.   Specific heat of air at constant pressure
    real(DP), intent(in):: EL        ! $ L $ .      水の凝結の潜熱. Latent heat of condensation of water vapor
    real(DP), intent(in):: RVap      ! $ R_v $ .    水蒸気気体定数. Gas constant of water vapor
    real(DP), intent(in):: EpsV      ! $ \epsilon_v $ .        水蒸気分子量比. Molecular weight ratio of water vapor
    real(DP), intent(in):: ES0       ! $ e^{*} $ (273K) .      0 ℃での飽和蒸気圧. Saturation vapor pressure at 0 degrees C
    real(DP), intent(in):: DelTime    ! $ \Delta t $ . タイムステップ. Time step
    character(*), intent(in), optional:: nmlfile
                              ! NAMELIST ファイルの名称. 
                              ! この引数に空文字以外を与えた場合, 
                              ! 指定されたファイルから 
                              ! NAMELIST 変数群を読み込みます. 
                              ! ファイルを読み込めない場合にはエラーを
                              ! 生じます.
                              !
                              ! NAMELIST 変数群の詳細に関しては 
                              ! NAMELIST#phy_lscond_nml 
                              ! を参照してください. 
                              !
                              ! NAMELIST file name. 
                              ! If nonnull character is specified to
                              ! this argument, 
                              ! NAMELIST group name is loaded from the 
                              ! file. 
                              ! If the file can not be read, 
                              ! an error occurs.
                              ! 
                              ! See "NAMELIST#phy_lscond_nml" 
                              ! for details about a NAMELIST group.
                              ! 
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 

    !-----------------------------------
    !  作業変数
    !  Work variables
    integer:: stat
    character(STRING):: cause_c
    character(*), parameter:: subname = 'PhyLSCondCreate'
  continue
    call BeginSub( subname, version )
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------
    if ( phy_lsc % initialized ) then
      stat = DC_EALREADYINIT
      cause_c = 'PHYLSC'
      goto 999
    end if

    !-----------------------------------------------------------------
    !  引数の正当性のチェック
    !  Validate arguments
    !-----------------------------------------------------------------
    if (imax < 1) then
      stat = DC_ENEGATIVE
      cause_c = 'imax'
      goto 999
    end if
    if (jmax < 1) then
      stat = DC_ENEGATIVE
      cause_c = 'jmax'
      goto 999
    end if
    if (kmax < 1) then
      stat = DC_ENEGATIVE
      cause_c = 'kmax'
      goto 999
    end if
    if (DelTime < 0.0_DP) then
      stat = DC_ENEGATIVE
      cause_c = 'DelTime'
      goto 999
    end if

    !-----------------------------------------------------------------
    !  "PHYLSC" の設定
    !  Configure the settings for "PHYLSC"
    !-----------------------------------------------------------------
    phy_lsc % imax    = imax   
    phy_lsc % jmax    = jmax   
    phy_lsc % kmax    = kmax   
    phy_lsc % Grav    = Grav   
    phy_lsc % Cp      = Cp     
    phy_lsc % EL      = EL     
    phy_lsc % RVap    = RVap   
    phy_lsc % EpsV    = EpsV   
    phy_lsc % ES0     = ES0    
    phy_lsc % DelTime = DelTime

    !-------------------------
    !  デフォルト値
    !  Default values
!!$    phy_lsc % param_r = 0.0_DP
!!$    phy_lsc % param_c = 'hogehoge'

    !-------------------------
    !  オプショナル引数からの値
    !  Values from optional arguments
!!$    phy_lsc % param_i = param_i
!!$    if ( present(param_r) )  phy_lsc % param_r = param_r
!!$    if ( present(param_c) )  phy_lsc % param_c = param_c

    !-------------------------
    !  NAMELIST からの値
    !  Values from NAMELIST

!!$    if ( present_and_not_empty(nmlfile) ) then
!!$      call MessageNotify( 'M', subname, &
!!$        & 'Loading NAMELIST file "%c" ...', &
!!$        & c1 = trim(nmlfile) )
!!$      call NmlRead ( nmlfile = nmlfile, &      ! (in)
!!$        & param_i = phy_lsc % param_i, &   ! (inout)
!!$        & param_r = phy_lsc % param_r, &   ! (inout)
!!$        & param_c_ = phy_lsc % param_c, &  ! (inout)
!!$        & err = err )                          ! (out)
!!$      if ( present_and_true(err) ) then
!!$        call MessageNotify( 'W', subname, &
!!$          & '"%c" can not be read.', &
!!$          & c1 = trim(nmlfile) )
!!$        stat = DC_ENOFILEREAD
!!$        cause_c = nmlfile
!!$        goto 999
!!$      end if
!!$    end if

    !-----------------------------------------------------------------
    !  臨界相対湿度や不安定の許容誤差の設定
    !  Configure critical relative humidity and admissible error of unstability
    !-----------------------------------------------------------------
    phy_lsc % CrtlRH = 1.0_DP
    phy_lsc % IterationMax = 3

    !-----------------------------------------------------------------
    !  設定値の正当性のチェック
    !  Validate setting values
    !-----------------------------------------------------------------
!!$    if ( phy_lsc % param_i < 0 ) then
!!$      stat = DC_ENEGATIVE
!!$      cause_c = 'param_i'
!!$      goto 999
!!$    end if

!!$    !-----------------------------------------------------------------
!!$    !  飽和比湿計算用オブジェクトの初期化
!!$    !  Initialize object for calculation of saturation specific humidity
!!$    !-----------------------------------------------------------------
!!$    call PhySatNhaCreate( &
!!$      & phy_sat_nha = phy_lsc % phy_sat, &       ! (out)
!!$      & imax = imax, jmax = jmax, kmax = kmax, & ! (in)
!!$      & EpsV = EpsV, &                           ! (in)
!!$      & err = err )                              ! (out)

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
    phy_lsc % initialized = .true.
999 continue
    call StoreError( stat, subname, err, cause_c )
    call EndSub( subname )
  end subroutine PhyLSCondCreate

  subroutine PhyLSCondLScaleCond( phy_lsc, &
    & xyz_Temp, xyz_QVap, &
    & xyz_Press, xyr_Press, &
    & xy_Rain, xyz_DTempDt, xyz_DQVapDt, &
    & err )
    !
    ! 対流調節スキームにより, 温度と比湿を調節します. 
    !
    ! なお, 与えられた *phy_lsc* が Create によって初期設定
    ! されていない場合, プログラムはエラーを発生させます.
    !
    ! Adjust temperature and specific humidity by 
    ! convective adjustment scheme.
    !
    ! If *phy_lsc* is not initialized by "Create" yet,
    ! error is occurred.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_string, only: PutLine, Printf
    use dc_types, only: DP, STRING, TOKEN, STDOUT
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
!!$    use phy_saturate_nha92, only: CalcQVapSat, CalcDQVapSatDTemp
    implicit none
    type(PHYLSC), intent(inout):: phy_lsc
    real(DP), intent(inout):: xyz_Temp (0:phy_lsc%imax-1, 0:phy_lsc%jmax-1, 0:phy_lsc%kmax-1)
                              ! $ T $ .     温度. Temperature
    real(DP), intent(inout):: xyz_QVap (0:phy_lsc%imax-1, 0:phy_lsc%jmax-1, 0:phy_lsc%kmax-1)
                              ! $ q $ .     比湿. Specific humidity
    real(DP), intent(in):: xyz_Press (0:phy_lsc%imax-1, 0:phy_lsc%jmax-1, 0:phy_lsc%kmax-1)
                              ! $ P_s $ . 地表面気圧 (整数レベル). 
                              ! Surface pressure (full level)
    real(DP), intent(in):: xyr_Press (0:phy_lsc%imax-1, 0:phy_lsc%jmax-1, 0:phy_lsc%kmax)
                              ! $ P_s $ . 地表面気圧 (半整数レベル). 
                              ! Surface pressure (half level)
    real(DP), intent(out):: xy_Rain (0:phy_lsc%imax-1, 0:phy_lsc%jmax-1)
                              ! 積雲スキームによる降水量. 
                              ! Precipitation by cumulus scheme
    real(DP), intent(out):: xyz_DTempDt (0:phy_lsc%imax-1, 0:phy_lsc%jmax-1, 0:phy_lsc%kmax-1)
                              ! 積雲スキームによる温度変化率. 
                              ! Temperature tendency by cumulus scheme
    real(DP), intent(out):: xyz_DQVapDt (0:phy_lsc%imax-1, 0:phy_lsc%jmax-1, 0:phy_lsc%kmax-1)
                              ! 積雲スキームによる比湿変化率. 
                              ! Specific humidity tendency by cumulus scheme
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 

    !-----------------------------------
    !  作業変数
    !  Work variables
    integer:: imax ! 経度格子点数. 
                   ! Number of grid points in longitude
    integer:: jmax ! 緯度格子点数. 
                   ! Number of grid points in latitude
    integer:: kmax ! 鉛直層数. 
                   ! Number of vertical level
    real(DP):: Grav      ! $ g $ .      重力加速度.     Gravitational acceleration
    real(DP):: Cp        ! $ C_p $ .    大気定圧比熱.   Specific heat of air at constant pressure
    real(DP):: DelTime    ! $ \Delta t $ . タイムステップ. Time step

    real(DP):: CrtlRH
                              ! 臨界相対湿度. 
                              ! Critical relative humidity
    integer:: IterationMax
                              ! イテレーション回数. 
                              ! Number of iteration

    real(DP):: EL        ! $ L $ .      水の凝結の潜熱. Latent heat of condensation of water vapor
    real(DP):: RVap      ! $ R_v $ .    水蒸気気体定数. Gas constant of water vapor
    real(DP):: EpsV      ! $ \epsilon_v $ .        水蒸気分子量比. Molecular weight ratio of water vapor
    real(DP):: ES0       ! $ e^{*} $ (273K) .      0 ℃での飽和蒸気圧. Saturation vapor pressure at 0 degrees C

    real(DP):: RUniv
                              ! $ R $ [J mol-1 K-1].
                              ! 普遍気体定数. Universal gas constant
    real(DP):: LatHeat
                              ! $ l $ [J mol-1].
                              ! 水の凝結の潜熱. Latent heat of condensation of water vapor
    real(DP):: P0
                              ! $ p_0^{*} $ [Pa].
                              ! 水蒸気飽和曲線の定数. constant for water vapor saturation curve


    real(DP):: xyz_QVapB (0:phy_lsc%imax-1, 0:phy_lsc%jmax-1, 0:phy_lsc%kmax-1)
                              ! 調節前の比湿. 
                              ! Specific humidity before adjust. 
    real(DP):: xyz_TempB (0:phy_lsc%imax-1, 0:phy_lsc%jmax-1, 0:phy_lsc%kmax-1)
                              ! 調節前の温度. 
                              ! Temperature before adjust. 
!!$    real(DP):: xyz_QVapSat (0:phy_lsc%imax-1, 0:phy_lsc%jmax-1, 0:phy_lsc%kmax-1)
!!$                              ! 飽和比湿. 
!!$                              ! Saturation specific humidity. 
    real(DP):: QVapSat
                              ! 飽和比湿. 
                              ! Saturation specific humidity. 
    real(DP):: DelQVap
                              ! 調節による比湿の変化量. 
                              ! Specific humidity variation by adjustment
    real(DP):: DelTemp
                              ! 調節による温度変化量. 
                              ! Temperature variation by adjustment
    real(DP):: DQVapSatDTemp
                              ! $ \DD{q_{\rm{sat}}}{T} $
    integer:: Iteration
    integer:: i, j, k         ! DO ループ用作業変数
                              ! Work variables for DO loop

    integer:: stat
    character(STRING):: cause_c
    character(*), parameter:: subname = 'PhyLSCondLScaleCond'
  continue
    call BeginSub( subname )
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------
    if ( .not. phy_lsc % initialized ) then
      stat = DC_ENOTINIT
      cause_c = 'PHYLSC'
      goto 999
    end if

    !-----------------------------------------------------------------
    !  *phy_lsc* に格納されている設定値の取り出し
    !  Fetch setting values stored in *phy_lsc*
    !-----------------------------------------------------------------
    imax    = phy_lsc % imax   
    jmax    = phy_lsc % jmax   
    kmax    = phy_lsc % kmax   
    Grav    = phy_lsc % Grav   
    Cp      = phy_lsc % Cp     
    DelTime = phy_lsc % DelTime

    CrtlRH       = phy_lsc % CrtlRH
    IterationMax = phy_lsc % IterationMax

    EL      = phy_lsc % EL     
    RVap    = phy_lsc % RVap   
    EpsV    = phy_lsc % EpsV   
    ES0     = phy_lsc % ES0    
    RUniv   = phy_lsc % RUniv  
    LatHeat = phy_lsc % LatHeat
    P0      = phy_lsc % P0     

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

    !-----------------------------------------------------------------
    !  調節
    !  Adjustment
    !-----------------------------------------------------------------
    do k = kmax-1, 0, -1
      do i = 0, imax-1
        do j = 0, jmax-1
          
          !-------------------------
          !  飽和比湿計算
          !  Calculate saturation specific humidity 

          QVapSat = EpsV * ( P0 / xyz_Press(i,j,k) ) &
            &         * exp ( - LatHeat / ( RUniv * xyz_Temp(i,j,k) ) )

!!$          call CalcQVapSat( phy_lsc % phy_sat, & ! (in)
!!$            &    Temp = xyz_Temp(i,j,k), &       ! (in)
!!$            &   Press = xyz_Press(i,j,k), &      ! (in)
!!$            & QVapSat = QVapSat )                ! (out)
!!$
!!$          QVapSat = &
!!$            & EpsV * ES0 &
!!$            &   * exp( EL / RVap &
!!$            &           * ( 1.0_DP / 273.0_DP - 1.0_DP / xyz_Temp(i,j,k) ) ) &
!!$            &   / xyz_Press(i,j,k)
          
          !-------------------------
          !  飽和していたら, 温度と比湿の変化を計算
          !  Calculate tendency of temperature and humidity 
          !  if moist is saturation. 

          if ( ( xyz_QVap(i,j,k) / QVapSat ) >= CrtlRH ) then
            
            do Iteration = 1, IterationMax
              
              !-------------------------
              !  飽和比湿計算
              !  Calculate saturation specific humidity
              QVapSat = EpsV * ( P0 / xyz_Press(i,j,k) ) &
                &         * exp ( - LatHeat / ( RUniv * xyz_Temp(i,j,k) ) )

              DQVapSatDTemp = &
                & QVapSat * ( LatHeat / ( RUniv * xyz_Temp(i,j,k)**2 ) )

!!$              call CalcQVapSat( phy_lsc % phy_sat, & ! (in)
!!$                &    Temp = xyz_Temp(i,j,k), &       ! (in)
!!$                &   Press = xyz_Press(i,j,k), &      ! (in)
!!$                & QVapSat = QVapSat )                ! (out)
!!$
!!$              call CalcDQVapSatDTemp( phy_lsc % phy_sat, & ! (in)
!!$                &          Temp = xyz_Temp(i,j,k), &       ! (in)
!!$                &         Press = xyz_Press(i,j,k), &      ! (in)
!!$                & DQVapSatDTemp = DQVapSatDTemp )          ! (out)
!!$
!!$              QVapSat = &
!!$                & EpsV * ES0  &
!!$                &   * exp( EL / RVap &
!!$                &           * ( 1.0_DP / 273.0_DP - 1.0_DP / xyz_Temp(i,j,k) ) ) &
!!$                &   / xyz_Press(i,j,k)
!!$
!!$              DQVapSatDTemp = &
!!$                & EL * QVapSat / ( RVap * xyz_Temp(i,j,k) * xyz_Temp(i,j,k) )
              !-------------------------
              !  温度と比湿の変化分をニュートン法で求める
              !  Calculate variation of temperature and specific humidity 
              !  with Newton method
              DelTemp = &
                & EL / Cp * ( xyz_QVap(i,j,k) - QVapSat ) &
                &    / ( 1.0_DP + EL / Cp * DQVapSatDTemp )
              DelQVap = DQVapSatDTemp * DelTemp 
              
              !-------------------------
              !  温度と比湿の調節
              !  Adjust temperature and specific humidity
              xyz_Temp(i,j,k) = xyz_Temp(i,j,k) + DelTemp
              xyz_QVap(i,j,k) = QVapSat + DelQVap
              
            end do
            
          end if
        end do
      end do
    end do
    
    !-----------------------------------------------------------------
    !  比湿変化率, 温度変化率, 降水量の算出
    !  Calculate specific humidity tendency, temperature tendency, 
    !  precipitation
    !-----------------------------------------------------------------
    xy_Rain     = 0.0_DP
    xyz_DTempDt = 0.0_DP
    xyz_DQvapDt = 0.0_DP

    xyz_DQVapDt = xyz_DQVapDt & 
      & + ( xyz_QVap - xyz_QVapB ) / ( 2.0_DP * DelTime )

    xyz_DTempDt = xyz_DTempDt &
      & + ( xyz_Temp - xyz_TempB ) / ( 2.0_DP * DelTime )

    do k = kmax-1, 0, -1
      xy_Rain = xy_Rain &
        & + ( xyz_Temp(:,:,k) - xyz_TempB(:,:,k) ) &
        &     * Cp / ( 2.0_DP * DelTime ) &
        &     * ( xyr_Press(:,:,k) - xyr_Press(:,:,k+1) ) / Grav
    end do

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
999 continue
    call StoreError( stat, subname, err, cause_c )
    call EndSub( subname )
  end subroutine PhyLSCondLScaleCond

  subroutine PhyLSCondClose( phy_lsc, err )
    !
    ! PHYLSC 型の変数の終了処理を行います.
    ! なお, 与えられた *phy_lsc* が Create によって初期設定
    ! されていない場合, プログラムはエラーを発生させます.
    !
    ! Deconstructor of "PHYLSC".
    ! Note that if *phy_lsc* is not initialized by "Create" yet,
    ! error is occurred.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_string, only: PutLine, Printf
    use dc_types, only: DP, STRING, TOKEN, STDOUT
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
!!$    use phy_saturate_nha92, only: PhySatNhaClose
    implicit none
    type(PHYLSC), intent(inout):: phy_lsc
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 

    !-----------------------------------
    !  作業変数
    !  Work variables
    integer:: stat
    character(STRING):: cause_c
    character(*), parameter:: subname = 'PhyLSCondClose'
  continue
    call BeginSub( subname )
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------
    if ( .not. phy_lsc % initialized ) then
      stat = DC_ENOTINIT
      cause_c = 'PHYLSC'
      goto 999
    end if

    !-----------------------------------------------------------------
    !  "PHYLSC" の設定の消去
    !  Clear the settings for "PHYLSC"
    !-----------------------------------------------------------------

!!$    !-----------------------------------------------------------------
!!$    !  飽和比湿計算用オブジェクトの終了処理
!!$    !  Terminate object for calculation of saturation specific humidity
!!$    !-----------------------------------------------------------------
!!$    call PhySatNhaClose( &
!!$      & phy_sat_nha = phy_lsc % phy_sat, & ! (inout)
!!$      & err = err )                        ! (out)

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
    phy_lsc % initialized = .false.
999 continue
    call StoreError( stat, subname, err, cause_c )
    call EndSub( subname )
  end subroutine PhyLSCondClose

  subroutine PhyLSCondPutLine( phy_lsc, unit, indent, err )
    !
    ! 引数 *phy_lsc* に設定されている情報を印字します.
    ! デフォルトではメッセージは標準出力に出力されます. 
    ! *unit* に装置番号を指定することで, 出力先を変更することが可能です.
    !
    ! Print information of *phy_lsc*.
    ! By default messages are output to standard output.
    ! Unit number for output can be changed by *unit* argument.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_string, only: PutLine, Printf
    use dc_types, only: DP, STRING, TOKEN, STDOUT
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
!!$    use phy_saturate_nha92, only: PhySatNhaPutLine
    implicit none
    type(PHYLSC), intent(in):: phy_lsc
    integer, intent(in), optional:: unit
                              ! 出力先の装置番号.
                              ! デフォルトの出力先は標準出力.
                              !
                              ! Unit number for output.
                              ! Default value is standard output.
    character(*), intent(in), optional:: indent
                              ! 表示されるメッセージの字下げ.
                              !
                              ! Indent of displayed messages.
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 

    !-----------------------------------
    !  作業変数
    !  Work variables
    integer:: stat
    character(STRING):: cause_c
    integer:: out_unit
    integer:: indent_len
    character(STRING):: indent_str
    character(*), parameter:: subname = 'PhyLSCondPutLine'
  continue
    call BeginSub( subname )
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------
    if ( present(unit) ) then
      out_unit = unit
    else
      out_unit = STDOUT
    end if

    indent_len = 0
    indent_str = ''
    if ( present(indent) ) then
      if ( len(indent) /= 0 ) then
        indent_len = len(indent)
        indent_str(1:indent_len) = indent
      end if
    end if


    !-----------------------------------------------------------------
    !  "PHYLSC" の設定の印字
    !  Print the settings for "PHYLSC"
    !-----------------------------------------------------------------
    if ( phy_lsc % initialized ) then
      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & '#<PHYLSC:: @initialized=%y', &
        & l = (/phy_lsc % initialized/) )

      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & ' @imax=%d @jmax=%d @kmax=%d', &
        & i = (/phy_lsc % imax, phy_lsc % jmax, phy_lsc % kmax/) )

      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & ' @Grav=%f @Cp=%f', &
        & d = (/ phy_lsc % Grav, phy_lsc % Cp/) )

      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & ' @EL=%f @RVap=%f @EpsV=%f @ES0=%f', &
        & d = (/ phy_lsc % EL, phy_lsc % RVap, &
        &        phy_lsc % EpsV, phy_lsc % ES0/) )

      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & ' @DelTime=%f', &
        & d = (/phy_lsc % DelTime/) )

      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & ' @CrtlRH=%f @IterationMax=%d', &
        & d = (/ phy_lsc % CrtlRH/), &
        & i = (/ phy_lsc % IterationMax/) )

      call Printf( unit = out_unit, &      ! (in)
        & fmt = indent_str(1:indent_len) // &
        &       ' @RUniv=%f @LatHeat=%f @P0=%f', & ! (in)
        & d = (/phy_lsc % RUniv, &
        &       phy_lsc % LatHeat, &
        &       phy_lsc % P0/) )               ! (in)

!!$      call Printf( out_unit, &
!!$        & indent_str(1:indent_len) // ' @phy_sat=' )
!!$      call PhySatNhaPutLine( &
!!$        & phy_sat_nha = phy_lsc % phy_sat, &           ! (in)
!!$        & unit = out_unit, &                           ! (in)
!!$        & indent = indent_str(1:indent_len) // '  ', & ! (in)
!!$        & err = err )                                  ! (out)

      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & '>' )
    else
      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & '#<PHYLSC:: @initialized=%y>', &
        & l = (/phy_lsc % initialized/) )
    end if

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
999 continue
    call StoreError( stat, subname, err, cause_c )
    call EndSub( subname )
  end subroutine PhyLSCondPutLine

  logical function PhyLSCondInitialized( phy_lsc ) result(result)
    !
    ! *phy_lsc* が初期設定されている場合には .true. が,
    ! 初期設定されていない場合には .false. が返ります.
    !
    ! If *phy_lsc* is initialized, .true. is returned.
    ! If *phy_lsc* is not initialized, .false. is returned.
    !
    implicit none
    type(PHYLSC), intent(in):: phy_lsc
  continue
    result = phy_lsc % initialized
  end function PhyLSCondInitialized

  subroutine PhyLSCondNmlRead( nmlfile, &
!!$    & param_i, param_r, param_c_, &
    & err )
    !
    ! NAMELIST ファイル *nmlfile* から値を入力するための
    ! 内部サブルーチンです. Create 内で呼び出されることを
    ! 想定しています.
    !
    ! 値が NAMELIST ファイル内で指定されていない場合には,
    ! 入力された値がそのまま返ります.
    !
    ! なお, *nmlfile* に空文字が与えられた場合, または
    ! 与えられた *nmlfile* を読み込むことができない場合, 
    ! プログラムはエラーを発生させます.
    !
    ! This is an internal subroutine to input values from 
    ! NAMELIST file *nmlfile*. This subroutine is expected to be
    ! called by "Create".
    !
    ! A value not specified in NAMELIST file is returned
    ! without change.
    !
    ! If *nmlfile* is empty, or *nmlfile* can not be read, 
    ! error is occurred.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_string, only: PutLine, Printf
    use dc_types, only: DP, STRING, TOKEN, STDOUT
    use dc_iounit, only: FileOpen
    use dc_message, only: MessageNotify
    use dc_present, only: present_and_true
    use dc_error, only: StoreError, DC_NOERR, DC_ENOFILEREAD
    implicit none
    character(*), intent(in):: nmlfile
                              ! NAMELIST ファイルの名称. 
                              ! NAMELIST file name
!!$    integer, intent(inout):: param_i
!!$    real(DP), intent(inout):: param_r
!!$    character(*), intent(inout):: param_c_
!!$    character(TOKEN):: param_c
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 

!!$    namelist /phy_lscond_nml/ &
!!$      & param_i, param_r, param_c
                              ! phy_lscond モジュール用
                              ! NAMELIST 変数群名.
                              !
                              ! phy_lscond#Create を使用する際に, 
                              ! オプショナル引数 *nmlfile* へ NAMELIST 
                              ! ファイル名を指定することで, そのファイルから
                              ! この NAMELIST 変数群を読み込みます.
                              !
                              ! NAMELIST group name for 
                              ! "phy_lscond" module.
                              ! 
                              ! If a NAMELIST filename is specified to 
                              ! an optional argument *nmlfile* 
                              ! when "phy_lscond#Create" is used, 
                              ! this NAMELIST group is loaded from 
                              ! the file.

    !-----------------------------------
    !  作業変数
    !  Work variables
    integer:: stat
    character(STRING):: cause_c
    integer:: unit_nml        ! NAMELIST ファイルオープン用装置番号. 
                              ! Unit number for NAMELIST file open
!!$    integer:: iostat_nml      ! NAMELIST 読み込み時の IOSTAT. 
!!$                              ! IOSTAT of NAMELIST read
    character(*), parameter:: subname = 'PhyLSCondNmlRead'
  continue
    call BeginSub( subname )
    stat = DC_NOERR
    cause_c = ''



    !-----------------------------------------------------------------
    !  文字型引数を NAMELIST 変数群へ代入
    !  Substitute character arguments to NAMELIST group
    !-----------------------------------------------------------------
!!$    param_c = param_c_

    !----------------------------------------------------------------
    !  NAMELIST ファイルのオープン
    !  Open NAMELIST file
    !----------------------------------------------------------------
    call FileOpen( unit = unit_nml, & ! (out)
      & file = nmlfile, mode = 'r', & ! (in)
      & err = err )                   ! (out)
    if ( present_and_true(err) ) then
      stat = DC_ENOFILEREAD
      cause_c = nmlfile
      goto 999
    end if


    !-----------------------------------------------------------------
    !  NAMELIST 変数群の取得
    !  Get NAMELIST group
    !-----------------------------------------------------------------
!!$    read( unit = unit_nml, & ! (in)
!!$      & nml = phy_lscond_nml, iostat = iostat_nml ) ! (out)
!!$    if ( iostat_nml == 0 ) then
!!$      call MessageNotify( 'M', subname, &
!!$        & 'NAMELIST group "%c" is loaded from "%c".', &
!!$        & c1 = 'phy_lscond_nml', c2 = trim(nmlfile) )
!!$      write(STDOUT, nml = phy_lscond_nml)
!!$    else
!!$      call MessageNotify( 'W', subname, &
!!$        & 'NAMELIST group "%c" is not found in "%c" (iostat=%d).', &
!!$        & c1 = 'phy_lscond_nml', c2 = trim(nmlfile), &
!!$        & i = (/iostat_nml/) )
!!$    end if

    close( unit_nml )

    !-----------------------------------------------------------------
    !  NAMELIST 変数群を文字型引数へ代入
    !  Substitute NAMELIST group to character arguments
    !-----------------------------------------------------------------
!!$    param_c_ = param_c

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
999 continue
    call StoreError( stat, subname, err, cause_c )
    call EndSub( subname )
  end subroutine PhyLSCondNmlRead

!!$  subroutine PhyLSCondSample( phy_lsc, err )
!!$    !--
!!$    ! PhyLSCondSample の要約を記述してください.
!!$    !++
!!$    ! なお, 与えられた *phy_lsc* が Create によって初期設定
!!$    ! されていない場合, プログラムはエラーを発生させます.
!!$    !--
!!$    ! Describe brief of PhyLSCondSample
!!$    !++
!!$    ! If *phy_lsc* is not initialized by "Create" yet,
!!$    ! error is occurred.
!!$    !
!!$    use dc_trace, only: BeginSub, EndSub
!!$    use dc_string, only: PutLine, Printf
!!$    use dc_types, only: DP, STRING, TOKEN, STDOUT
!!$    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
!!$    implicit none
!!$    type(PHYLSC), intent(inout):: phy_lsc
!!$    logical, intent(out), optional:: err
!!$                              ! 例外処理用フラグ.
!!$                              ! デフォルトでは, この手続き内でエラーが
!!$                              ! 生じた場合, プログラムは強制終了します.
!!$                              ! 引数 *err* が与えられる場合,
!!$                              ! プログラムは強制終了せず, 代わりに
!!$                              ! *err* に .true. が代入されます.
!!$                              !
!!$                              ! Exception handling flag. 
!!$                              ! By default, when error occur in 
!!$                              ! this procedure, the program aborts. 
!!$                              ! If this *err* argument is given, 
!!$                              ! .true. is substituted to *err* and 
!!$                              ! the program does not abort. 
!!$
!!$!!$    integer:: param_i
!!$!!$    real(DP):: param_r
!!$!!$    character(STRING):: param_c
!!$
!!$    !-----------------------------------
!!$    !  作業変数
!!$    !  Work variables
!!$    integer:: stat
!!$    character(STRING):: cause_c
!!$    character(*), parameter:: subname = 'PhyLSCondSample'
!!$  continue
!!$    call BeginSub( subname )
!!$    stat = DC_NOERR
!!$    cause_c = ''
!!$
!!$    !-----------------------------------------------------------------
!!$    !  初期設定のチェック
!!$    !  Check initialization
!!$    !-----------------------------------------------------------------
!!$    if ( .not. phy_lsc % initialized ) then
!!$      stat = DC_ENOTINIT
!!$      cause_c = 'PHYLSC'
!!$      goto 999
!!$    end if
!!$
!!$    !-----------------------------------------------------------------
!!$    !  *phy_lsc* に格納されている設定値の取り出し
!!$    !  Fetch setting values stored in *phy_lsc*
!!$    !-----------------------------------------------------------------
!!$!!$    param_i = phy_lsc % param_i
!!$!!$    param_r = phy_lsc % param_r
!!$!!$    param_c = phy_lsc % param_c
!!$
!!$
!!$    !-----------------------------------------------------------------
!!$    !  終了処理, 例外処理
!!$    !  Termination and Exception handling
!!$    !-----------------------------------------------------------------
!!$999 continue
!!$    call StoreError( stat, subname, err, cause_c )
!!$    call EndSub( subname )
!!$  end subroutine PhyLSCondSample

end module phy_lscond
