!= 乾燥対流調節
!
!= Dry convective adjustment
!
! Authors::   Yukiko YAMADA, Yasuhiro MORIKAWA
! Version::   $Id: phy_dryconv_adjust.f90,v 1.4 2008-06-14 11:44:16 morikawa Exp $
! Tag Name::  $Name: dcpam4-20080624-1 $
! Copyright:: Copyright (C) GFD Dennou Club, 2007. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]   
!

module phy_dryconv_adjust
  !
  != 乾燥対流調節
  !
  != Dry convective adjustment
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  ! 乾燥対流調節を行います. 
  !
  ! Dry convective adjustment is performed. 
  !
  !== Procedures List
  !
  ! Create           :: PHYDRYCONV 型変数の初期設定
  ! Close            :: PHYDRYCONV 型変数の終了処理
  ! PutLine          :: PHYDRYCONV 型変数に格納されている情報の印字
  ! initialized      :: PHYDRYCONV 型変数が初期設定されているか否か
  ! DryConvectAdjust :: 乾燥対流調節を行う
  ! ------------     :: ------------
  ! Create           :: Constructor of "PHYDRYCONV"
  ! Close            :: Deconstructor of "PHYDRYCONV"
  ! PutLine          :: Print information of "PHYDRYCONV"
  ! initialized      :: Check initialization of "PHYDRYCONV"
  ! DryConvectAdjust :: Dry convective adjustment is performed. 
  !
  !== Usage
  !
  ! 始めに, PHYDRYCONV 型の変数を定義し, Create で初期設定を行います.
  ! DryConvectAdjust を用いて乾燥対流調節を行ってください. 
  ! PHYDRYCONV 型の変数の終了処理には Close を用いてください.
  !
  ! First, initialize "PHYDRYCONV" by "Create".
  ! Dry convective adjustment is performed by "DryConvectAdjust".
  ! In order to terminate "PHYDRYCONV", use "Close".
  !

  use dc_types, only: DP, TOKEN
  implicit none
  private
  public:: PHYDRYCONV, Create, Close, PutLine, initialized, DryConvectAdjust

  type PHYDRYCONV
    !
    ! まず, Create で "PHYDRYCONV" 型の変数を初期設定して下さい.
    ! 初期設定された "PHYDRYCONV" 型の変数を再度利用する際には,
    ! Close によって終了処理を行ってください.
    !
    ! Initialize "PHYDRYCONV" variable by "Create" before usage.
    ! If you reuse "PHYDRYCONV" 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):: RAir      ! $ R $ .      大気気体定数.   Gas constant of air
    real(DP):: Cp        ! $ C_p $ .    大気定圧比熱.   Specific heat of air at constant pressure
    real(DP):: DelTime    ! $ \Delta t $ . タイムステップ. Time step

  end type PHYDRYCONV

  character(*), parameter:: version = &
    & '$Name: dcpam4-20080624-1 $' // &
    & '$Id: phy_dryconv_adjust.f90,v 1.4 2008-06-14 11:44:16 morikawa Exp $'

  interface Create
    module procedure PhyDryConvAdjCreate
  end interface

  interface Close
    module procedure PhyDryConvAdjClose
  end interface

  interface PutLine
    module procedure PhyDryConvAdjPutLine
  end interface

  interface initialized
    module procedure PhyDryConvAdjInitialized
  end interface

  interface NmlRead
    module procedure PhyDryConvAdjNmlRead
  end interface

  interface DryConvectAdjust
    module procedure PhyDryConvAdjDryConvectAdjust
  end interface

!!$  interface Sample
!!$    module procedure PhyDryConvAdjSample
!!$  end interface

