!= 負の水蒸気除去
!
!= Remove negative moisture
!
! Authors::   Yasuhiro MORIKAWA, Yukiko YAMADA
! Version::   $Id: negative_moist.f90,v 1.4 2008-11-08 15:34:40 morikawa Exp $ 
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2008. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module negative_moist
  !
  != 負の水蒸気除去
  !
  != Remove negative moisture
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  ! 負の水蒸気を除去します.
  !
  ! Remove negative moisture
  !
  !== Procedures List
  !
  ! RemoveNegMoist   :: 負の水蒸気の除去
  ! ---------------  :: ---------------
  ! RemoveNegMoist   :: Remove negative moisture
  !
  !--
  !== NAMELIST
  !
  ! NAMELIST#negative_moist_nml
  !++

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

  ! 格子点設定
  ! Grid points settings
  !
  use gridset, only: imax, & ! 経度格子点数. 
                             ! Number of grid points in longitude
    &                jmax, & ! 緯度格子点数. 
                             ! Number of grid points in latitude
    &                kmax    ! 鉛直層数. 
                             ! Number of vertical level

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

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

  ! 宣言文 ; Declaration statements
  !
  implicit none
  private

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

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


  ! 非公開変数
  ! Private variables
  !

  character(*), parameter:: module_name = 'negative_moist'
                              ! モジュールの名称. 
                              ! Module name
  character(*), parameter:: version = &
    & '$Name:  $' // &
    & '$Id: negative_moist.f90,v 1.4 2008-11-08 15:34:40 morikawa Exp $'
                              ! モジュールのバージョン
                              ! Module version

  ! INTERFACE 文 ; INTERFACE statements
  !
  interface RemoveNegMoist
    module procedure RemoveNegMoist
  end interface

