!= Held and Suarez (1994) による強制と散逸
!
!= Forcing and dissipation suggested by Held and Suarez (1994)
!
! Authors::   Yasuhiro MORIKAWA
! Version::   $Id: phy_hs94.f90,v 1.11 2008-06-03 11:17:06 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_hs94
  != Held and Suarez (1994) による強制と散逸
  !
  != Forcing and dissipation suggested by Held and Suarez (1994)
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  ! Held and Suarez (1994) で提案される乾燥大気 GCM ベンチマーク用の
  ! 強制と散逸を計算します. 
  ! 与える強制と散逸として, 温度場の帯状対称場への簡単なニュートン冷却と, 
  ! 境界層摩擦を表現する下層風のレイリー摩擦を用います. 
  ! 詳細を以下に記します. 
  !
  ! Forcing and dissipation for dry air GCM benchmark
  ! suggested by Held and Suarez (1994) are caluclate.
  ! We use simple Newtonian relaxation of the temperature field to a
  ! zonally symmetric state and Rayleigh damping of low-level winds to
  ! represent boundary-layer friction.
  ! Their specifications are detailed as follows.
  !
  ! \[
  !    \left( \DP{\Dvect{v}}{t} \right)_{\mathrm{HS94}} = 
  !        - k_v (\sigma) \Dvect{v}, \] \[
  !    \left( \DP{T}{t} \right)_{\mathrm{HS94}} = 
  !        - k_T (\phi, \sigma) [T - T_{eq} (\phi,p)], \] \[
  !    T_{eq} = \mathrm{max}
  !     \left\{
  !        200 \mathrm{K}, 
  !        \left[
  !          315 \mathrm{K} - (\Delta T)_y \sin^2\phi 
  !                         - (\Delta \theta)_z 
  !                           \log \left(\frac{p}{p_0}\right) \cos^2\phi
  !        \right] \left(\frac{p}{p_0}\right)^\kappa
  !     \right\}, \] \[
  !    k_T = k_a + (k_s - k_a) 
  !          \mathrm{max} 
  !          \left(0, \frac{\sigma - \sigma_b}{1 - \sigma_b}\right) \cos^4\phi,
  !     \] \[
  !    k_v = k_f
  !          \mathrm{max} 
  !          \left(0, \frac{\sigma - \sigma_b}{1 - \sigma_b}\right),
  !     \] \[
  !    \sigma_b = 0.7, \qquad 
  !    k_f = 1 \mathrm{day}^{-1}, \qquad
  !    k_a = \Dinv{40} \mathrm{day}^{-1}, \qquad
  !    k_s = \Dinv{4} \mathrm{day}^{-1}, \] \[
  !    (\Delta T)_y = 60 \mathrm{K}, \qquad
  !    (\Delta \theta)_z = 10 \mathrm{K}, \qquad
  !    p_0 = 1000 \mathrm{hPa}, \qquad
  !    \kappa = \frac{R}{c_p}.
  ! \]
  !
  ! Forcing では, 与えられた速度や温度 ( $ t+\Delta t$ を想定) 
  ! に対して以下のように強制と散逸を適用します.
  !
  ! By Forcing, forcing and dissipation are applied to 
  ! given wind and temperature ($ t+\Delta t$ is expected) as follows.
  !
  ! \[
  !    \hat{\Dvect{v}}^{t+\Delta t} = 
  !      \Dvect{v}^{t+\Delta t} 
  !      + 2 \Delta t \left( \DP{\Dvect{v}}{t} \right)_{\mathrm{HS94}} \] \[
  !    \hat{T}^{t+\Delta t} = 
  !      T^{t+\Delta t} 
  !      + 2 \Delta t \left( \DP{T}{t} \right)_{\mathrm{HS94}}
  ! \]
  !
  !== Procedures List
  !
  ! PhyHsCreate        :: PHYHS94 型変数の初期設定
  ! PhyHsClose         :: PHYHS94 型変数の終了処理
  ! PhyHsPutLine       :: PHYHS94 型変数に格納されている情報の印字
  ! PhyHsInitialized   :: PHYHS94 型変数が初期設定されているか否か
  ! PhyHsForcing       :: 強制と散逸の計算
  ! ------------  :: ------------
  ! PhyHsCreate        :: Constructor of "PHYHS94"
  ! PhyHsClose         :: Deconstructor of "PHYHS94"
  ! PhyHsPutLine       :: Print information of "PHYHS94"
  ! PhyHsInitialized   :: Check initialization of "PHYHS94"
  ! PhyHsForcing       :: Calculate forcing and dissipation
  !
  !== Usage
  !
  ! 始めに, PHYHS94 型の変数を定義し, PhyHsCreate で初期設定を行います.
  ! 強制と散逸の計算に PhyHsForcing を用います.
  ! PHYHS94 型の変数の終了処理には PhyHsClose を用いてください.
  !
  ! First, initialize "PHYHS94" by "PhyHsCreate".
  ! Use "PhyHsForcing" in order to calculate forcing and dissipation
  ! In order to terminate "PHYHS94", use "PhyHsClose".
  !
  !== References
  !
  ! * Held, I. M., Suarez, M. J., 1994: 
  !   A proposal for the intercomparison of the dynamical cores of
  !   atmospheric general circuation models.
  !   <i>Bull. Am. Meteor. Soc.</i>, <b>75</b>, 1825--1830.
  !

  use dc_types, only: DP, TOKEN
  use dc_date_types, only: DC_DIFFTIME
  use gt4_history_nmlinfo, only: GTHST_NMLINFO
  implicit none
  private
  public:: PHYHS94, PhyHsCreate, PhyHsForcing
  public:: PhyHsClose, PhyHsPutLine, PhyHsInitialized, PhyHsSetTime

  type PHYHS94
    !
    ! まず, PhyHsCreate で "PHYHS94" 型の変数を初期設定して下さい.
    ! 初期設定された "PHYHS94" 型の変数を再度利用する際には,
    ! PhyHsClose によって終了処理を行ってください.
    !
    ! Initialize "PHYHS94" variable by "PhyHsCreate" before usage. 
    ! If you reuse "PHYHS94" variable again for another application, 
    ! terminate by "PhyHsClose".
    !
    logical:: initialized = .false.     ! 初期設定フラグ. 
                                        ! Initialization flag

    !-----------------------------------------------------------------
    !  格子点数・最大全波数
    !  Grid points and maximum truncated wavenumber
    !-----------------------------------------------------------------
    integer:: imax ! 経度格子点数. 
                   ! Number of grid points in longitude
    integer:: jmax ! 緯度格子点数. 
                   ! Number of grid points in latitude
    integer:: kmax ! 鉛直層数. 
                   ! Number of vertical level

    !-----------------------------------------------------------------
    !  座標変数
    !  Coordinate variables
    !-----------------------------------------------------------------
    real(DP), pointer:: x_Lon (:)
                              ! 経度. Longitude
    real(DP), pointer:: x_Lon_Weight (:)
                              ! 経度積分用座標重み. 
                              ! Weight for integration in longitude
    real(DP), pointer:: y_Lat (:) =>null()
                              ! 緯度. Latitude
    real(DP), pointer:: y_Lat_Weight (:)
                              ! 緯度積分用座標重み. 
                              ! Weight for integration in latitude
    real(DP), pointer:: z_Sigma (:) =>null()
                              ! $ \sigma $ レベル (整数). 
                              ! Full $ \sigma $ level

    !-----------------------------------------------------------------
    !  時刻管理
    !  Time control
    !-----------------------------------------------------------------
    type(DC_DIFFTIME):: current_time
                              ! 現在時刻. Current time.
    type(DC_DIFFTIME):: delta_time
                              ! $ Delta t $ . タイムステップ. Time step

    !-----------------------------------------------------------------
    !  ヒストリファイルへのデータ出力設定
    !  Configure the settings for history data output
    !-----------------------------------------------------------------
    type(GTHST_NMLINFO):: gthstnml
                              ! NAMELIST#phy_hs94_history_nml 
                              ! から入手される個別のデータ出力情報. 
                              ! 
                              ! Individual data output information from 
                              ! "NAMELIST#phy_hs94_history_nml". 

    !-----------------------------------
    !  Held and Suarez (1994) で使用される係数
    !  Coefficient used by Held and Suarez (1994) 
    real(DP):: Kappa      ! $ \kappa = R/C_p $ .
                          ! 気体定数の定圧比熱に対する比. Ratio of gas constant to specific heat
    real(DP):: P0             ! $ p_0 $ .
    real(DP):: DelTempY       ! $ (\Delta T)_y $ .
    real(DP):: DelPotTempZ    ! $ (\Delta \theta)_z $ .
    real(DP), pointer:: z_kv (:) =>null()
                              ! $ k_v $ .
    real(DP), pointer:: yz_kt (:,:) =>null()
                              ! $ k_T $ .
  end type PHYHS94

  character(*), parameter:: version = &
    & '$Name: dcpam4-20080609-1 $' // &
    & '$Id: phy_hs94.f90,v 1.11 2008-06-03 11:17:06 morikawa Exp $'

  !-----------------------------------------------------------------
  !  公開手続
  !  Public procedures
  !-----------------------------------------------------------------

  interface PhyHsCreate
    module procedure PhyHsCreate
  end interface

  interface PhyHsForcing
    module procedure PhyHsForcing
  end interface

  interface PhyHsClose
    module procedure PhyHsClose
  end interface

  interface PhyHsPutLine
    module procedure PhyHsPutLine
  end interface

  interface PhyHsInitialized
    module procedure PhyHsInitialized
  end interface

  interface PhyHsSetTime
    module procedure PhyHsSetTime
  end interface