contains

  subroutine PhyDryConvAdjCreate( phy_dryconv, &
    & imax, jmax, kmax, &
    & RAir, Cp, &
    & DelTime, &
    & nmlfile, err )
    !
    ! PHYDRYCONV 型の変数の初期設定を行います.
    ! 他のサブルーチンを使用する前に必ずこのサブルーチンによって
    ! PHYDRYCONV 型の変数を初期設定してください.
    !
    ! なお, 与えられた *phy_dryconv* が既に初期設定されている場合,
    ! プログラムはエラーを発生させます.
    !
    ! NAMELIST を利用する場合には引数 *nmlfile* に NAMELIST ファイル名
    ! を与えてください. NAMELIST 変数群の詳細に関しては 
    ! NAMELIST#phy_dryconv_adjust_nml を参照してください. 
    !
    ! Constructor of "PHYDRYCONV".
    ! Initialize *phy_dryconv* by this subroutine, 
    ! before other procedures are used, 
    !
    ! Note that if *phy_dryconv* is already initialized 
    ! by this procedure, error is occurred.
    !
    ! In order to use NAMELIST, specify a NAMELIST filename to 
    ! argument *nmlfile*. See "NAMELIST#phy_dryconv_adjust_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
    implicit none
    type(PHYDRYCONV), intent(inout):: phy_dryconv
    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):: RAir      ! $ R $ .      大気気体定数.   Gas constant of air
    real(DP), intent(in):: Cp        ! $ C_p $ .    大気定圧比熱.   Specific heat of air at constant pressure
    real(DP), intent(in):: DelTime    ! $ \Delta t $ . タイムステップ. Time step
    character(*), intent(in), optional:: nmlfile
                              ! NAMELIST ファイルの名称. 
                              ! この引数に空文字以外を与えた場合, 
                              ! 指定されたファイルから 
                              ! NAMELIST 変数群を読み込みます. 
                              ! ファイルを読み込めない場合にはエラーを
                              ! 生じます.
                              !
                              ! NAMELIST 変数群の詳細に関しては 
                              ! NAMELIST#phy_dryconv_adjust_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_dryconv_adjust_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 = 'PhyDryConvAdjCreate'
  continue
    call BeginSub( subname, version )
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------
    if ( phy_dryconv % initialized ) then
      stat = DC_EALREADYINIT
      cause_c = 'PHYDRYCONV'
      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

    !-----------------------------------------------------------------
    !  "PHYDRYCONV" の設定
    !  Configure the settings for "PHYDRYCONV"
    !-----------------------------------------------------------------
    phy_dryconv % imax    = imax   
    phy_dryconv % jmax    = jmax   
    phy_dryconv % kmax    = kmax   
    phy_dryconv % Cp      = Cp     
    phy_dryconv % RAir    = RAir   
    phy_dryconv % DelTime = DelTime

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

    !-------------------------
    !  オプショナル引数からの値
    !  Values from optional arguments
