!= Output frequently used variables
!
!= Output frequently used variables
!
! Authors::   Yoshiyuki O. Takahashi
! Version::   $Id: output_freq_used_vars.f90,v 1.2 2015/02/11 11:55:46 yot Exp $ 
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2008. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module output_freq_used_vars
  !
  != Output frequently used variables
  !
  != Output frequently used variables
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  !
  !== References
  !
!!$  !  McFarlane, N. A., 
!!$  !    The effect of orographically excited gravity wave drag on the general
!!$  !    circulation of the lower stratosphere and troposphsere,
!!$  !    J. Atmos. Sci., 44, 1775-1800, 1987.
  !
  !== Procedures List
  !
!!$  ! GWDM1987     :: Calculation of gravity wave drag tendency
!!$  ! GWDM1987Init :: Initialization
!!$  ! ------------ :: ------------
!!$  ! GWDM1987     :: Calculation of gravity wave drag tendency
!!$  ! GWDM1987Init :: Initialization
  !
  !== NAMELIST
  !
  ! NAMELIST#gwd_m1987_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

  ! 組成に関わる配列の設定
  ! Settings of array for atmospheric composition
  !
  use composition, only: &
    &                    ncmax

  ! 種別型パラメタ
  ! 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

  ! 物理・数学定数設定
  ! Physical and mathematical constants settings
  !
  use constants0, only: &
    & PI                    ! $ \pi $.
                            ! 円周率. Circular constant


  ! 宣言文 ; Declaration statements
  !
  implicit none
  private

  ! 公開手続き
  ! Public procedure
  !
  public :: OutputFreqUsedVars
  public :: OutputFreqUsedVarsInit

  ! 公開変数
  ! Public variables
  !

  ! 非公開変数
  ! Private variables
  !
  real(DP), save :: AdiabLapseRate
                              ! Adiabatic lapse rate
  real(DP), save :: SigmaRefForSLP
                              ! Sigma of level for calculation of scale height


  logical, save :: output_freq_used_vars_inited = .false.
                              ! 初期設定フラグ. 
                              ! Initialization flag

  character(*), parameter:: module_name = 'output_freq_used_vars'
                              ! モジュールの名称. 
                              ! Module name
  character(*), parameter:: version = &
    & '$Name:  $' // &
    & '$Id: output_freq_used_vars.f90,v 1.2 2015/02/11 11:55:46 yot Exp $'
                              ! モジュールのバージョン
                              ! Module version

