!= 地表面フラックスユーティリティ
!
!= Surface flux utility routines
!
! Authors::   Yoshiyuki O. Takahashi
! Version::   $Id: surface_flux_util.f90,v 1.1 2013/10/06 13:44:15 yot Exp $ 
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2008-2009. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module surface_flux_util
  !
  != 地表面フラックスユーティリティ
  !
  != Surface flux utility routines
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  ! 地表面フラックスを計算. 
  !
  ! Surface fluxes are calculated.
  !
  !== References
  !
!!$  ! Louis, J-F., M. Tiedtke, and J-F. Geleyn, 
!!$  ! A short history of the PBL parameterization at ECMWF, 
!!$  ! Workshop on Planetary Boundary Layer Parameterization, 59-80, ECMWF, Reading, U.K., 
!!$  ! 1982.
  !
  !== Procedures List
  !
!!$  ! SurfaceFlux       :: 地表面フラックスの計算
!!$  ! ------------      :: ------------
!!$  ! SurfaceFlux       :: Calculate surface fluxes
  !
  !== NAMELIST
  !
  ! NAMELIST#surface_flux_util_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, &
    & IndexH2OVap

  ! 種別型パラメタ
  ! Kind type parameter
  !
  use dc_types, only: DP, &      ! 倍精度実数型. Double precision. 
    &                 STRING     ! 文字列.       Strings. 

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

  ! 宣言文 ; Declaration statements
  !
  implicit none
  private

  ! 公開手続き
  ! Public procedure
  !
  public :: SurfaceFluxUtilLimitFlux
  public :: SurfaceFluxUtilInit

  ! 公開変数
  ! Public variables
  !

  ! 非公開変数
  ! Private variables
  !
  logical, save :: surface_flux_util_inited = .false.
                              ! 初期設定フラグ. 
                              ! Initialization flag

  character(*), parameter:: module_name = 'surface_flux_util'
                              ! モジュールの名称. 
                              ! Module name
  character(*), parameter:: version = &
    & '$Name:  $' // &
    & '$Id: surface_flux_util.f90,v 1.1 2013/10/06 13:44:15 yot Exp $'
                              ! モジュールのバージョン
                              ! Module version


contains

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

  subroutine SurfaceFluxUtilLimitFlux( &
    & DelTime,                         & ! (in)
    & xyzf_QMix, xyr_Press,            & ! (in)
    & xy_SurfH2OVapFlux &!, xyf_QMixFlux  & ! (inout)
    & )
    !
    ! 
    !
    ! Restrict surface flux 
    ! Now, only the H2O vapor flux is restricted.
    !

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

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

    ! 物理定数設定
    ! Physical constants settings
    !
    use constants, only: &
      & Grav                  ! $ g $ [m s-2].
                              ! 重力加速度.
                              ! Gravitational acceleration

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

    ! デバッグ用ユーティリティ
    ! Utilities for debug
    !
    use dc_trace, only: DbgMessage, BeginSub, EndSub

    ! 宣言文 ; Declaration statements
    !
    implicit none

    real(DP), intent(in):: DelTime
                              ! Time step
    real(DP), intent(in):: xyzf_QMix(0:imax-1, 1:jmax, 1:kmax, 1:ncmax)
                              ! $ q $ .     比湿. Specific humidity
    real(DP), intent(in):: xyr_Press (0:imax-1, 1:jmax, 0:kmax)
                              ! $ p_s $ . 地表面気圧 (半整数レベル). 
                              ! Surface pressure (half level)
    real(DP), intent(inout):: xy_SurfH2OVapFlux(0:imax-1, 1:jmax)
                              ! 惑星表面水蒸気フラックス.
                              ! Water vapor flux at the surface