!!$    phy_dryconv % param_i = param_i
!!$    if ( present(param_r) )  phy_dryconv % param_r = param_r
!!$    if ( present(param_c) )  phy_dryconv % 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_dryconv % param_i, &   ! (inout)
!!$        & param_r = phy_dryconv % param_r, &   ! (inout)
!!$        & param_c_ = phy_dryconv % 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

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


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

  subroutine PhyDryConvAdjClose( phy_dryconv, err )
    !
    ! PHYDRYCONV 型の変数の終了処理を行います.
    ! なお, 与えられた *phy_dryconv* が Create によって初期設定
    ! されていない場合, プログラムはエラーを発生させます.
    !
    ! Deconstructor of "PHYDRYCONV".
    ! Note that if *phy_dryconv* 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(PHYDRYCONV), intent(inout):: phy_dryconv
    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 = 'PhyDryConvAdjClose'
  continue
    call BeginSub( subname )
    stat = DC_NOERR
    cause_c = ''

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

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


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

  subroutine PhyDryConvAdjPutLine( phy_dryconv, unit, indent, err )
    !
    ! 引数 *phy_dryconv* に設定されている情報を印字します.
    ! デフォルトではメッセージは標準出力に出力されます. 
    ! *unit* に装置番号を指定することで, 出力先を変更することが可能です.
    !
    ! Print information of *phy_dryconv*.
    ! 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
    implicit none
    type(PHYDRYCONV), intent(in):: phy_dryconv
    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 = 'PhyDryConvAdjPutLine'
  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


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

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

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

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

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

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

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

  subroutine PhyDryConvAdjNmlRead( 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_dryconv_adjust_nml/ &
!!$      & param_i, param_r, param_c
                              ! phy_dryconv_adjust モジュール用
                              ! NAMELIST 変数群名.
                              !
                              ! phy_dryconv_adjust#Create を使用する際に, 
                              ! オプショナル引数 *nmlfile* へ NAMELIST 
                              ! ファイル名を指定することで, そのファイルから
                              ! この NAMELIST 変数群を読み込みます.
                              !
                              ! NAMELIST group name for 
                              ! "phy_dryconv_adjust" module.
                              ! 
                              ! If a NAMELIST filename is specified to 
                              ! an optional argument *nmlfile* 
                              ! when "phy_dryconv_adjust#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 = 'PhyDryConvAdjNmlRead'
  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_dryconv_adjust_nml, iostat = iostat_nml ) ! (out)