!!$  interface PhyHsSample
!!$    module procedure PhyHsSample
!!$  end interface

  !-----------------------------------------------------------------
  !  非公開手続
  !  Private procedures
  !-----------------------------------------------------------------

  interface NmlRead
    module procedure PhyHsNmlRead
  end interface

contains

  subroutine PhyHsCreate( phy_hs, &
    & imax, jmax, kmax, &
    & x_Lon, y_Lat, z_Sigma, DelTime, &
    & Cp, RAir, &
    & day_seconds, &
    & x_Lon_Weight, y_Lat_Weight, &
    & current_time_value, current_time_unit, &
    & history_varlist, &
    & history_interval_value, history_interval_unit, &
    & history_precision, history_fileprefix, &
    & nmlfile, err )
    !
    ! PHYHS94 型の変数の初期設定を行います.
    ! 他のサブルーチンを使用する前に必ずこのサブルーチンによって
    ! PHYHS94 型の変数を初期設定してください.
    !
    ! なお, 与えられた *phy_hs* が既に初期設定されている場合,
    ! プログラムはエラーを発生させます.
    !
    ! NAMELIST を利用する場合には引数 *nmlfile* に NAMELIST ファイル名
    ! を与えてください. NAMELIST 変数群の詳細に関しては 
    ! NAMELIST#phy_hs94_nml を参照してください. 
    !
    ! Constructor of "PHYHS94".
    ! Initialize *phy_hs* by this subroutine, 
    ! before other procedures are used, 
    !
    ! Note that if *phy_hs* is already initialized 
    ! by this procedure, error is occurred.
    !
    ! In order to use NAMELIST, specify a NAMELIST filename to 
    ! argument *nmlfile*. See "NAMELIST#phy_hs94_nml"
    ! for details about a NAMELIST group.
    !
    use dc_trace, only: BeginSub, EndSub, DbgMessage
    use dc_string, only: PutLine, Printf, Split, StrInclude, StoA, JoinChar
    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, USR_ERRNO
    use dc_date_types, only: DAY_SECONDS_EARTH
    use dc_date, only: DCDiffTimeCreate
    use dc_hash, only: HASH, DCHashPut, DCHashRewind, DCHashNext, DCHashDelete
    use gt4_history_nmlinfo, only: HstNmlInfoCreate, HstNmlInfoAdd, &
      & HstNmlInfoEndDefine, HstNmlInfoPutLine
    use gt4_history, only: GT_HISTORY, &
      & HistoryAddVariable, HistoryAddAttr
    implicit none
    type(PHYHS94), intent(inout):: phy_hs
    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):: x_Lon (0:imax-1)
                              ! 経度. Longitude
    real(DP), intent(in):: y_Lat (0:jmax-1)
                              ! 緯度. Latitude
    real(DP), intent(in):: z_Sigma (0:kmax-1)
                              ! $ \sigma $ レベル (整数). 
                              ! Full $ \sigma $ level
    real(DP), intent(in):: DelTime    ! $ \Delta t $ . タイムステップ. Time step
    real(DP), intent(in):: Cp         ! $ C_p $ .    大気定圧比熱.   Specific heat of air at constant pressure
    real(DP), intent(in):: RAir       ! $ R $ .      大気気体定数.   Gas constant of air
    real(DP), intent(in), optional:: day_seconds
                              ! 1 日の秒数. 
                              ! この引数を与えない場合, 1 日の秒数は
                              ! 86400.0 となります. 
                              ! 
                              ! Seconds in day. 
                              ! If this argument is not given, seconds in day
                              ! become 86400.0 .
    real(DP), intent(in), optional:: x_Lon_Weight (0:imax-1)
                              ! 経度積分用座標重み. 
                              ! Weight for integration in longitude
    real(DP), intent(in), optional:: y_Lat_Weight (0:jmax-1)
                              ! 緯度積分用座標重み. 
                              ! Weight for integration in latitude
    real, intent(in), optional:: current_time_value
                              ! 現在時刻の数値. Numerical value of current time
    character(*), intent(in), optional:: current_time_unit
                              ! 現在時刻の単位. Unit of current time
    character(*), intent(in), optional:: history_varlist
                              ! ヒストリデータの出力変数リスト. 
                              ! カンマで区切って並べる. 
                              ! (例: "Data1,Data2" ). 
                              ! 
                              ! List of variables output to history data. 
                              ! Delimiter is comma. 
                              ! (exp. "Data1,Data2" ). 
                              ! 
    real, intent(in), optional:: history_interval_value
                              ! ヒストリデータの出力間隔の数値. 
                              ! Numerical value for interval of history data output
    character(*), intent(in), optional:: history_interval_unit
                              ! ヒストリデータの出力間隔の単位. 
                              ! Unit for interval of history data output
    character(*), intent(in), optional:: history_precision
                              ! ヒストリデータの精度. 
                              ! Precision of history data
    character(*), intent(in), optional:: history_fileprefix
                              ! ヒストリデータのファイル名の接頭詞. 
                              ! Prefix of history data filenames
    character(*), intent(in), optional :: nmlfile
                              ! NAMELIST ファイルの名称. 
                              ! この引数に空文字以外を与えた場合, 
                              ! 指定されたファイルから 
                              ! NAMELIST 変数群を読み込みます. 
                              ! ファイルを読み込めない場合にはエラーを
                              ! 生じます.
                              !
                              ! NAMELIST 変数群の詳細に関しては 
                              ! NAMELIST#phy_hs94_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_hs94_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. 

    !-----------------------------------
    !  ヒストリファイルへのデータ出力設定
    !  Configure the settings for history data output
    character(STRING):: name = ''
                              ! 変数名. Variable identifier
    character(STRING):: longname = ''
                              ! 変数の記述的名称. Descriptive name of variables
    character(STRING), allocatable:: dims(:)
                              ! 座標軸の名称. Name of axes
    character(STRING):: units = ''
                              ! 単位. Units
    type(GT_HISTORY), pointer:: gthist =>null()
                              ! gt4_history モジュール用構造体. 
                              ! Derived type for "gt4_history" module
    character(TOKEN):: precision
                              ! ヒストリデータの精度. 
                              ! Precision of history data
    logical:: average
                              ! 出力データの平均化フラグ. 
                              ! Flag for average of output data
    type(HASH):: registered_varnames
                              ! このモジュールから出力される変数名のリスト.
                              ! 
                              ! List of names of variables output 
                              ! from this module. 
    logical:: end

    !-----------------------------------
    !  作業変数
    !  Work variables
    real(DP):: day_seconds_work
                              ! 1 日の秒数. 
                              ! Seconds in day. 
    real(DP):: SigmaB         ! $ \sigma_b $ .
    real(DP):: kf             ! $ k_f $ .
    real(DP):: ka             ! $ k_a $ .
    real(DP):: ks             ! $ k_s $ .

    integer:: j, k            ! DO ループ用作業変数
                              ! Work variables for DO loop
    integer:: stat
    character(STRING):: cause_c
    real(DP), parameter:: PI = 3.1415926535897930_DP
                                ! $ \pi $ . 円周率. Circular constant
    character(*), parameter:: subname = 'PhyHsCreate'
  continue
    call BeginSub( subname,  version = version, &
      & fmt = 'Cp=<%f> RAir=<%f>', &
      & d=(/Cp, RAir/) )
    stat = DC_NOERR
    cause_c = ''

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

    !-----------------------------------------------------------------
    !  設定値の正当性のチェック
    !  Validate setting values
    !-----------------------------------------------------------------
    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
    if ( present(day_seconds) ) then
      if (day_seconds < 0.0_DP) then
        stat = DC_ENEGATIVE
        cause_c = 'day_seconds'
        goto 999
      end if
    end if

    !-----------------------------------------------------------------
    !  座標軸の設定
    !  Configure axes
    !-----------------------------------------------------------------
    phy_hs % imax  = imax 
    phy_hs % jmax  = jmax 
    phy_hs % kmax  = kmax 

    allocate( phy_hs % x_Lon (0:imax-1) )
    phy_hs % x_Lon = x_Lon

    allocate( phy_hs % y_Lat (0:jmax-1) )
    phy_hs % y_Lat = y_Lat

    allocate( phy_hs % z_Sigma (0:kmax-1) )
    phy_hs % z_Sigma = z_Sigma

    allocate( phy_hs % x_Lon_Weight (0:imax-1) )
    if ( present(x_Lon_Weight) ) then
      phy_hs % x_Lon_Weight = x_Lon_Weight
    else
      phy_hs % x_Lon_Weight = 2.0_DP * PI / imax
    end if

    allocate( phy_hs % y_Lat_Weight (0:jmax-1) )
    if ( present(y_Lat_Weight) ) then
      phy_hs % y_Lat_Weight = y_Lat_Weight
    else
      phy_hs % y_Lat_Weight = 2.0_DP / jmax
    end if

    !-----------------------------------------------------------------
    !  時刻管理
    !  Time control
    !-----------------------------------------------------------------
    if ( present(current_time_value) .and. present(current_time_unit) ) then
      call DCDiffTimeCreate( &
        & diff = phy_hs % current_time, &      ! (out)
        & value = real(current_time_value, DP), & ! (in)
        & unit = current_time_unit )              ! (in)
    else
      call DCDiffTimeCreate( &
        & diff = phy_hs % current_time, & ! (out)
        & value = 0.0_DP, &    ! (in)
        & unit = 'sec' )       ! (in)
    end if

    call DCDiffTimeCreate( &
      & diff = phy_hs % delta_time, & ! (out)
      & value = DelTime, &             ! (in)
      & unit = 'sec' )                 ! (in)


    !-----------------------------------------------------------------
    !  ヒストリファイルへのデータ出力設定
    !  Configure the settings for history data output
    !-----------------------------------------------------------------

    !-------------------------
    !  デフォルト値
    !  Default values
    call HstNmlInfoCreate( gthstnml = phy_hs % gthstnml ) ! (inout)

    !-------------------------
    !  オプショナル引数からの値
    !  Values from optional arguments
    call HstNmlInfoAdd( &
      & gthstnml = phy_hs % gthstnml, &   ! (inout)
      & name = '', &                               ! (in)
      & interval_value = history_interval_value, & ! (in)
      & interval_unit = history_interval_unit, &   ! (in)
      & precision = history_precision, &           ! (in)
      & average = .false., &                       ! (in)
      & fileprefix = history_fileprefix )          ! (in)

    if ( present(history_varlist) ) then
      call HstNmlInfoAdd( &
        & gthstnml = phy_hs % gthstnml, & ! (inout)
        & name = history_varlist )                 ! (in)
    end if

    !-----------------------------------------------------------------
    !  NAMELIST からの値の読み込み
    !  Load 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)