contains

  subroutine OutputFreqUsedVars(     &
    & xy_PsA, xyz_TempA, xyzf_QMixA, & ! (in)
    & xy_SurfHeight                  & ! (in)
    & )
    !
    ! 
    !
    ! Output frequently used variables
    !

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

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

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

    ! 組成に関わる配列の設定
    ! Settings of array for atmospheric composition
    !
    use composition, only: &
      &                    IndexH2OVap, &
      &                    a_QMixName
                              ! 成分の変数名
                              ! Name of variables for composition

    ! 物理定数設定
    ! Physical constants settings
    !
    use constants, only: &
      & Grav, & 
                              ! $ g $ [m s-2]. 
                              ! 重力加速度. 
                              ! Gravitational acceleration
      & GasRDry, &
                              ! $ R $ [J kg-1 K-1]. 
                              ! 乾燥大気の気体定数. 
                              ! Gas constant of air
      & CpDry
                              ! $ C_p $ [J kg-1 K-1].
                              ! 乾燥大気の定圧比熱.
                              ! Specific heat of air at constant pressure

    ! 積分と平均の操作
    ! Operation for integral and average
    !
    use intavr_operate, only: IntLonLat_xy

    ! 温度の半整数σレベルの補間, 気圧と高度の算出
    ! Interpolate temperature on half sigma level,
    ! and calculate pressure and height
    !
    use auxiliary, only: AuxVars

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


    ! 宣言文 ; Declaration statements
    !

    real(DP), intent(in ) :: xy_PsA       (0:imax-1, 1:jmax)
                              ! Temperature
    real(DP), intent(in ) :: xyz_TempA    (0:imax-1, 1:jmax, 1:kmax)
                              ! Temperature
    real(DP), intent(in ) :: xyzf_QMixA   (0:imax-1, 1:jmax, 1:kmax, 1:ncmax)
    real(DP), intent(in ) :: xy_SurfHeight(0:imax-1, 1:jmax)


    ! 作業変数
    ! Work variables
    !
    real(DP) :: xyr_Press     (0:imax-1, 1:jmax, 0:kmax)
                              ! Pressure
    real(DP) :: xyz_Press     (0:imax-1, 1:jmax, 1:kmax)
                              ! Pressure
    real(DP) :: xyz_Exner     (0:imax-1, 1:jmax, 1:kmax)
                              ! Exner function
    real(DP) :: xyz_VirTemp   (0:imax-1, 1:jmax, 1:kmax)
                              ! Virtual temperature
    real(DP) :: xyz_Height    (0:imax-1, 1:jmax, 1:kmax)
                              ! Height

    real(DP) :: xy_Sum        (0:imax-1, 1:jmax)
    real(DP) :: Sum

    real(DP) :: xyz_Rho       (0:imax-1, 1:jmax, 1:kmax)
                              ! Pressure
    real(DP) :: xyz_PotTemp   (0:imax-1, 1:jmax, 1:kmax)
                              ! Potential temperature
    real(DP) :: xyz_BVFreqSq  (0:imax-1, 1:jmax, 1:kmax)
                              ! Brunt-Vaisalla frequency squared

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

    integer  :: xy_KIndex          (0:imax-1, 1:jmax)
                              ! K index for reference level used for SLP calc.
    real(DP) :: xy_PressRefForSLP  (0:imax-1, 1:jmax)
    real(DP) :: xy_HeightRefForSLP (0:imax-1, 1:jmax)
    real(DP) :: xy_VirTempRefForSLP(0:imax-1, 1:jmax)
    real(DP) :: xy_ScaleHeight     (0:imax-1, 1:jmax)
    real(DP) :: xy_SLP             (0:imax-1, 1:jmax)
                              ! Sea level pressure


    integer :: i               ! 経度方向に回る DO ループ用作業変数
                               ! Work variables for DO loop in longitude
    integer :: j               ! 緯度方向に回る DO ループ用作業変数
                               ! Work variables for DO loop in latitude
    integer :: k               ! 鉛直方向に回る DO ループ用作業変数
                               ! Work variables for DO loop in vertical direction
    integer :: kp
    integer :: kn
    integer :: n


    ! 実行文 ; Executable statement
    !

    ! 初期化確認
    ! Initialization check
    !
    if ( .not. output_freq_used_vars_inited ) then
      call MessageNotify( 'E', module_name, 'This module has not been initialized.' )
    end if

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


    ! 温度の半整数σレベルの補間, 気圧と高度の算出
    ! Interpolate temperature on half sigma level,
    ! and calculate pressure and height
    !
    call AuxVars( &
      & xy_PsA, xyz_TempA, xyzf_QMixA(:,:,:,IndexH2OVap),    & ! (in )
      & xy_SurfHeight = xy_SurfHeight,                       & ! (in ) optional
      & xyr_Press     = xyr_Press,                           & ! (out) optional
      & xyz_Press     = xyz_Press,                           & ! (out) optional
      & xyz_VirTemp   = xyz_VirTemp,                         & ! (out) optional
      & xyz_Height    = xyz_Height,                          & ! (out) optional
      & xyz_Exner     = xyz_Exner                            & ! (out) optional
      & )
    !
    do n = 1, ncmax
      xy_Sum = 0.0_DP
      do k = kmax, 1, -1
        xy_Sum = xy_Sum + xyzf_QMixA(:,:,k,n) &
          & * ( xyr_Press(:,:,k-1) - xyr_Press(:,:,k) ) / Grav
      end do
      Sum = IntLonLat_xy( xy_Sum )
      call HistoryAutoPut( TimeA, 'GM'//trim(a_QMixName(n)), Sum )
    end do
    !
    xyz_Rho = xyz_Press / ( GasRDry * xyz_TempA )
    call HistoryAutoPut( TimeA, 'Rho', xyz_TempA / xyz_Exner )
    !
    call HistoryAutoPut( TimeA, 'Height', xyz_Height )
    !
    xyz_PotTemp = xyz_TempA / xyz_Exner
    call HistoryAutoPut( TimeA, 'PotTemp', xyz_PotTemp )
    !
    do k = 1, kmax
      kp = max( k - 1, 1    )
      kn = min( k + 1, kmax )
      xyz_BVFreqSq(:,:,k) =                               &
        & Grav / xyz_PotTemp(:,:,k)                       &
        & * ( xyz_PotTemp(:,:,kn) - xyz_PotTemp(:,:,kp) ) &
        & / ( xyz_Height (:,:,kn) - xyz_Height (:,:,kp) )
    end do
    call HistoryAutoPut( TimeA, 'BVFreqSq', xyz_BVFreqSq )


    xy_KIndex = 1
    do k = 1, kmax
      do j = 1, jmax
        do i = 0, imax-1
          if ( xyz_Press(i,j,k) / xy_PsA(i,j) > SigmaRefForSLP ) then
            xy_KIndex(i,j) = k
          end if
        end do
      end do
    end do
    do j = 1, jmax
      do i = 0, imax-1
        xy_PressRefForSLP  (i,j) = xyz_Press  (i,j,xy_KIndex(i,j))
        xy_HeightRefForSLP (i,j) = xyz_Height (i,j,xy_KIndex(i,j))
        xy_VirTempRefForSLP(i,j) = xyz_VirTemp(i,j,xy_KIndex(i,j))
      end do
    end do
    xy_SLP = &
      & xy_PressRefForSLP &
      & * (   1.0_DP &
      &     + AdiabLapseRate &
      &       * ( 0.0_DP - xy_HeightRefForSLP ) / xy_VirTempRefForSLP &
      &   )**( - Grav / ( GasRDry * AdiabLapseRate ) )
    call HistoryAutoPut( TimeA, 'SLP', xy_SLP )


    xyz_QVapSat = xyz_CalcQVapSat( xyz_TempA, xyz_Press )
    xyz_RH = xyzf_QMixA(:,:,:,IndexH2OVap) / xyz_QVapSat
    call HistoryAutoPut( TimeA, 'RH', xyz_RH )

    xyz_QVapSat = xyz_CalcQVapSatOnLiq( xyz_TempA, xyz_Press )
    xyz_RH = xyzf_QMixA(:,:,:,IndexH2OVap) / xyz_QVapSat
    call HistoryAutoPut( TimeA, 'RHOnWat', xyz_RH )


    ! MEMO
    !
    ! dp/dz = - \rho g
    !       = - p / (RT) g
    ! 1/p dp/dz = - g / (RT)
    ! d(lnp)/dz = - g / (RT)
    !
    ! \int_{z_0}^z d{lnp(z')}/dz' = - \int_{z_0}^z g / (RT(z')) dz'
    ! ln{p(z)} - ln{p(z_0)} = - g/R \int_{z_0}^z 1/T(z') dz'
    ! ln{p(z)/p(z_0)}
    ! = - g/R \int_{z_0}^z 1/T(z') dz'
    ! = - g/R \int_{z_0}^z 1/{ T(z_0) + \Gamma (z' - z_0) } dz'
    ! = - g/(R \Gamma) \int_{z_0}^z \Gamma/{ T(z_0) + \Gamma (z' - z_0) } dz'
    ! = - g/(R \Gamma) [ ln{ T(z_0) + \Gamma (z' - z_0) } ]_{z_0}^z
    ! = - g/(R \Gamma) [ ln{ T(z_0) + \Gamma (z - z_0) } - ln{ T(z_0) } ]
    ! = - g/(R \Gamma) ln[ { T(z_0) + \Gamma (z - z_0) } / T(z_0) ]
    ! = ln[ { T(z_0) + \Gamma (z - z_0) } / T(z_0) ]^{- g/(R \Gamma)}
    ! p(z)/p(z_0)
    ! = [ { T(z_0) + \Gamma (z - z_0) } / T(z_0) ]^{- g/(R \Gamma)}
    ! p(z)
    ! = p(z_0) [ { T(z_0) + \Gamma (z - z_0) } / T(z_0) ]^{- g/(R \Gamma)}
    ! = p(z_0) { 1.0 + \Gamma (z - z_0) / T(z_0) }^{- g/(R \Gamma)}
    !
    ! T(z) = T(z_0) + \Gamma (z - z_0)


    do j = 1, jmax
      do i = 0, imax-1
        xy_ScaleHeight(i,j) = GasRDry * xyz_VirTemp(i,j,xy_KIndex(i,j)) / Grav
      end do
    end do
    xy_SLP = xy_PsA * exp( - ( 0.0_DP - xy_SurfHeight ) / xy_ScaleHeight )
    call HistoryAutoPut( TimeA, 'SLPTmp', xy_SLP )


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

  end subroutine OutputFreqUsedVars

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

  subroutine OutputFreqUsedVarsInit
    !
    ! moist_conv_adjust モジュールの初期化を行います. 
    ! NAMELIST#moist_conv_adjust_nml の読み込みはこの手続きで行われます. 
    !
    ! "moist_conv_adjust" module is initialized. 
    ! "NAMELIST#moist_conv_adjust_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

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

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

    ! 座標データ設定
    ! Axes data settings
    !
    use axesset, only: &
      & AxnameX, &
      & AxnameY, &
      & AxnameZ, &
      & AxnameR, &
      & AxnameT

    ! 組成に関わる配列の設定
    ! Settings of array for atmospheric composition
    !
    use composition, only: &
    &                    a_QMixName
                              ! 成分の変数名
                              ! Name of variables for composition

    ! 物理定数設定
    ! Physical constants settings
    !
    use constants, only: &
      & Grav, & 
                              ! $ g $ [m s-2]. 
                              ! 重力加速度. 
                              ! Gravitational acceleration
      & GasRDry, &
                              ! $ R $ [J kg-1 K-1]. 
                              ! 乾燥大気の気体定数. 
                              ! Gas constant of air
      & CpDry
                              ! $ C_p $ [J kg-1 K-1].
                              ! 乾燥大気の定圧比熱.
                              ! Specific heat of air at constant pressure

    ! 宣言文 ; Declaration statements
    !
    implicit none

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

!!$    real(DP)         :: GWDDampPeriodValue
!!$    character(TOKEN) :: GWDDampPeriodUnit

    integer:: n


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

    ! 実行文 ; Executable statement
    !

    if ( output_freq_used_vars_inited ) return


    ! デフォルト値の設定
    ! Default values settings
    !
    SigmaRefForSLP = exp( - 200.0_DP / ( ( GasRDry * 300.0_DP ) / Grav ) )
                              ! 200 m height is approximately set

    AdiabLapseRate = - 5.0e-3_DP
                              ! Another example:
                              ! -5 degrees / km
                              ! This value is originated from JMA method
                              ! (see dcmodel e-mail at 2013/03/25 from 
                              ! Toyoda-san).
                              ! In addition, this value is shown in a book 
                              ! by Ninomiya-sensei, "気象がわかる数と式".

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

      call NmlutilMsg( iostat_nml, module_name ) ! (in)
    end if


    ! Calculation of divergence damping period
    !
!!$    GWDDampPeriod = DCCalConvertByUnit( GWDDampPeriodValue, GWDDampPeriodUnit, 'sec' )

    ! ヒストリデータ出力のためのへの変数登録
    ! Register of variables for history data output
    !
    do n = 1, ncmax
      call HistoryAutoAddVariable( 'GM'//trim(a_QMixName(n)), &  ! (in)
        & (/ AxNameT /),                                      &  ! (in)
        & 'global mean column mass of ' // trim(a_QMixName(n)), 'kg m-2' ) ! (in)
    end do
    call HistoryAutoAddVariable( 'Rho'    ,       &  ! (in)
      & (/ AxNameX, AxNameY, AxNameZ, AxNameT /), &  ! (in)
      & 'density', 'kg m-3' )                        ! (in)
    call HistoryAutoAddVariable( 'Height' ,       &  ! (in)
      & (/ AxNameX, AxNameY, AxNameZ, AxNameT /), &  ! (in)
      & 'geopotential height', 'm' )                 ! (in)
    call HistoryAutoAddVariable( 'PotTemp' ,      &  ! (in)
      & (/ AxNameX, AxNameY, AxNameZ, AxNameT /), &  ! (in)
      & 'potential temperature', 'K' )               ! (in)
    call HistoryAutoAddVariable( 'BVFreqSq'    ,  &  ! (in)
      & (/ AxNameX, AxNameY, AxNameZ, AxNameT /), &  ! (in)
      & 'Brunt-Vaisala frequency squared', 's-2' )   ! (in)
    call HistoryAutoAddVariable( 'RH'          ,  &  ! (in)
      & (/ AxNameX, AxNameY, AxNameZ, AxNameT /), &  ! (in)
      & 'relative humidity', '1' )                   ! (in)
    call HistoryAutoAddVariable( 'RHOnWat'     ,  &  ! (in)
      & (/ AxNameX, AxNameY, AxNameZ, AxNameT /), &  ! (in)
      & 'relative humidity on water', '1' )          ! (in)
    call HistoryAutoAddVariable( 'SLP'    ,       &  ! (in)
      & (/ AxNameX, AxNameY, AxNameT /),          &  ! (in)
      & 'sea level pressure', 'Pa' )                 ! (in)
    call HistoryAutoAddVariable( 'SLPTmp' ,       &  ! (in)
      & (/ AxNameX, AxNameY, AxNameT /),          &  ! (in)
      & 'sea level pressure', 'Pa' )                 ! (in)


    ! Initialization of modules used in this module
    !


    ! 印字 ; Print
    !
    call MessageNotify( 'M', module_name, '----- Initialization Messages -----' )
!!$    call MessageNotify( 'M', module_name, '  FlagUse               = %b', l = (/ FlagUse /) )
    call MessageNotify( 'M', module_name, '  SigmaRefForSLP = %f', d = (/ SigmaRefForSLP /) )
    call MessageNotify( 'M', module_name, '  AdiabLapseRate = %f', d = (/ AdiabLapseRate /) )
    call MessageNotify( 'M', module_name, '    (compared to -g/Cp = %f)', d = (/ (- Grav / CpDry) /) )
    call MessageNotify( 'M', module_name, '-- version = %c', c1 = trim(version) )

    output_freq_used_vars_inited = .true.

  end subroutine OutputFreqUsedVarsInit

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

end module output_freq_used_vars
