!= CO2 相変化 (火星計算用)
!
!= Phase change of CO2 (for the use in Mars calculation)
!
! Authors::   Yoshiyuki O. Takahashi
! Version::   $Id: co2_phase_change.f90,v 1.1 2010-09-18 01:46:54 yot Exp $ 
! Tag Name::  $Name: dcpam5-20110714 $
! Copyright:: Copyright (C) GFD Dennou Club, 2008. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module co2_phase_change
  !
  != CO2 相変化
  !
  != Phase change of CO2
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  !== Procedures List
  ! 
!!$  ! DryConvAdjust :: 乾燥対流調節
!!$  ! ------------  :: ------------
!!$  ! DryConvAdjust :: Dry convective adjustment
  !
  !== NAMELIST
  !
  ! NAMELIST#dry_conv_adjust_nml
  !

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

  ! 格子点設定
  ! 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. 

  ! NAMELIST ファイル入力に関するユーティリティ
  ! Utilities for NAMELIST file input
  !
  use namelist_util, only: MaxNmlArySize
                              ! NAMELIST から読み込む配列の最大サイズ. 
                              ! Maximum size of arrays loaded from NAMELIST

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

  ! 宣言文 ; Declaration statements
  !
  implicit none
  private

  logical, save:: FlagUse
                              ! 使用フラグ
                              ! flag for use of this scheme

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

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

  ! 非公開変数
  ! Private variables
  !

  character(*), parameter:: module_name = 'co2_phase_change'
                              ! モジュールの名称. 
                              ! Module name
  character(*), parameter:: version = &
    & '$Name: dcpam5-20110714 $' // &
    & '$Id: co2_phase_change.f90,v 1.1 2010-09-18 01:46:54 yot Exp $'
                              ! モジュールのバージョン
                              ! Module version