!!$    if ( iostat_nml == 0 ) then
!!$      call MessageNotify( 'M', subname, &
!!$        & 'NAMELIST group "%c" is loaded from "%c".', &
!!$        & c1 = 'phy_dryconv_adjust_nml', c2 = trim(nmlfile) )
!!$      write(STDOUT, nml = phy_dryconv_adjust_nml)
!!$    else
!!$      call MessageNotify( 'W', subname, &
!!$        & 'NAMELIST group "%c" is not found in "%c" (iostat=%d).', &
!!$        & c1 = 'phy_dryconv_adjust_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 PhyDryConvAdjNmlRead

  subroutine PhyDryConvAdjDryConvectAdjust( phy_dryconv, &
    & xyz_Press, xyr_Press, &
    & xyz_Temp, &
    & xyz_DTempDt, &
    & err )
    !
    ! 乾燥対流調節を行います. 
    !
    ! なお, 与えられた *phy_dryconv* が Create によって初期設定
    ! されていない場合, プログラムはエラーを発生させます.
    !
    ! Dry convective adjustment is performed. 
    !
    ! If *phy_dryconv* 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(PHYDRYCONV), intent(inout):: phy_dryconv
    real(DP), intent(in):: xyz_Press (0:phy_dryconv%imax-1, 0:phy_dryconv%jmax-1, 0:phy_dryconv%kmax-1)
                              ! $ p_s $ . 地表面気圧 (整数レベル). 
                              ! Surface pressure (full level)
    real(DP), intent(in):: xyr_Press (0:phy_dryconv%imax-1, 0:phy_dryconv%jmax-1, 0:phy_dryconv%kmax)
                              ! $ p_s $ . 地表面気圧 (半整数レベル). 
                              ! Surface pressure (half level)
    real(DP), intent(inout):: xyz_Temp (0:phy_dryconv%imax-1, 0:phy_dryconv%jmax-1, 0:phy_dryconv%kmax-1)
                              ! $ T $ .     温度. Temperature
    real(DP), intent(out):: xyz_DTempDt (0:phy_dryconv%imax-1, 0:phy_dryconv%jmax-1, 0:phy_dryconv%kmax-1)
                              ! 乾燥対流調節による温度変化率. 
                              ! Temperature tendency by dry convective adjustment

    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):: RAir      ! $ R $ .      大気気体定数.   Gas constant of air
    real(DP):: Cp        ! $ C_p $ .    大気定圧比熱.   Specific heat of air at constant pressure
    real(DP):: DelTime    ! $ \Delta t $ . タイムステップ. Time step

    real(DP):: xyz_TempB (0:phy_dryconv%imax-1, 0:phy_dryconv%jmax-1, 0:phy_dryconv%kmax-1)
                              ! 調節前の温度. 
                              ! Temperature before adjust. 
    logical:: xy_Adjust (0:phy_dryconv%imax-1, 0:phy_dryconv%jmax-1)
                              ! 今回調節されたか否か. 
                              ! Whether it was adjusted this time or not?
    logical:: xy_AdjustB (0:phy_dryconv%imax-1, 0:phy_dryconv%jmax-1)
                              ! 前回調節されたか否か. 
                              ! Whether it was adjusted last time or not?
    real(DP):: xyz_DPressDz (0:phy_dryconv%imax-1, 0:phy_dryconv%jmax-1, 0:phy_dryconv%kmax-1)
                              ! $ \DD{p}{z} $
                              ! 
    real(DP):: xyz_DDPressDDPress (0:phy_dryconv%imax-1, 0:phy_dryconv%jmax-1, 0:phy_dryconv%kmax-1)
                              ! $ \DD{p_{k}}{p_{k-1}} $
                              ! 
    real(DP):: xyz_DPFact (0:phy_dryconv%imax-1, 0:phy_dryconv%jmax-1, 0:phy_dryconv%kmax-1)
                              ! $ (R / C_p)
                              ! \frac{p_{k-1} - p_{k}}{2 p_{k-1/2}} $ . 
                              !
                              ! ファクター. 
                              ! Factor
    real(DP):: TempSat
                              ! 飽和温度. 
                              ! Saturated temperature
    real(DP):: DelTemp
                              ! 調節による温度の変化量. 
                              ! Temperature variation by adjustment
    logical:: Adjust
                              ! 今回全領域において一度でも調節されたか否か?. 
                              ! Whether it was adjusted even once in global 
                              ! this time or not?


    integer, parameter :: IterationMax = 10
                              ! イテレーション回数. 
                              ! Number of iteration
    
    real(DP):: TempSatMax(IterationMax)
                              ! 不安定の許容誤差. 
                              ! Admissible error of unstability

    data TempSatMax  / 0.01  , 0.02  , 0.02  , 0.05  , 0.05  , &
         &             0.10  , 0.10  , 0.20  , 0.20  , 0.40  /


    integer:: i, j, k         ! DO ループ用作業変数
                              ! Work variables for DO loop
    integer:: Iteration

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

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

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

    !-----------------------------------------------------------------
    !  調節前 "QVap" の保存
    !  Store "QVap" before adjustment
    !-----------------------------------------------------------------
    xyz_TempB  = xyz_Temp
    
    !-----------------------------------------------------------------
    !  変数初期化
    !  Initialize a variable
    !-----------------------------------------------------------------
    xyz_DTempDt = 0.0_DP
    
    !-----------------------------------------------------------------
    !  ファクターの計算
    !  Calculate factor
    !-----------------------------------------------------------------
    do k = 0, kmax-1
      xyz_DPressDz(:,:,k) = xyr_Press(:,:,k) - xyr_Press(:,:,k+1)
    end do
    
    do k = 1, kmax-1

      xyz_DDPressDDPress(:,:,k) = xyz_DPressDz(:,:,k) / xyz_DPressDz(:,:,k-1)
      
      xyz_DPFact(:,:,k) = &
        &   RAir / Cp &
        &   * ( xyz_Press(:,:,k-1) - xyz_Press(:,:,k) ) &
        &   / ( xyz_DPressDz(:,:,k-1) + xyz_DPressDz(:,:,k) ) &
        &   / xyr_Press(:,:,k)

    end do
    
    !-----------------------------------------------------------------
    !  調節
    !  Adjustment
    !-----------------------------------------------------------------
    xy_AdjustB = .true.
    
    !-------------------------
    !  イテレーション
    !  iteration
    do Iteration = 1, IterationMax
      xy_Adjust = .false.
      
      do k = 1, kmax-1
        do i = 0, imax-1
          do j = 0, jmax-1
            if ( xy_AdjustB(i,j) ) then
              
              TempSat = xyz_Temp(i,j,k-1) - xyz_Temp(i,j,k) &
                & - xyz_DPFact(i,j,k) &
                &  * ( xyz_DPressDz(i,j,k-1) * xyz_Temp(i,j,k-1) &
                &     + xyz_DPressDz(i,j,k) * xyz_Temp(i,j,k) )
              
              !-------------------------
              !  不安定であるならば
              !  If it is unstable
              if ( TempSat > TempSatMax(Iteration) ) then
                
                DelTemp = TempSat / ( 1.0_DP + xyz_DDPressDDPress(i,j,k) )
                xyz_Temp(i,j,k) = xyz_Temp(i,j,k) + DelTemp
                xyz_Temp(i,j,k-1) = &
                  &   xyz_Temp(i,j,k-1) &
                  & - DelTemp * xyz_DDPressDDPress(i,j,k)
                
                !-------------------------
                !  調節したか否か?
                !  Whether it was adjusted or not?
                xy_Adjust(i,j) = .true.
              end if
              
            end if
          end do
        end do
      end do
      
      Adjust = .false.
      do i = 0, imax-1
        do j = 0, jmax-1
          xy_AdjustB(i,j) = xy_Adjust(i,j)
          Adjust          = Adjust .or. xy_Adjust(i,j)
        end do
      end do
      
      if ( .not. Adjust ) exit
      
    end do
    
    !-----------------------------------------------------------------
    !  温度変化率の算出
    !  Calculate temperature tendency
    !-----------------------------------------------------------------
    xyz_DTempDt = &
      &   xyz_DTempDt &
      & + ( xyz_Temp - xyz_TempB ) / ( 2.0_DP * DelTime )
    
    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