contains

  subroutine RemoveNegMoist( &
    & xyz_QVap, xyz_DNegQVapDt, & ! (inout)
    & xyr_Press &                 ! (in)
    & )
    !
    ! *xyz_QVap* の負の値を除去します. 
    ! *xyz_DNegQVapDt* には *xyz_QVap* の変化量が返ります. 
    ! *xyz_DNegQVapDt* は入出力引数なので, 変化量は入力値に
    ! 上乗せされて返ります. 入力された値は *xyz_QVap* の変化量に
    ! 影響を及ぼしません. 
    !
    ! Remove negative values in *xyz_QVap*. 
    ! Variation of *xyz_QVap* is returned to *xyz_DNegQVapDt*. 
    ! So *xyz_DNegQVapDt* is input/output argument, variation is 
    ! added on input values. Input values do not have influence on
    ! variation of *xyz_QVap*. 
    !

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

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

    ! 時刻管理
    ! Time control
    !
    use timeset, only: DelTime, &  ! $ \Delta t $
      & TimesetClockStart, TimesetClockStop

    ! 宣言文 ; Declaration statements
    !
    implicit none
    real(DP), intent(inout):: xyz_QVap (0:imax-1, 1:jmax, 1:kmax)
                              ! $ q $ .     比湿. Specific humidity
    real(DP), intent(inout):: xyz_DNegQVapDt (0:imax-1, 1:jmax, 1:kmax)
                              ! $ \DP{q}{t} $ .  比湿補正率. 
                              ! Specific humidity correction
    real(DP), intent(in):: xyr_Press  (0:imax-1, 1:jmax, 0:kmax)
                              ! $ \hat{p} $ . 気圧 (半整数レベル). 
                              ! Air pressure (half level)

    ! 作業変数
    ! Work variables
    !
    real(DP):: xyz_QVapB (0:imax-1, 1:jmax, 1:kmax)
                              ! 調節前の比湿. 
                              ! Specific humidity before adjust. 
    real(DP):: xy_QVapW (0:imax-1, 1:jmax)
                              ! 比湿 (作業変数). 
                              ! Specific humidity (work variable). 

    real(DP):: xyz_DPressDz (0:imax-1, 1:jmax, 1:kmax)
                              ! $ \Delta p $
                              ! 
    real(DP):: xyz_QVapDPressDz (0:imax-1, 1:jmax, 1:kmax)
                              ! $ q \Delta p $
                              ! 
    real(DP):: xyz_DelQVapDPressDz (0:imax-1, 1:jmax, 1:kmax)
                              ! $ \Delta q \Delta p $
                              ! 
    real(DP):: QVapDPressDzAvrXYZ
                              ! $ \int<q \Delta p>dz $
                              ! 
    real(DP):: DelQVapDPressDzAvrXYZ
                              ! $ \int<\Delta q \Delta p>dz $
                              ! 

    integer:: k               ! 鉛直方向に回る DO ループ用作業変数
                              ! Work variables for DO loop in vertical direction

    ! 実行文 ; Executable statement
    !

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

    ! 初期化
    ! Initialization
    !
    if ( .not. negative_moist_inited ) call NegMoistInit

    ! 調節前の比湿の保存
    ! Save specific humidity before adjust
    !
    xyz_QVapB = xyz_QVap

    ! $ \Delta p $ の計算
    ! Calculate $ \Delta p $
    !
    do k = 1, kmax
      xyz_DPressDz(:,:,k) = xyr_Press(:,:,k-1) - xyr_Press(:,:,k)
    end do

    ! 局所での補正 (負の値を最下層へ)
    ! Correction at local (Negative values moved to botton layer)
    !
    xy_QVapW = 0.0_DP
    do k = kmax, 2, -1
      where ( xyz_QVap(:,:,k) < 0.0_DP )
        xy_QVapW = - xyz_QVap(:,:,k) &
          &          * xyz_DPressDz(:,:,k) / xyz_DPressDz(:,:,k-1)
        xyz_QVap(:,:,k) = 0.0_DP
        xyz_QVap(:,:,k-1) = xyz_QVap(:,:,k-1) - xy_QVapW
      end where
    end do

    ! 全球での補正
    ! Correction in global
    !

    ! 各層における補正量の算出
    ! Calculate amount of correction in each layer
    !
    xyz_QVapDPressDz = xyz_QVap * xyz_DPressDz
    where ( xyz_QVapDPressDz < 0.0_DP )
      xyz_DelQVapDPressDz = - xyz_QVapDPressDz
    elsewhere
      xyz_DelQVapDPressDz = 0.0_DP
    end where

    if ( all( xyz_QVapDPressDz < 0.0_DP ) ) then
      call MessageNotify( 'E', module_name, &
        & 'negative moisture is too much, so it can not be removed.' )
    end if

    ! 補正量の東西南北鉛直平均
    ! Zonal and meridional and vertical mean of amount of correction
    !
    QVapDPressDzAvrXYZ = 0.0_DP
    DelQVapDPressDzAvrXYZ = 0.0_DP

    do k = 1, kmax
      QVapDPressDzAvrXYZ = &
        &   QVapDPressDzAvrXYZ  &
        & + AvrLonLat_xy( xyz_QVapDPressDz(:,:,k) )

      DelQVapDPressDzAvrXYZ = &
        &   DelQVapDPressDzAvrXYZ  &
        & + AvrLonLat_xy( xyz_DelQVapDPressDz(:,:,k) )
    end do

    ! 負値をゼロとし, その分全体を引き下げる. 
    ! Minus values are brought back to zero, 
    !   and total is reduced by just that much
    !
    if ( QVapDPressDzAvrXYZ /= 0.0_DP ) then 
      xyz_QVap = &
        &   QVapDPressDzAvrXYZ &
        &   / ( QVapDPressDzAvrXYZ + DelQVapDPressDzAvrXYZ ) &
        &   * max( xyz_QVap, 0.0_DP )
    end if

    if ( any( xyz_QVap < 0.0_DP ) ) then
      call MessageNotify( 'E', module_name, &
        & 'negative moisture is too much, so it can not be removed.' )
    end if

    ! 比湿変化の算出
    ! Calculate specific humidity variance
    !
    xyz_DNegQVapDt = &
      &   xyz_DNegQVapDt + ( xyz_QVap - xyz_QVapB ) / ( 2.0_DP * DelTime )

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

  end subroutine RemoveNegMoist

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

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

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

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

    ! ファイル入出力補助
    ! 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

    ! 宣言文 ; 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 /negative_moist_nml/
          !
          ! デフォルト値については初期化手続 "negative_moist#NegMoistInit" 
          ! のソースコードを参照のこと. 
          !
          ! Refer to source codes in the initialization procedure
          ! "negative_moist#NegMoistInit" for the default values. 
          !

    ! 実行文 ; Executable statement
    !

    if ( negative_moist_inited ) return
    call InitCheck

    ! デフォルト値の設定
    ! 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 = negative_moist_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, '-- version = %c', c1 = trim(version) )

    negative_moist_inited = .true.
  end subroutine NegMoistInit

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

  subroutine InitCheck
    !
    ! 依存モジュールの初期化チェック
    !
    ! Check initialization of dependency modules

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

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

    ! 格子点設定
    ! Grid points settings
    !
    use gridset, only: gridset_inited

    ! 物理定数設定
    ! Physical constants settings
    !
    use constants, only: constants_inited

    ! 座標データ設定
    ! Axes data settings
    !
    use axesset, only: axesset_inited

    ! 時刻管理
    ! Time control
    !
    use timeset, only: timeset_inited

    ! 実行文 ; Executable statement
    !

    if ( .not. namelist_util_inited ) &
      & call MessageNotify( 'E', module_name, '"namelist_util" module is not initialized.' )

    if ( .not. gridset_inited ) &
      & call MessageNotify( 'E', module_name, '"gridset" module is not initialized.' )

    if ( .not. constants_inited ) &
      & call MessageNotify( 'E', module_name, '"constants" module is not initialized.' )

    if ( .not. axesset_inited ) &
      & call MessageNotify( 'E', module_name, '"axesset" module is not initialized.' )

    if ( .not. timeset_inited ) &
      & call MessageNotify( 'E', module_name, '"timeset" module is not initialized.' )

  end subroutine InitCheck

end module negative_moist