contains

  subroutine CO2PhaseChangeLimitTemp( &
    & xyr_Press, xyz_Press,  &  ! (in)
    & xy_SurfTemp, xyz_Temp  &  ! (inout)
    & )
    !
    ! CO2 相変化
    !
    ! CO2 phase change
    !

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

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

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


    ! 宣言文 ; Declaration statements
    !
    implicit none

    real(DP), intent(in   ):: xyr_Press (0:imax-1, 1:jmax, 0:kmax)
                              ! $ \hat{p} $ . 気圧 (半整数レベル). 
                              ! Air pressure (half level)
    real(DP), intent(in   ):: xyz_Press (0:imax-1, 1:jmax, 1:kmax)
                              ! $ p $ . 気圧 (整数レベル). 
                              ! Air pressure (full level)
    real(DP), intent(inout):: xy_SurfTemp(0:imax-1, 1:jmax)
                              ! $ T_s $ .   惑星表面温度. Surface temperature
    real(DP), intent(inout):: xyz_Temp   (0:imax-1, 1:jmax, 1:kmax)
                              ! $ T $ .     温度. Temperature

    ! 作業変数
    ! Work variables
    !
    real(DP):: xy_SurfTempB  (0:imax-1, 1:jmax)
                              ! 調節前の惑星表面温度. 
                              ! Surface temperature before adjustment
    real(DP):: xyz_TempB     (0:imax-1, 1:jmax, 1:kmax)
                              ! 調節前の温度. 
                              ! Temperature before adjustment
    real(DP):: xy_DSurfTempDt(0:imax-1, 1:jmax)
                              ! 惑星表面温度変化率. 
                              ! Surface temperature tendency
    real(DP):: xyz_DTempDt   (0:imax-1, 1:jmax, 1:kmax)
                              ! 温度変化率. 
                              ! Temperature tendency

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

    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

    logical :: FlagCheckPs


    ! 実行文 ; Executable statement
    !

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

    ! 初期化
    ! Initialization
    !
    if ( .not. co2_phase_change_inited ) call CO2PhaseChangeInit

    if ( .not. FlagUse ) return


    FlagCheckPs = .false.
    do j = 1, jmax
      do i = 0, imax-1
        if ( xyr_Press(i,j,0) > 1.0d4 ) then
          FlagCheckPs = .true.
        end if
      end do
    end do
    if ( FlagCheckPs ) then
      call MessageNotify( 'W', module_name, 'Surface pressure is greater than 10000 Pa.' )
    end if


    ! 調節前 "Temp" の保存
    ! Store "Temp" before adjustment
    !
    xy_SurfTempB = xy_SurfTemp
    xyz_TempB    = xyz_Temp


    do j = 1, jmax
      do i = 0, imax-1
        xy_SurfTempCond(i,j) = &
          & 149.2d0 + 6.48d0 * log( 0.135d0 * xyr_Press(i,j,0) * 1.0d-2 )
      end do
    end do
    do k = 1, kmax
      do j = 1, jmax
        do i = 0, imax-1
          xyz_TempCond(i,j,k) = &
            & 149.2d0 + 6.48d0 * log( 0.135d0 * xyz_Press(i,j,k) * 1.0d-2 )
        end do
      end do
    end do

    do j = 1, jmax
      do i = 0, imax-1
        if ( xy_SurfTemp(i,j) < xy_SurfTempCond(i,j) ) then
          xy_SurfTemp(i,j) = xy_SurfTempCond(i,j)
        end if
      end do
    end do
    do k = 1, kmax
      do j = 1, jmax
        do i = 0, imax-1
          if ( xyz_Temp(i,j,k) < xyz_TempCond(i,j,k) ) then
            xyz_Temp(i,j,k) = xyz_TempCond(i,j,k)
          end if
        end do
      end do
    end do


    ! 温度変化率
    ! Calculate temperature tendency
    !
    xy_DSurfTempDt = ( xy_SurfTemp - xy_SurfTempB ) / ( 2.0_DP * DelTime )
    xyz_DTempDt    = ( xyz_Temp    - xyz_TempB    ) / ( 2.0_DP * DelTime )


    ! ヒストリデータ出力
    ! History data output
    !
    call HistoryAutoPut( TimeN, 'DSurfTempDtCO2PhaseChange', xy_DSurfTempDt )
    call HistoryAutoPut( TimeN, 'DTempDtCO2PhaseChange'    , xyz_DTempDt    )


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

  end subroutine CO2PhaseChangeLimitTemp

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

  subroutine CO2PhaseChangeInit
    !
    ! co2_phase_change モジュールの初期化を行います. 
    ! NAMELIST#co2_phase_change_nml の読み込みはこの手続きで行われます. 
    !
    ! "co2_phase_change" module is initialized. 
    ! "NAMELIST#co2_phase_change_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 /co2_phase_change_nml/ &
      & FlagUse

          ! デフォルト値については初期化手続 "co2_phase_change#CO2PhaseChangeInit" 
          ! のソースコードを参照のこと. 
          !
          ! Refer to source codes in the initialization procedure
          ! "co2_phase_change#CO2PhaseChangeInit" for the default values. 
          !

    ! 実行文 ; Executable statement
    !

    if ( co2_phase_change_inited ) return

    ! デフォルト値の設定
    ! Default values settings
    !
    FlagUse = .false.

    ! 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 = co2_phase_change_nml, &  ! (out)
        & iostat = iostat_nml )         ! (out)
      close( unit_nml )

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


    ! ヒストリデータ出力のためのへの変数登録
    ! Register of variables for history data output
    !
    call HistoryAutoAddVariable( 'DSurfTempDtCO2PhaseChange', &
      & (/ 'lon ', 'lat ', 'time' /),                         &
      & 'heating by CO2 phase change', 'K s-1' )
    call HistoryAutoAddVariable( 'DTempDtCO2PhaseChange',     &
      & (/ 'lon ', 'lat ', 'sig ', 'time' /),                 &
      & 'heating by CO2 phase change', 'K s-1' )

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

    co2_phase_change_inited = .true.

  end subroutine CO2PhaseChangeInit

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

end module co2_phase_change