999 continue
    call StoreError( stat, subname, err, cause_c )
    call EndSub( subname )
  end subroutine PhyDryConvAdjDryConvectAdjust

!!$  subroutine PhyDryConvAdjSample( phy_dryconv, err )
!!$    !--
!!$    ! PhyDryConvAdjSample の要約を記述してください.
!!$    !++
!!$    ! なお, 与えられた *phy_dryconv* が Create によって初期設定
!!$    ! されていない場合, プログラムはエラーを発生させます.
!!$    !--
!!$    ! Describe brief of PhyDryConvAdjSample
!!$    !++
!!$    ! If *phy_dryconv* 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(PHYDRYCONV), intent(inout):: phy_dryconv
!!$    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 = 'PhyDryConvAdjSample'
!!$  continue
!!$    call BeginSub( subname )
!!$    stat = DC_NOERR
!!$    cause_c = ''
!!$
!!$    !-----------------------------------------------------------------
!!$    !  初期設定のチェック
!!$    !  Check initialization
!!$    !-----------------------------------------------------------------
!!$    if ( .not. phy_dryconv % initialized ) then
!!$      stat = DC_ENOTINIT
!!$      cause_c = 'PHYDRYCONV'
!!$      goto 999
!!$    end if
!!$
!!$    !-----------------------------------------------------------------
!!$    !  *phy_dryconv* に格納されている設定値の取り出し
!!$    !  Fetch setting values stored in *phy_dryconv*
!!$    !-----------------------------------------------------------------
!!$!!$    param_i = phy_dryconv % param_i
!!$!!$    param_r = phy_dryconv % param_r
!!$!!$    param_c = phy_dryconv % param_c
!!$
!!$
!!$    !-----------------------------------------------------------------
!!$    !  終了処理, 例外処理
!!$    !  Termination and Exception handling
!!$    !-----------------------------------------------------------------
!!$999 continue
!!$    call StoreError( stat, subname, err, cause_c )
!!$    call EndSub( subname )
!!$  end subroutine PhyDryConvAdjSample

end module phy_dryconv_adjust