!!$        & CoefAlpha   = phy_hs % CoefAlpha, & ! (inout)
!!$        & key00_      = phy_hs % key00, &     ! (inout)
        & gthstnml    = phy_hs % gthstnml, &  ! (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

    call HstNmlInfoEndDefine( &
      & gthstnml = phy_hs % gthstnml, & ! (inout)
      & err = err )                              ! (out)
    if ( present_and_true( err ) ) then
      stat = USR_ERRNO
      goto 999
    end if

    !-----------------------------------------------------------------
    !  係数の設定
    !  Configure coefficients
    !-----------------------------------------------------------------
    phy_hs % Kappa = RAir / Cp

    if ( present(day_seconds) ) then
      day_seconds_work = day_seconds
    else
      day_seconds_work = DAY_SECONDS_EARTH
    end if

    phy_hs % P0          = 1000.0e2_DP
    phy_hs % DelTempY    = 60.0_DP
    phy_hs % DelPotTempZ = 10.0_DP

    SigmaB = 0.7_DP
    kf     = 1.0_DP / day_seconds_work
    ka     = 1.0_DP / ( 40.0_DP * day_seconds_work )
    ks     = 1.0_DP / (  4.0_DP * day_seconds_work )

    call DbgMessage( &
      & 'day_seconds=<%f>, SigmaB=<%f>, kf=<%f>, ka=<%f>, ks=<%f>', &
      & d=(/day_seconds_work, SigmaB, kf, ka, ks/) )

    allocate( phy_hs % z_kv (0:kmax-1) )

    phy_hs % z_kv = &
      & kf * max( 0.0_DP, &
      &           (    z_Sigma - SigmaB ) &
      &             / ( 1.0_DP - SigmaB ) &
      &         )

    allocate( phy_hs % yz_kt (0:jmax-1,0:kmax-1) )

    do k = 0, kmax - 1
      do j = 0, jmax - 1
        phy_hs % yz_kt(j,k) = &
          & ka + ( ks - ka ) &
          &  * max( 0.0_DP, &
          &         ( z_Sigma(k) - SigmaB ) &
          &           / ( 1.0_DP - SigmaB ) &
          &       ) * cos( y_Lat(j) ) ** 4
      end do
    end do

    !-----------------------------------------------------------------
    !  データ出力の初期設定
    !  Initialize data output
    !-----------------------------------------------------------------

    !-------------------------
    !  xyz_DUDt の出力設定
    !  Configure the settings for "xyz_DUDt" output
    name = 'DUDt'
    longname = 'eastward wind tendency'
    units = 'm s-2'
    allocate( dims(4) )
    dims = StoA( 'lon', 'lat', 'sig', 'time' )

    ! 出力ファイルの初期設定.
    !   * gthist (gt4_history#GT_HISTORY) が設定される.
    ! Initialize output file.
    !   * "gthist" (gt4_history#GT_HISTORY) is configured.
    call output_init  ! これは内部サブルーチン. This is internal subroutine
    deallocate( dims )

    !-------------------------
    !  xyz_DVDt の出力設定
    !  Configure the settings for "xyz_DVDt" output
    name = 'DVDt'
    longname = 'northward wind tendency'
    units = 'm s-2'
    allocate( dims(4) )
    dims = StoA( 'lon', 'lat', 'sig', 'time' )

    ! 出力ファイルの初期設定.
    !   * gthist (gt4_history#GT_HISTORY) が設定される.
    ! Initialize output file.
    !   * "gthist" (gt4_history#GT_HISTORY) is configured.
    call output_init  ! これは内部サブルーチン. This is internal subroutine
    deallocate( dims )

    !-------------------------
    !  xyz_DTempDt の出力設定
    !  Configure the settings for "xyz_DTempDt" output
    name = 'DTempDt'
    longname = 'temperature tendency'
    units = 'K s-1'
    allocate( dims(4) )
    dims = StoA( 'lon', 'lat', 'sig', 'time' )

    ! 出力ファイルの初期設定.
    !   * gthist (gt4_history#GT_HISTORY) が設定される.
    ! Initialize output file.
    !   * "gthist" (gt4_history#GT_HISTORY) is configured.
    call output_init  ! これは内部サブルーチン. This is internal subroutine
    deallocate( dims )

    !-------------------------
    !  xyz_TempEQ の出力設定
    !  Configure the settings for "xyz_TempEQ" output
    name = 'TempEQ'
    longname = 'equilibrium temperature'
    units = 'K'
    allocate( dims(4) )
    dims = StoA( 'lon', 'lat', 'sig', 'time' )

    ! 出力ファイルの初期設定.
    !   * gthist (gt4_history#GT_HISTORY) が設定される.
    ! Initialize output file.
    !   * "gthist" (gt4_history#GT_HISTORY) is configured.
    call output_init  ! これは内部サブルーチン. This is internal subroutine
    deallocate( dims )

    !-----------------------------------------------------------------
    !  このモジュールから出力される変数名のリストを表示
    !  Print list of names of variables output from this module
    !-----------------------------------------------------------------
    call Printf( STDOUT, &
      & ' *** MESSAGE *** +---- "%c" module output varnames list -----', &
      & c1 = 'phy_hs94' )
    call DCHashRewind( hashv = registered_varnames ) ! (inout)
    do
      call DCHashNext( hashv = registered_varnames, & ! (inout)
        & key = name, value = longname, end = end )   ! (out)
      if ( end ) exit
      call Printf( STDOUT, &
        & ' *** MESSAGE *** |      "%c" (%c)', &
        & c1 = trim(name), c2 = trim(longname) )
    enddo
    call DCHashDelete( hashv = registered_varnames ) ! (inout)
    call Printf( STDOUT, &
      & ' *** MESSAGE *** `----------------------------------------' )

    !-----------------------------------------------------------------
    !  設定値の正当性のチェック
    !  Validate setting values
    !-----------------------------------------------------------------

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

  contains

    subroutine output_init
      !
      ! 変数 *name* に関して出力ファイルの初期設定を行います. 
      ! 出力ファイル名や出力間隔などの情報は phy_hs % gthstnml 
      ! から取り出されます. 
      ! 
      ! 変数 *name* に関して出力が行われる場合には, 
      ! *gthist* に出力先ファイルの gt4_history#GT_HISTORY
      ! 型変数を結合させます. そうでない場合は, *gthist* を空状態にします. 
      !
      ! また, 出力データの精度を precision に, 
      ! 出力データ平均化の可否を average に設定します. 
      ! 
      ! 標準出力に表示される変数リスト *registered_varnames* に
      ! *name*, *longname*, *dims*, *units* が登録されます. 
      !
      ! An output file is initialized for a variable *name*. 
      ! Information such as the output filename and output intervals 
      ! is taken out of "phy_hs % gthstnml". 
      !
      ! When output is done for the variable *name*, *gthist* is 
      ! associated with the "gt4_history#GT_HISTORY" variable of 
      ! the output file. Otherwise, *gthist* is nullified. 
      !
      ! Moreover, the accuracy of output data is set to *precision*, and 
      ! right or wrong of averaging the output data is set to *average*. 
      !
      ! *name*, *longname*, *dims*, *units* are registered to 
      ! a list of variables *registered_varnames* that is printed to 
      ! standard output. 
      !
      use dc_date, only: DCDiffTimeCreate, EvalSec, EvalByUnit
      use gt4_history_nmlinfo, only: GTHST_NMLINFO, &
        & HstNmlInfoInitialized, HstNmlInfoInquire, &
        & HstNmlInfoOutputValid, HstNmlInfoAssocGtHist, HstNmlInfoPutLine
      use gt4_history, only: GT_HISTORY, &
        & HistoryCreate, HistoryAddVariable, HistoryPut, &
        & HistoryAddAttr, HistoryInitialized

      !-----------------------------------
      !  作業変数
      !  Work variables
      character(STRING):: file
                                ! ヒストリデータのファイル名. 
                                ! History data filenames
      character(STRING):: dims_str
                                ! 座標軸のリスト. 
                                ! List of axes
      real:: interval_value
                                ! ヒストリデータの出力間隔の数値. 
                                ! Numerical value for interval of history data output
      character(TOKEN):: interval_unit
                                ! ヒストリデータの出力間隔の単位. 
                                ! Unit for interval of history data output
      real(DP), parameter:: PI = 3.1415926535897930_DP
                                ! $ \pi $ . 円周率. Circular constant
    continue
      !-----------------------------------------------------------------
      !  標準出力に表示される変数の登録
      !  Register a variable name for print to standard output
      !-----------------------------------------------------------------
      if ( allocated(dims) ) then
        dims_str = JoinChar( dims, ',' )
      else
        dims_str = ''
      end if
      call DCHashPut( hashv = registered_varnames, &     ! (inout)
        & key = name, &                                  ! (in)
        & value = trim( longname ) // ' [' // &
        &         trim( units ) // '] {' // &
        &         trim( dims_str ) // '}' ) ! (in)

      !-----------------------------------------------------------------
      !  変数の初期化
      !  Initialize variable
      !-----------------------------------------------------------------
      nullify( gthist )
      precision = 'float'
      average = .false.

      !-----------------------------------------------------------------
      !  出力が有効かどうかを確認する
      !  Confirm whether the output is effective
      !-----------------------------------------------------------------
      if ( .not. HstNmlInfoOutputValid( phy_hs % gthstnml, name ) ) then
        return
      end if

      !-----------------------------------------------------------------
      !  GT_HISTORY 変数の取得
      !  Get "GT_HISTORY" variable
      !-----------------------------------------------------------------
      call HstNmlInfoAssocGtHist( &
        & gthstnml = phy_hs % gthstnml, & ! (in)
        & name = name, &                       ! (in)
        & history = gthist, &                  ! (out)
        & err = err )                          ! (out)
      if ( present_and_true( err ) ) return

      call HstNmlInfoInquire( &
        & gthstnml = phy_hs % gthstnml, & ! (in)
        & name = name, &                       ! (in)
        & precision = precision, &             ! (out)
        & average = average, &                 ! (out)
        & err = err )                          ! (out)
      if ( present_and_true( err ) ) return

      !-----------------------------------------------------------------
      !  GT_HISTORY 変数の初期設定の確認
      !  Check initialization of "GT_HISTORY" variable
      !-----------------------------------------------------------------
      if ( HistoryInitialized( gthist ) ) then

        !---------------------------------------------------------------
        !  HistoryAddVariable による変数作成
        !  A variable is created by "HistoryAddVariable"
        !---------------------------------------------------------------
        call HistoryAddVariable( &
          &  history = gthist, &                       ! (inout)
          &  varname = name,         dims = dims, &    ! (in)
          & longname = longname,    units = units, &   ! (in)
          &    xtype = precision, average = average )  ! (in)
        return
      end if

      !-----------------------------------------------------------------
      !  HistoryCreate のための設定値の取得
      !  Get the settings for "HistoryCreate"
      !-----------------------------------------------------------------
      call HstNmlInfoInquire( &
        & gthstnml = phy_hs % gthstnml, & ! (in)
        & name = name, &                       ! (in)
        & file = file, &                       ! (out)
        & interval_unit = interval_unit, &     ! (out)
        & interval_value = interval_value, &   ! (out)
        & err = err )                          ! (out)
      if ( present_and_true( err ) ) return

      !-----------------------------------------------------------------
      !  HistoryCreate によるファイル作成
      !  Files are created by "HistoryCreate"
      !-----------------------------------------------------------------
      call HistoryCreate( &
        & history = gthist, &   ! (out)
        & file = file, &        ! (in)
        & title = 'Held and Suarez (1994) Forcing', &            ! (in)
        & source = 'dcpam4 : ' // trim(version), &               ! (in)
        & institution = 'GFD Dennou Club', &                     ! (in)
        & dims = StoA('lon', 'lat', 'sig', 'time'), &            ! (in)
        & dimsizes = (/ phy_hs % imax, phy_hs % jmax, &
        &               phy_hs % kmax, 0 /), &                ! (in)
        & longnames = StoA('longitude', 'latitude', &
        &                  'sigma at layer midpoints', &
        &                  'time'), &                            ! (in)
        & units = StoA( 'degree_east', 'degree_north', &
        &               '1', interval_unit ), &                  ! (in)
        & origin = real( EvalbyUnit( phy_hs % current_time, &
        &                            interval_unit) ), &         ! (in)
        & interval = interval_value, &                           ! (in)
        & err = err )                                            ! (out)
      if ( present_and_true( err ) ) then
        nullify( gthist )
        return
      end if

      call HistoryAddAttr( &
        & history = gthist, &                            ! (inout)
        & varname = 'lon', attrname = 'standard_name', & ! (in)
        & value = 'longitude' )                          ! (in)
      call HistoryAddAttr( &
        & history = gthist, &                            ! (inout)
        & varname = 'lat', attrname = 'standard_name', & ! (in)
        & value = 'latitude' )                           ! (in)
      call HistoryAddAttr( &
        & history = gthist, &                              ! (inout)
        & varname = 'sig', attrname = 'standard_name', &   ! (in)
        & value = 'atmosphere_sigma_coordinate' )          ! (in)
      call HistoryAddAttr( &
        & history = gthist, &                             ! (inout)
        & varname = 'time', attrname = 'standard_name', & ! (in)
        & value = 'time' )                                ! (in)
      call HistoryAddAttr( &
        & history = gthist, &                              ! (inout)
        & varname = 'sig', attrname = 'positive', &        ! (in)
        & value = 'down' )                                 ! (in)

      call HistoryPut( &
        & history = gthist, &                      ! (inout)
        & varname = 'lon', &                       ! (in)
        & array = phy_hs % x_Lon / PI * 180.0_DP ) ! (in)
      call HistoryPut( &
        & history = gthist, &                      ! (inout)
        & varname = 'lat', &                       ! (in)
        & array = phy_hs % y_Lat / PI * 180.0_DP ) ! (in)
      call HistoryPut( &
        & history = gthist, &          ! (inout)
        & varname = 'sig', &           ! (in)
        & array = phy_hs % z_Sigma )   ! (in)

      call HistoryAddVariable( &
        & history = gthist, &                                 ! (inout)
        & varname = 'lon_weight', &                           ! (in)
        & dims = StoA('lon'), &                               ! (in)
        & longname = 'weight for integration in longitude', & ! (in)
        & units = 'radian', xtype = 'double' )                ! (in)
      call HistoryAddAttr( &
        & history = gthist, &                                 ! (inout)
        & varname = 'lon', attrname = 'gt_calc_weight', &     ! (in)
        & value = 'lon_weight' )                              ! (in)
      call HistoryPut( &
        & history = gthist, &                     ! (inout)
        & varname = 'lon_weight', &               ! (in)
        & array = phy_hs % x_Lon_Weight )         ! (in)

      call HistoryAddVariable( &
        & history = gthist, &                                 ! (inout)
        & varname = 'lat_weight', &                           ! (in)
        & dims = StoA('lat'), &                               ! (in)
        & longname = 'weight for integration in latitude', &  ! (in)
        & units = 'radian', xtype = 'double' )                ! (in)
      call HistoryAddAttr( &
        & history = gthist, &                                 ! (inout)
        & varname = 'lat', attrname = 'gt_calc_weight', &     ! (in)
        & value = 'lat_weight' )                              ! (in)
      call HistoryPut( &
        & history = gthist, &                     ! (inout)
        & varname = 'lat_weight', &               ! (in)
        & array = phy_hs % y_Lat_Weight )         ! (in)

      !-----------------------------------------------------------------
      !  HistoryAddVariable による変数作成
      !  A variable is created by "HistoryAddVariable"
      !-----------------------------------------------------------------
      if ( HistoryInitialized( gthist ) ) then
        call HistoryAddVariable( &
          &  history = gthist, &                       ! (inout)
          &  varname = name,         dims = dims, &    ! (in)
          & longname = longname,    units = units, &   ! (in)
          &    xtype = precision, average = average )  ! (in)
      else
        nullify( gthist )
      end if

    end subroutine output_init

  end subroutine PhyHsCreate

  subroutine PhyHsForcing( phy_hs, &
    & xyz_U,    xyz_V,    xyz_Temp, xy_Ps, &
    & xyz_DUDt, xyz_DVDt, xyz_DTempDt, &
    & historyput_flag, err )
    !
    ! 引数として与えられた東西風速 xyz_U, 南北風速 xyz_V, 
    ! 温度 xyz_Temp から, 
    ! 温度場の帯状対称場への簡単なニュートン冷却と
    ! 境界層摩擦を表現する下層風のレイリー摩擦による
    ! 風速と温度の変化率を求め, 
    ! xyz_DUDt, xyz_DVDt, xyz_DTempDt に返します. 
    !
    ! なお, 与えられた *phy_hs* が Create によって初期設定
    ! されていない場合, プログラムはエラーを発生させます.
    !
    ! Tendencies by simple Newtonian relaxation of the temperature field to a
    ! zonally symmetric state and Rayleigh damping of low-level winds to
    ! represent boundary-layer friction are calculated 
    ! from zonal wind "xyz_U", meridional wind "xyz_V", 
    ! temperature "xyz_Temp".
    ! And the tencencies are returned as 
    ! "xyz_DUDt", "xyz_DVDt", "xyz_DTempDt". 
    !
    ! If *phy_hs* is not initialized by "Create" yet,
    ! error is occurred.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_string, only: PutLine, Printf, Split, StrInclude, StoA, JoinChar
    use dc_types, only: DP, STRING, TOKEN, STDOUT
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT, USR_ERRNO
    use dc_present, only: present_and_true
    use dc_date, only: EvalSec, EvalbyUnit, operator(+)
    use gt4_history_nmlinfo, only: HstNmlInfoInquire, &
      & HstNmlInfoOutputValid, HstNmlInfoAssocGtHist, HstNmlInfoPutLine
    use gt4_history, only: GT_HISTORY, HistoryPut, HistoryInitialized
    implicit none
    type(PHYHS94), intent(inout):: phy_hs
    real(DP), intent(in):: xyz_U (0:phy_hs%imax-1, 0:phy_hs%jmax-1, 0:phy_hs%kmax-1)
                              ! $ U $ . 東西風速. 
                              ! Zonal wind
    real(DP), intent(in):: xyz_V (0:phy_hs%imax-1, 0:phy_hs%jmax-1, 0:phy_hs%kmax-1)
                              ! $ V $ . 南北風速. 
                              ! Meridional wind
    real(DP), intent(in):: xyz_Temp (0:phy_hs%imax-1, 0:phy_hs%jmax-1, 0:phy_hs%kmax-1)
                              ! $ T $ . 温度. 
                              ! Temperature
    real(DP), intent(in):: xy_Ps (0:phy_hs%imax-1, 0:phy_hs%jmax-1)
                              ! $ P_s $ . 地表面気圧. 
                              ! Surface pressure
    real(DP), intent(out):: xyz_DUDt (0:phy_hs%imax-1, 0:phy_hs%jmax-1, 0:phy_hs%kmax-1)
                              ! $ \DP{U}{t} $ . 東西風速変化. 
                              ! Zonal wind tendency
    real(DP), intent(out):: xyz_DVDt (0:phy_hs%imax-1, 0:phy_hs%jmax-1, 0:phy_hs%kmax-1)
                              ! $ \DP{V}{t} $ . 南北風速変化. 
                              ! Meridional wind tendency
    real(DP), intent(out):: xyz_DTempDt (0:phy_hs%imax-1, 0:phy_hs%jmax-1, 0:phy_hs%kmax-1)
                              ! $ \DP{T}{t} $ . 温度変化. 
                              ! Temperature tendency
    logical, intent(in), optional:: historyput_flag
                              ! データ出力のフラグ. 
                              ! SetTime によって時刻を明示的に
                              ! 指定した場合には, この引数に
                              ! .true. または .false. を指定する
                              ! ことでデータ出力のオンオフを
                              ! 明示的に指定する必要があります. 
                              ! デフォルトは .false. です.
                              ! 
                              ! Data output flag. 
                              ! When time is specified by "SetTime", 
                              ! explicit specification of data output
                              ! on/off by specifying ".true." or ".false."
                              ! to this argument.
                              ! Default value is ".false.". 
                              ! 
    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. 

    !-----------------------------------
    !  ヒストリファイルへのデータ出力設定
    !  Configure the settings for history data output
    character(STRING):: name = ''
                              ! 変数名. Variable identifier
    real:: time
                              ! 時刻. Time
    type(GT_HISTORY), pointer:: gthist =>null()
                              ! gt4_history モジュール用構造体. 
                              ! Derived type for "gt4_history" module

    !-----------------------------------
    !  作業変数
    !  Work variables
    integer:: jmax ! 緯度格子点数. 
                   ! Number of grid points in latitude
    integer:: kmax ! 鉛直層数. 
                   ! Number of vertical level

    real(DP):: y_Lat (0:phy_hs%jmax-1)
                              ! 緯度. Latitude
    real(DP):: z_Sigma (0:phy_hs%kmax-1)
                              ! $ \sigma $ レベル (整数). 
                              ! Full $ \sigma $ level

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

    real(DP):: Kappa      ! $ \kappa = R/C_p $ .
                          ! 気体定数の定圧比熱に対する比. Ratio of gas constant to specific heat

    real(DP):: P0             ! $ p_0 $ .
    real(DP):: DelTempY       ! $ (\Delta T)_y $ .
    real(DP):: DelPotTempZ    ! $ (\Delta \theta)_z $ .
    real(DP):: z_kv (0:phy_hs%kmax-1)
                              ! $ k_v $ .
    real(DP):: yz_kt (0:phy_hs%jmax-1, 0:phy_hs%kmax-1)
                              ! $ k_T $ .
    real(DP):: xyz_TempEQ (0:phy_hs%imax-1, 0:phy_hs%jmax-1, 0:phy_hs%kmax-1)
                              ! $ T_{eq} $ . 平衡温度. 
                              ! Equilibrium temperature
    real(DP):: xyz_Press (0:phy_hs%imax-1, 0:phy_hs%jmax-1, 0:phy_hs%kmax-1)
                              ! $ T $ . 圧力. 
                              ! Pressure
    integer:: j, k            ! DO ループ用作業変数
                              ! Work variables for DO loop
    integer:: stat
    character(STRING):: cause_c
    character(*), parameter:: subname = 'PhyHsForcing'
  continue
    call BeginSub( subname )
    stat = DC_NOERR
    cause_c = ''

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

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

    y_Lat   = phy_hs % y_Lat
    z_Sigma = phy_hs % z_Sigma
!!$    DelTime = EvalSec( phy_hs % delta_time )

    Kappa   = phy_hs % Kappa

    P0          = phy_hs % P0
    DelTempY    = phy_hs % DelTempY
    DelPotTempZ = phy_hs % DelPotTempZ
    z_kv        = phy_hs % z_kv
    yz_kt       = phy_hs % yz_kt

    !-----------------------------------------------------------------
    !  東西風速 $ U $ と南北風速 $ V $ へレイリー摩擦を適用
    !  Apply Rayleigh damping to zonal wind $ U $ and meridional wind $ V $
    !-----------------------------------------------------------------
!!$    do k = 0, kmax - 1
!!$      xyz_U (:,:,k) = &
!!$        & xyz_U (:,:,k) &
!!$        & * ( 1.0_DP - 2.0_DP * DelTime * z_kv (k) )
!!$
!!$      xyz_V (:,:,k) = &
!!$        & xyz_V (:,:,k) &
!!$        & * ( 1.0_DP - 2.0_DP * DelTime * z_kv (k) )
!!$    end do

    do k = 0, kmax - 1
      xyz_DUDt (:,:,k) = - z_kv (k) * xyz_U (:,:,k)

      xyz_DVDt (:,:,k) = - z_kv (k) * xyz_V (:,:,k)
    end do


    !-----------------------------------------------------------------
    !  温度 $ T $ へニュートン冷却を適用
    !  Apply Newtonian relaxation to temperature $ T $
    !-----------------------------------------------------------------
    do k = 0, kmax - 1
       xyz_Press(:,:,k) = z_Sigma(k) * xy_Ps
    enddo

    do j = 0, jmax - 1
      xyz_TempEQ(:,j,:) = &
        & max( 200.0_DP, &
        &      ( 315.0_DP &
        &        - DelTempY * sin( y_Lat(j) ) ** 2 &
        &        - DelPotTempZ * log( xyz_Press(:,j,:) / P0 ) &
        &                                 * cos( y_Lat(j) ) ** 2 &
        &      ) &
        &      * ( xyz_Press(:,j,:) / P0 ) ** Kappa &
        &     )
    end do

!!$    do k = 0, kmax - 1
!!$      do j = 0, jmax - 1
!!$        xyz_Temp (:,j,k) = xyz_Temp (:,j,k) &
!!$          & - 2.0_DP * DelTime &
!!$          &   * yz_kt (j,k) * ( xyz_Temp (:,j,k) - xyz_TempEQ (:,j,k) )
!!$      end do
!!$    end do

    do k = 0, kmax - 1
      do j = 0, jmax - 1
        xyz_DTempDt (:,j,k) = &
          & - yz_kt (j,k) * ( xyz_Temp (:,j,k) - xyz_TempEQ (:,j,k) )
      end do
    end do


    !----------------------------------------------------------------
    !  ヒストリファイルへのデータ出力
    !  History data output
    !----------------------------------------------------------------

    !-------------------------
    !  xyz_DUDt の出力
    !  Output "xyz_DUDt"
    name = 'DUDt'

    ! 出力のチェック. 
    !   * gthist (gt4_history#GT_HISTORY), time (単精度実数型) が設定される.
    ! Check for output.
    !   * "gthist" (gt4_history#GT_HISTORY), time (real) are configured.
    call output_check ! これは内部サブルーチン. This is internal subroutine

    ! 出力データを引数 array に渡す.
    ! Give output data to argument "array"
    if ( associated( gthist ) ) then
      call HistoryPut( &
        & history = gthist, &                 ! (inout)
        & varname = name, array = xyz_DUDt, & ! (in)
        & time = time, quiet = .false., &     ! (in)
        & err = err )                         ! (out)
    end if


    !-------------------------
    !  xyz_DVDt の出力
    !  Output "xyz_DVDt"
    name = 'DVDt'

    ! 出力のチェック. 
    !   * gthist (gt4_history#GT_HISTORY), time (単精度実数型) が設定される.
    ! Check for output.
    !   * "gthist" (gt4_history#GT_HISTORY), time (real) are configured.
    call output_check ! これは内部サブルーチン. This is internal subroutine

    ! 出力データを引数 array に渡す.
    ! Give output data to argument "array"
    if ( associated( gthist ) ) then
      call HistoryPut( &
        & history = gthist, &                 ! (inout)
        & varname = name, array = xyz_DVDt, & ! (in)
        & time = time, quiet = .false., &     ! (in)
        & err = err )                         ! (out)
    end if


    !-------------------------
    !  xyz_DTempDt の出力
    !  Output "xyz_DTempDt"
    name = 'DTempDt'

    ! 出力のチェック. 
    !   * gthist (gt4_history#GT_HISTORY), time (単精度実数型) が設定される.
    ! Check for output.
    !   * "gthist" (gt4_history#GT_HISTORY), time (real) are configured.
    call output_check ! これは内部サブルーチン. This is internal subroutine

    ! 出力データを引数 array に渡す.
    ! Give output data to argument "array"
    if ( associated( gthist ) ) then
      call HistoryPut( &
        & history = gthist, &                    ! (inout)
        & varname = name, array = xyz_DTempDt, & ! (in)
        & time = time, quiet = .false., &        ! (in)
        & err = err )                            ! (out)
    end if


    !-------------------------
    !  xyz_TempEQ の出力
    !  Output "xyz_TempEQ"
    name = 'TempEQ'

    ! 出力のチェック. 
    !   * gthist (gt4_history#GT_HISTORY), time (単精度実数型) が設定される.
    ! Check for output.
    !   * "gthist" (gt4_history#GT_HISTORY), time (real) are configured.
    call output_check ! これは内部サブルーチン. This is internal subroutine

    ! 出力データを引数 array に渡す.
    ! Give output data to argument "array"
    if ( associated( gthist ) ) then
      call HistoryPut( &
        & history = gthist, &                   ! (inout)
        & varname = name, array = xyz_TempEQ, & ! (in)
        & time = time, quiet = .false., &       ! (in)
        & err = err )                           ! (out)
    end if

    !-----------------------------------------------------------------
    !  時刻の更新
    !  Update time
    !-----------------------------------------------------------------
    phy_hs % current_time = &
      & phy_hs % current_time + phy_hs % delta_time

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

  contains

    subroutine output_check
      !
      ! 変数 *name* を出力するかどうかをチェックします. 
      ! 出力に関する情報は phy_hs % gthstnml から取り出されます. 
      !
      ! 変数 *name* に関して出力するよう設定されている場合には, 
      ! *gthist* に出力先ファイルの gt4_history#GT_HISTORY
      ! 型変数を結合させます. そうでない場合は, *gthist* を空状態にします. 
      !
      ! また, 現在時刻を *time* に設定します. 
      !
      ! Check whether to output variable *name*. 
      ! Information about output is taken out of "phy_hs % gthstnml". 
      !
      ! When output is done for the variable *name*, *gthist* is 
      ! associated with "gt4_history#GT_HISTORY" variable of
      ! the output file. Otherwise, *gthist* is nullified. 
      !
      ! Moreover, current time is set to *time*. 
      !
      character(TOKEN):: interval_unit
                                ! ヒストリデータの出力間隔の単位. 
                                ! Unit for interval of history data output
    continue

      nullify( gthist )
      time = 0.0

      if ( HstNmlInfoOutputValid( phy_hs % gthstnml, name ) ) then
        call HstNmlInfoInquire( &
          & gthstnml = phy_hs % gthstnml, & ! (in)
          & name = name, &                     ! (in)
          & interval_unit = interval_unit )    ! (out)

        time = real( EvalbyUnit( phy_hs % current_time, interval_unit ) )
        if ( present_and_true( historyput_flag ) ) time = 0.0

        call HstNmlInfoAssocGtHist( & 
          & gthstnml = phy_hs % gthstnml, & 
          & name = name, &                     ! (in)
          & history = gthist, err = err )      ! (out)
        if ( present_and_true( err ) ) then
          nullify( gthist )
          return
        end if

        if ( .not. HistoryInitialized( gthist ) ) nullify( gthist )
      end if

    end subroutine output_check

  end subroutine PhyHsForcing

  subroutine PhyHsClose( phy_hs, err )
    !
    ! PHYHS94 型の変数の終了処理を行います.
    ! なお, 与えられた *phy_hs* が Create によって初期設定
    ! されていない場合, プログラムはエラーを発生させます.
    !
    ! Deconstructor of "PHYHS94".
    ! Note that if *phy_hs* is not initialized by "Create" yet,
    ! error is occurred.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_string, only: PutLine, Printf, Split, StrInclude, StoA, JoinChar
    use dc_types, only: DP, STRING, TOKEN, STDOUT
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
    use gt4_history_nmlinfo, only: HstNmlInfoClose, HstNmlInfoNames, &
      & HstNmlInfoAssocGtHist, HstNmlInfoPutLine
    use gt4_history, only: GT_HISTORY, HistoryClose, HistoryInitialized
    implicit none
    type(PHYHS94), intent(inout):: phy_hs
    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. 

    !-----------------------------------
    !  ヒストリファイルへのデータ出力設定
    !  Configure the settings for history data output
    character(STRING):: name = ''
                              ! 変数名. Variable identifier
    character(STRING):: varnames
                              ! 変数名リスト. 
                              ! List of variables
    character(TOKEN), pointer:: varnames_array(:) =>null()
                              ! 変数名リスト配列. 
                              ! List of variables (array) 
    integer:: i, vnmax
    type(GT_HISTORY), pointer:: gthist =>null()
                              ! gt4_history モジュール用構造体. 
                              ! Derived type for "gt4_history" module

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

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

    !-----------------------------------------------------------------
    !  "PHYHS94" の設定の消去
    !  Clear the settings for "PHYHS94"
    !-----------------------------------------------------------------
    deallocate( phy_hs % x_Lon )
    deallocate( phy_hs % x_Lon_Weight )
    deallocate( phy_hs % y_Lat )
    deallocate( phy_hs % y_Lat_Weight )
    deallocate( phy_hs % z_Sigma )
    deallocate( phy_hs % z_kv )
    deallocate( phy_hs % yz_kt )

    !-----------------------------------------------------------------
    !  ヒストリファイルへのデータ出力の終了処理
    !  Terminate the settings for history data output
    !-----------------------------------------------------------------
    varnames = HstNmlInfoNames( phy_hs % gthstnml )
    call Split( str = varnames, sep = ',', & ! (in)
      & carray = varnames_array )            ! (out)
    vnmax = size( varnames_array )

    do i = 1, vnmax
      name = varnames_array(i)
      if ( trim( name ) == '' ) exit
      nullify( gthist )
      call HstNmlInfoAssocGtHist( & 
        & gthstnml = phy_hs % gthstnml, & ! (in)
        & name = name, &                           ! (in)
        & history = gthist, &                      ! (out)
        & err = err )                              ! (out)
      if ( HistoryInitialized( gthist ) ) then

        call HistoryClose( history = gthist, & ! (inout)
          & err = err )                        ! (out)

      end if
    end do

    !-----------------------------------------------------------------
    !  ヒストリファイルへのデータ出力設定の割付解除
    !  Deallocate the settings for history data output
    !-----------------------------------------------------------------
    call HstNmlInfoClose( &
      & phy_hs % gthstnml, & ! (inout)
      & err = err )                   ! (out)

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

  subroutine PhyHsPutLine( phy_hs, unit, indent, err )
    !
    ! 引数 *phy_hs* に設定されている情報を印字します.
    ! デフォルトではメッセージは標準出力に出力されます. 
    ! *unit* に装置番号を指定することで, 出力先を変更することが可能です.
    !
    ! Print information of *phy_hs*.
    ! 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_types, only: DP, STRING, TOKEN, STDOUT
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
    use dc_string, only: Printf
    use dc_date, only: EvalSec
    use gt4_history_nmlinfo, only: HstNmlInfoPutLine
    implicit none
    type(PHYHS94), intent(in):: phy_hs
    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 = 'PhyHsPutLine'
  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


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

      call Printf( unit = out_unit, &                             ! (in)
        & fmt = indent_str(1:indent_len) // &
        &       ' @imax=%d @jmax=%d @kmax=%d', &                  ! (in)
        & i = (/ phy_hs % imax, phy_hs % jmax, phy_hs % kmax /) ) ! (in)

      call Printf( unit = out_unit, &                             ! (in)
        & fmt = indent_str(1:indent_len) // &
        &       ' @current_time=%f [sec] @delta_time=%f [sec]', & ! (in)
        & d = (/ EvalSec( phy_hs % current_time ), &
        &        EvalSec( phy_hs % delta_time ) /) )              ! (in)

      call Printf(out_unit, &
        & indent_str(1:indent_len) // &
        & ' @x_Lon=%*f', &
        & d=phy_hs % x_Lon, n=(/phy_hs % imax/) )

      call Printf(out_unit, &
        & indent_str(1:indent_len) // &
        & ' @x_Lon_Weight=%*f', &
        & d=phy_hs % x_Lon_Weight, n=(/phy_hs % imax/) )

      call Printf(out_unit, &
        & indent_str(1:indent_len) // &
        & ' @y_Lat=%*f', &
        & d=phy_hs % y_Lat, n=(/phy_hs % jmax/) )

      call Printf(out_unit, &
        & indent_str(1:indent_len) // &
        & ' @y_Lat_Weight=%*f', &
        & d=phy_hs % y_Lat_Weight, n=(/phy_hs % jmax/) )

      call Printf(out_unit, &
        & indent_str(1:indent_len) // &
        & ' @z_Sigma=%*f', &
        & d=phy_hs % z_Sigma, n=(/phy_hs % kmax/) )

      call Printf(out_unit, &
        & indent_str(1:indent_len) // &
        & ' @Kappa=%f @P0=%f', &
        & d=(/phy_hs % Kappa, phy_hs % P0/) )

!!$      call Printf(out_unit, &
!!$        & indent_str(1:indent_len) // &
!!$        & ' @Cp=%f @RAir=%f @Kappa=%f', &
!!$        & d=(/phy_hs % Cp, phy_hs % RAir, phy_hs % Kappa/) )
!!$
!!$      call Printf(out_unit, &
!!$        & indent_str(1:indent_len) // &
!!$        & ' @SigmaB=%f @P0=%f @kf=%f @ka=%f @ks=%f', &
!!$        & d=(/phy_hs % SigmaB, phy_hs % P0, &
!!$        &     phy_hs % kf, phy_hs % ka, phy_hs % ks/) )

      call Printf(out_unit, &
        & indent_str(1:indent_len) // &
        & ' @DelTempY=%f @DelPotTempZ=%f', &
        & d=(/phy_hs % DelTempY, phy_hs % DelPotTempZ/) )

      call Printf(out_unit, &
        & indent_str(1:indent_len) // &
        & ' @z_kv=%*f', &
        & d=phy_hs % z_kv, n=(/phy_hs % kmax/) )

!!$      call Printf(out_unit, &
!!$        & indent_str(1:indent_len) // &
!!$        & ' @yz_kt=%*f', &
!!$        & d=pack( phy_hs % yz_kt ), n=(/phy_hs % jmax * phy_hs % kmax/) )

      call Printf( unit = out_unit, &         ! (in)
        & fmt = indent_str(1:indent_len) // &
        &       ' @gthstnml=' )               ! (in)
      call HstNmlInfoPutLine( &
        & gthstnml = phy_hs % gthstnml, &    ! (in)
        & unit = out_unit, &                          ! (in)
        & indent = indent_str(1:indent_len) // '  ' ) ! (in)

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

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

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

  subroutine PhyHsSetTime( phy_hs, &
    & current_time_value, current_time_unit, &
    & err )
    !
    ! *phy_hs* に対して時刻の設定を行います. 
    !
    ! ヒストリデータを出力している場合には, 
    ! ヒストリデータの出力時刻も設定します. 
    ! 一度でもこのサブルーチンを呼んだ場合には, 
    ! それ以後のヒストリデータ出力前にこのサブルーチンを呼び出し, 
    ! 時刻の設定を行ってください. 
    ! また, データを出力するサブルーチンに対しても 
    ! オプショナル引数 historyput_flag に .true. を与えてください. 
    !
    ! なお, 与えられた *phy_hs* が PhyHsCreate 
    ! によって初期設定されていない場合, プログラムはエラーを発生させます. 
    !
    ! Set time to *phy_hs*. 
    !
    ! When history data are output, 
    ! the output time of history data are specified. 
    ! Once this subroutine is called, the time of history data must be 
    ! specified by this routine before history data output. 
    ! In additional, give ".true." to an optional argument 
    ! "historyput_flag" of a data output subroutine. 
    !
    ! If *phy_hs* is not initialized 
    ! by "PhyHsCreate" yet, error is occurred. 
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_string, only: PutLine, Printf, Split, StrInclude, StoA, JoinChar
    use dc_types, only: DP, STRING, TOKEN, STDOUT
    use dc_date, only: DCDiffTimeCreate, EvalbyUnit
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
    use gt4_history_nmlinfo, only: HstNmlInfoAdd, HstNmlInfoInquire, &
      & HstNmlInfoNames, HstNmlInfoAssocGtHist, &
      & HstNmlInfoOutputStepDisable, HstNmlInfoPutLine
    use gt4_history, only: GT_HISTORY, HistorySetTime, HistoryInitialized
    implicit none
    type(PHYHS94), intent(inout):: phy_hs
    real, intent(in):: current_time_value
                              ! 現在時刻の数値. Numerical value of current time
    character(*), intent(in):: current_time_unit
                              ! 現在時刻の単位. Unit of current time
    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. 

    !-----------------------------------
    !  ヒストリファイルへのデータ出力設定
    !  Configure the settings for history data output
    character(STRING):: name = ''
                              ! 変数名. Variable identifier
    character(TOKEN):: interval_unit
                              ! ヒストリデータの出力間隔の単位. 
                              ! Unit for interval of history data output
    character(STRING):: varnames
                              ! 変数名リスト. 
                              ! List of variables
    character(TOKEN), pointer:: varnames_array(:) =>null()
                              ! 変数名リスト配列. 
                              ! List of variables (array) 
    integer:: i, vnmax
    type(GT_HISTORY), pointer:: gthist =>null()
                              ! gt4_history モジュール用構造体. 
                              ! Derived type for "gt4_history" module

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

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

    !-----------------------------------------------------------------
    !  時刻設定
    !  Configure time
    !-----------------------------------------------------------------
    call DCDiffTimeCreate( &
      & diff = phy_hs % current_time, &  ! (out)
      & value = real( current_time_value, DP ), & ! (in)
      & unit = current_time_unit )                ! (in)

    !-----------------------------------------------------------------
    !  ヒストリファイルへのデータの時刻設定
    !  Configure the time of history data
    !-----------------------------------------------------------------
    varnames = HstNmlInfoNames( phy_hs % gthstnml )
    call Split( str = varnames, sep = ',', & ! (in)
      & carray = varnames_array )            ! (out)
    vnmax = size( varnames_array )

    do i = 1, vnmax
      name = varnames_array(i)
      if ( trim( name ) == '' ) exit

      call HstNmlInfoOutputStepDisable( & 
        & gthstnml = phy_hs % gthstnml, & ! (inout)
        & name = name, &                           ! (in)
        & err = err )                              ! (out)

      nullify( gthist )
      call HstNmlInfoAssocGtHist( & 
        & gthstnml = phy_hs % gthstnml, & ! (in)
        & name = name, &                           ! (in)
        & history = gthist, &                      ! (out)
        & err = err )                              ! (out)

      if ( HistoryInitialized( gthist ) ) then
        call HstNmlInfoInquire( &
          & gthstnml = phy_hs % gthstnml, & ! (in)
          & name = name, &                           ! (in)
          & interval_unit = interval_unit )          ! (out)

        call HistorySetTime( &
          & history = gthist, &                     ! (inout)
          & time = &
          &   real( EvalbyUnit( phy_hs % current_time, &
          &                     interval_unit) ) ) ! (in)
      end if

    end do

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

  end subroutine PhyHsSetTime

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

  subroutine PhyHsNmlRead( nmlfile, &
!!$    & CoefAlpha, &
!!$    & key00_, &
    & gthstnml, &
    & err )
    !
    ! NAMELIST ファイル *nmlfile* から値を入力するための
    ! 内部サブルーチンです. PhyHsCreate 内で呼び出されることを
    ! 想定しています.
    !
    ! 値が NAMELIST ファイル内で指定されていない場合には,
    ! 入力された値がそのまま返ります.
    !
    ! なお, *nmlfile* に空文字が与えられた場合, または
    ! 与えられた *nmlfile* を読み込むことができない場合, 
    ! プログラムはエラーを発生させます.
    !
    ! This is an internal subroutine to input values from 
    ! NAMELIST file *nmlfile*. This subroutine is expected to be
    ! called by "PhyHsCreate".
    !
    ! 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, Split, StrInclude, StoA, JoinChar
    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_date, only: DCDiffTimeCreate
    use dc_error, only: StoreError, DC_NOERR, DC_ENOFILEREAD, DC_ENOASSOC
    use gt4_history_nmlinfo, only: GTHST_NMLINFO, HstNmlInfoAdd, &
      & HstNmlInfoInquire, HstNmlInfoInitialized, HstNmlInfoPutLine
    implicit none
    character(*), intent(in):: nmlfile
                              ! NAMELIST ファイルの名称. 
                              ! NAMELIST file name

!!$    real(DP), intent(inout):: CoefAlpha
!!$                              ! $ \alpha $ . 係数. Coefficient
!!$
!!$    character(*), intent(inout):: key00_
!!$    character(TOKEN):: key00
!!$                              ! キーワード. Keyword
!!$

    type(GTHST_NMLINFO), intent(inout):: gthstnml
                              ! NAMELIST#phy_hs94_history_nml 
                              ! から入手される個別のデータ出力情報. 
                              ! 
                              ! 初期設定やデフォルト値の設定などを
                              ! 行った後に与えること. 
                              ! 
                              ! Individual data output information from 
                              ! "NAMELIST#phy_hs94_history_nml". 
                              ! 
                              ! Before this argument is given to 
                              ! this procedure, initialize and 
                              ! configure the defaut settings. 
    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_hs94_nml/ &
!!$      & CoefAlpha, key00
                              ! phy_hs94 モジュール用
                              ! NAMELIST 変数群名.
                              !
                              ! phy_hs94#PhyHsCreate を使用する際に, 
                              ! オプショナル引数 *nmlfile* へ NAMELIST 
                              ! ファイル名を指定することで, そのファイルから
                              ! この NAMELIST 変数群を読み込みます.
                              !
                              ! NAMELIST group name for
                              ! "phy_hs94" module.
                              ! 
                              ! If a NAMELIST filename is specified to 
                              ! an optional argument *nmlfile* 
                              ! when "phy_hs94#PhyHsCreate" is used, 
                              ! this NAMELIST group is loaded from 
                              ! the file.

    character(STRING):: name
                              ! 変数名. 
                              ! 空白の場合には, この他の設定値は
                              ! phy_hs94 モジュールにおいて
                              ! 出力されるデータ全ての
                              ! デフォルト値となります. 
                              ! 
                              ! "Data1,Data2" のようにカンマで区切って複数
                              ! の変数を指定することも可能です. 
                              ! 
                              ! Variable identifier. 
                              ! If blank is given, other values are 
                              ! used as default values of output data 
                              ! in "phy_hs94". 
                              ! 
                              ! Multiple variables can be specified 
                              ! as "Data1,Data2" too. Delimiter is comma. 
    character(STRING):: file
                              ! 出力ファイル名. 
                              ! これはデフォルト値としては使用されません. 
                              ! *name* に値が設定されている時のみ有効です. 
                              ! 
                              ! Output file name. 
                              ! This is not used as default value. 
                              ! This value is valid only when *name* is 
                              ! specified. 

    real:: interval_value
                              ! ヒストリデータの出力間隔の数値. 
                              ! 負の値を与えると, 出力を抑止します. 
                              ! Numerical value for interval of history data output
                              ! Negative values suppresses output.
    character(TOKEN):: interval_unit
                              ! ヒストリデータの出力間隔の単位. 
                              ! Unit for interval of history data output
    character(TOKEN):: precision
                              ! ヒストリデータの精度. 
                              ! Precision of history data
    logical:: average
                              ! 出力データの平均化フラグ. 
                              ! Flag for average of output data
    character(STRING):: fileprefix
                              ! ヒストリデータのファイル名の接頭詞. 
                              ! Prefixes of history data filenames

    namelist /phy_hs94_history_nml/ &
      & name, &
      & file, &
      & interval_value, &
      & interval_unit, &
      & precision, &
      & fileprefix, &
      & average
                              ! phy_hs94 モジュールのヒストリデータ用
                              ! NAMELIST 変数群名.
                              !
                              ! phy_hs94#PhyHsCreate を使用する際に, 
                              ! オプショナル引数 *nmlfile* へ NAMELIST 
                              ! ファイル名を指定することで, そのファイルから
                              ! この NAMELIST 変数群を読み込みます.
                              !
                              ! NAMELIST group name for 
                              ! history data of "phy_hs94" module.
                              ! 
                              ! If a NAMELIST filename is specified to 
                              ! an optional argument *nmlfile* 
                              ! when "phy_hs94#PhyHsCreate" 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(TOKEN):: pos_nml
                              ! NAMELIST 読み込み時のファイル位置. 
                              ! File position of NAMELIST read
    character(*), parameter:: subname = 'PhyHsNmlRead'
  continue
    call BeginSub( subname )
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------

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

    !----------------------------------------------------------------
    !  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
    !-----------------------------------------------------------------
    !-------------------------
    !  係数などの取得
    !  Get coefficients etc.
!!$    rewind( unit_nml )
!!$    read( unit = unit_nml, & ! (in)
!!$      & nml = phy_hs94_nml, iostat = iostat_nml ) ! (out)
!!$    if ( iostat_nml == 0 ) then
!!$      call MessageNotify( 'M', subname, &
!!$        & 'NAMELIST group "%c" is loaded from "%c".', &
!!$        & c1 = 'phy_hs94_nml', c2 = trim(nmlfile) )
!!$      write(STDOUT, nml = phy_hs94_nml)
!!$    else
!!$      call MessageNotify( 'W', subname, &
!!$        & 'NAMELIST group "%c" is not found in "%c" (iostat=%d).', &
!!$        & c1 = 'phy_hs94_nml', c2 = trim(nmlfile), &
!!$        & i = (/iostat_nml/) )
!!$    end if

    !-------------------------
    !  出力データの個別情報の取得
    !  Get individual information of output data
    rewind( unit_nml )
    iostat_nml = 0
    pos_nml = ''
    do while ( trim(pos_nml) /= 'APPEND' .and. iostat_nml == 0 )

      name                   = ''
      file                   = ''
      call HstNmlInfoInquire( &
        & gthstnml = gthstnml, &             ! (in)
        & interval_value = interval_value, & ! (out)
        & interval_unit = interval_unit, &   ! (out)
        & precision = precision, &           ! (out)
        & average = average, &               ! (out)
        & fileprefix = fileprefix )          ! (out)

      read( unit = unit_nml, &                      ! (in)
        &    nml = phy_hs94_history_nml, & ! (out)
        & iostat = iostat_nml )                     ! (out)
      inquire( unit = unit_nml, & ! (in)
        &  position = pos_nml )   ! (out)

      if ( iostat_nml == 0 ) then
        call MessageNotify( 'M', subname, &
          & 'NAMELIST group "%c" is loaded from "%c".', &
          & c1='phy_hs94_history_nml', c2=trim(nmlfile) )
        write(STDOUT, nml = phy_hs94_history_nml)

        call HstNmlInfoAdd( &
          & gthstnml = gthstnml, &             ! (in)
          & name = name, &                     ! (in)
          & file = file, &                     ! (in)
          & interval_value = interval_value, & ! (in)
          & interval_unit = interval_unit, &   ! (in)
          & precision = precision, &           ! (in)
          & average = average, &               ! (in)
          & fileprefix = fileprefix )          ! (in)

      else
        call MessageNotify( 'W', subname, &
          & 'NAMELIST group "%c" is not found in "%c" any more (iostat=%d).', &
          & c1='phy_hs94_history_nml', c2=trim(nmlfile), &
          & i = (/iostat_nml/) )
      end if
    end do

    close( unit_nml )

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

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

end module phy_hs94