!!$    real(DP), intent(inout):: xyf_QMixFlux(0:imax-1, 1:jmax, 1:ncmax)
!!$                              ! 惑星表面比湿フラックス. 
!!$                              ! Specific humidity flux at surface

    ! 作業変数
    ! Work variables
    !
    real(DP):: xyz_DelMass(0:imax-1, 1:jmax, 1:kmax)
                              ! 
                              ! Mass in each layer
    real(DP):: xy_ConsMass(0:imax-1, 1:jmax)
                              ! 
                              ! Constituent mass in each column
    real(DP):: xy_SurfFlux(0:imax-1, 1:jmax)

    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 altitude
    integer:: n               ! 組成方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in dimension of constituents

    ! 実行文 ; Executable statement
    !

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


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

    do k = 1, kmax
      xyz_DelMass(:,:,k) = ( xyr_Press(:,:,k-1) - xyr_Press(:,:,k) ) / Grav
    end do

!!$    do n = 1, ncmax
    do n = IndexH2OVap, IndexH2OVap

      xy_ConsMass = 0.0_DP
      do k = kmax, 1, -1
        xy_ConsMass = xy_ConsMass + xyz_DelMass(:,:,k) * xyzf_QMix(:,:,k,n)
      end do

      if ( n == IndexH2OVap ) then
        xy_SurfFlux = xy_SurfH2OVapFlux
      else
!!$        xy_SurfFlux = xyf_QMixFlux(:,:,n)
      end if

      do j = 1, jmax
        do i = 0, imax-1
          if ( - xy_SurfFlux(i,j) * DelTime > xy_ConsMass(i,j) ) then
            xy_SurfFlux(i,j) = - xy_ConsMass(i,j) / DelTime !&
!!$              & * ( 1.0_DP - 1.0d-15 )
          end if
        end do
      end do

      if ( n == IndexH2OVap ) then
        xy_SurfH2OVapFlux = xy_SurfFlux
      else
!!$        xyf_QMixFlux(:,:,n) = xy_SurfFlux
      end if

    end do


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

  end subroutine SurfaceFluxUtilLimitFlux

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

  subroutine SurfaceFluxUtilInit
    !
    ! surface_flux_util モジュールの初期化を行います. 
    ! NAMELIST#surface_flux_util_nml の読み込みはこの手続きで行われます. 
    !
    ! "surface_flux_util" module is initialized. 
    ! "NAMELIST#surface_flux_util_nml" is loaded in this procedure. 
    !

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

    ! NAMELIST ファイル入力に関するユーティリティ
    ! Utilities for NAMELIST file input
    !
    use namelist_util, only: namelist_filename, NmlutilMsg, NmlutilAryValid

    ! ファイル入出力補助
    ! File I/O support
    !
    use dc_iounit, only: FileOpen

    ! 種別型パラメタ
    ! Kind type parameter
    !
    use dc_types, only: STDOUT ! 標準出力の装置番号. Unit number of standard output

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

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

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

    ! 宣言文 ; Declaration statements
    !
    implicit none

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

    ! NAMELIST 変数群
    ! NAMELIST group name
    !
!!$    namelist /surface_flux_util_nml/                                  &
!!$      & FlagConstBulkCoef
          !
          ! デフォルト値については初期化手続 "surface_flux_util#SurfaceFluxUtilInit" 
          ! のソースコードを参照のこと. 
          !
          ! Refer to source codes in the initialization procedure
          ! "surface_flux_bulk#SurfaceFluxInit" for the default values. 
          !

    ! 実行文 ; Executable statement
    !

    if ( surface_flux_util_inited ) return


    ! デフォルト値の設定
    ! Default values settings
    !

    ! 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 = surface_flux_util_nml, &  ! (out)
!!$        & iostat = iostat_nml )        ! (out)
!!$      close( unit_nml )
!!$
!!$      call NmlutilMsg( iostat_nml, module_name ) ! (in)
!!$    end if


    ! 印字 ; Print
    !
    call MessageNotify( 'M', module_name, '----- Initialization Messages -----' )

!!$    call MessageNotify( 'M', module_name, '  VelMinForRi       = %f', d = (/ VelMinForRi   /) )
    call MessageNotify( 'M', module_name, '-- version = %c', c1 = trim(version) )

    surface_flux_util_inited = .true.

  end subroutine SurfaceFluxUtilInit

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

end module surface_flux_util
