!= Program ArareAnal
!
! Authors::   SUGIYAMA Ko-ichiro, ODAKA Masatsugu
! Version::   $Id: arare-analysis.f90,v 1.4 2011-02-28 11:39:32 sugiyama Exp $
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2006. All rights reserved.
! License::   See COPYRIGHT[link:../../COPYRIGHT]
!
!== Overview 
!
! 非静力学モデル deepconv/arare 2 次データ作成プログラム
!
!
program ArareAnal

  !----- モジュール読み込み ------

  !-----   型宣言, 文字列処理   ----
  use dc_types,       only : STRING
  use dc_string,      only : StoA

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

  !  コマンドライン引数解釈
  use argset,        only : argset_init  

  !-----    管理モジュール   -----
  !  化学量計算モジュール
  use chemcalc, only: chemcalc_init, xz_SvapPress, xz_LatentHeat, ReactHeatNH4SH
  use chemdata, only: chemdata_init

  !  入出力ファイル名管理モジュール
  use fileset,       only : fileset_init

  !  デバッグ出力管理モジュール
  use debugset,      only : debugset_init

  !  時間管理モジュール
  use timeset,       only : timeset_init, TimeDisp, TImeInt

  !  格子点管理モジュール 
  use gridset,       only : gridset_init, DelX, DelZ, &
    &                       DimXMin, DimXMax, DimZMin, DimZMax, SpcNum, &
    &                       RegXMax, RegZMax, RegXMin, RegZMin

  !  基本場設定モジュール
  use basicset,      only : basicset_init, SpcWetSymbol, &
    &                       MolWtDry, MolWtWet, CpDry, PressBasis, GasRDry,    &
    &                       SpcWetID, SpcWetMolfr, xz_DensBasicZ,    &
    &                       xza_MixRtBasicZ, xz_PotTempBasicZ, xz_ExnerBasicZ, &
    &                       xz_TempBasicZ, xz_PressBasicZ, Grav, xz_EffMolWtBasicZ

  !  湿潤ルーチン設定モジュール
  use moistset,      only: moistset_init,   &
    &                      GasNum, CloudNum, RainNum, CondNum, RactNum, &
    &                      IdxG,   IdxC,   IdxR,                        &
    &                      IdxCG,  IdxCC,  IdxCR,                       &
    &                      IdxNH3, IdxH2S, IdxNH4SHc, IdxNH4SHr         

  use ChemCalc, only: xz_LatentHeat,    &!潜熱
    &                 ReactHeatNH4SH     !NH4SH の反応熱

  !  積算値管理モジュール
  use StorePotTemp,      only : StorePotTemp_init
  use StoreMixRt,        only : StoreMixRt_init
  use StoreBuoy,         only : StoreBuoy_init
  use StoreStab,         only : StoreStab_init

  !-----    下請けモジュール   -----
  !微分平均演算
  use average

  !  断熱上昇気塊の温度減率計算用モジュール
  use ECCM,         only : eccm_molfr, eccm_stab, eccm_wet2
  
  ! 境界条件
  use boundary,      only : BoundaryXCyc_xz, BoundaryZSym_xz

  !  湿潤気塊の浮力計算用モジュール
  use MoistBuoyancy,only : MoistBuoy_Init, xr_BuoyMolWt, xr_BuoyDrag
  use DynFunc,       only : xr_Buoy
  
  use average, only:  xz_avr_xr
  use differentiate_center2, only: xr_dz_xz

  !暗黙の型宣言禁止
  implicit none
  
  !変数定義
  real(8), allocatable :: xz_TempMoist(:,:)
  real(8), allocatable :: xz_PressMoist(:,:)
  real(8), allocatable :: xza_MolFrMoist(:,:,:)

  real(8), allocatable :: xz_PotTemp(:,:)
  real(8), allocatable :: xz_PotTempAll(:,:)
  real(8), allocatable :: xz_VTempAll(:,:)
  real(8), allocatable :: xz_Exner(:,:)
  real(8), allocatable :: pz_VelX(:,:)
  real(8), allocatable :: xr_VelZ(:,:)
  real(8), allocatable :: xza_MixRt(:,:,:)
  real(8), allocatable :: xza_MixRtAll(:,:,:)
  real(8), allocatable :: xza_MixRtAll2(:,:,:)
  real(8), allocatable :: xza_MixRtSat(:,:,:)
  real(8), allocatable :: xza_MixRtEq(:,:,:)
  real(8), allocatable :: xza_MixRtMoist(:,:,:)
  real(8), allocatable :: xza_Humidity(:,:,:)
  real(8), allocatable :: za_MolFrEq(:,:)
  real(8), allocatable :: xz_VPotTempAll(:,:)
  real(8), allocatable :: xz_EqPotTempAll(:,:)
  real(8), allocatable :: xz_Dens(:,:)
  real(8)              :: AnalTime
  real(8)              :: Hum

  real(8), allocatable :: xz_TempAll(:,:)
  real(8), allocatable :: xz_PressAll(:,:)
  real(8), allocatable :: xz_EffMolWt(:,:)
  real(8), allocatable :: xz_EffMolWtMoist(:,:)
  real(8), allocatable :: xza_MixRtDivMolWt(:,:,:)
  real(8), allocatable :: xza_LatentHeat(:,:,:)

  real(8), allocatable :: xz_EqConst(:,:)
  real(8), allocatable :: xz_EqConstSat(:,:)

  real(8), allocatable :: xza_MolFrAll(:,:,:)
  real(8), allocatable :: xz_MolWtWet(:,:)
  real(8), allocatable :: xz_MolWtMoist(:,:)
  real(8), allocatable :: xz_Stab(:,:)
  real(8), allocatable :: xz_StabTemp(:,:)
  real(8), allocatable :: xz_StabMolWt(:,:)
  real(8), allocatable :: xz_StabMoist(:,:)
  real(8), allocatable :: xz_StabTempMoist(:,:)
  real(8), allocatable :: xz_StabMolWtMoist(:,:)

  real(8), allocatable :: xz_StrmFunc(:,:)
  real(8), allocatable :: pq_StrmFunc(:,:)
  real(8), allocatable :: xr_Dens(:,:)
  real(8), allocatable :: pz_Dens(:,:)
  real(8), allocatable :: MolFrIni(:)

!  real(8), allocatable :: xza_CloudDens(:,:,:)
!  real(8), allocatable :: xz_CloudDens(:,:)
  real(8), allocatable :: xz_CloudMixRtEq(:,:)
  real(8), allocatable :: xza_CloudMixRtEq(:,:,:)
  real(8), allocatable :: xz_CloudMixRtMoist(:,:)
  real(8), allocatable :: xza_CloudMixRtMoist(:,:,:)

  real(8)              :: Humidity
  integer              :: t, s, i, k, tt, step
  integer              :: Idx
  character(100)       :: cfgfile


  !コマンドライン引数の解釈
  !  NAMELIST ファイル名の読み込み
  call argset_init(cfgfile)

  !物質特性の初期化
  call chemdata_init()

  !時刻に関する設定の初期化
  !  NAMELIST から必要な情報を読み取り, 時間関連の変数の設定を行う. 
  call timeset_init(cfgfile)

  !格子点情報の初期化
  !  NAMELIST から情報を得て, 格子点を計算する
  call gridset_init(cfgfile)

  !化学計算ルーチンの初期化
  call chemcalc_init()

  !基本場の情報の初期化
  !  NAMELIST から情報を得て, 基本場を設定する.
  call basicset_init(cfgfile)

  !I/O ファイル名の初期化
  !  NAMELIST ファイル名を指定し, deepconv/arare の
  !  出力ファイル名を NAMELIST から得る
  call fileset_init(cfgfile)

  !基本場の取得
  call AnalFile_BasicZ_Get( )

  !湿潤ルーチンの共有変数の初期化
  call moistset_init()

  !積算値を保管するためのモジュールの初期化
  !  NAMELIST から情報を得て, 基本場を設定する.
  call StorePotTemp_init( )
  call StoreMixRt_init( )
  call StoreBuoy_init( )  
  call StoreStab_init( )  

  !内部変数の初期化. とりあえずゼロを入れて値を確定させておく. 
  call ArareAlloc

  !分子量に対する浮力計算ルーチンの初期化
  call MoistBuoy_Init()             

  write(*,*) "OK1"
  
  !NetCDF ファイルの作成と基本場の取得  
  call AnalFile_Open( )
    

  write(*,*) "OK0"

  !----------------------------------------------------------------------
  ! 基本場の温度・圧力に対して湿度 100 % の時の混合比を求める
  ! 基本場の物質量は時間変化しないので, この位置で計算. 
  ! 全ての時刻に対して同じ値が入ることになる. 
  !----------------------------------------------------------------------
  Hum = 1.0d0
  do i = DimXMin, DimXMax
     call ECCM_MolFr( SpcWetMolFr(1:SpcNum), Hum, xz_TempBasicZ(i,:), &
          &              xz_PressBasicZ(i,:), za_MolFrEq )
  end do
  do i = DimXMin, DimXMax
     do s = 1, SpcNum
        xza_MixRtEq(i,:,s) = za_MolFrEq(:,s) * MolWtWet(s) / MolWtDry
     end do
  end do

  write(*,*) "*** s, MolWtWet(s) ***"
  do s = 1, GasNum
     write(*,*) s, MolWtWet(s)
  end do
  
  xz_CloudMixRtEq = 0.0d0
  do k = RegZMin, RegZMax
     do s = 1, GasNum
        xza_CloudMixRtEq(:,k,s) = xza_MixRtEq(:,k-1,s)  - xza_MixRtEq(:,k,s)
        xz_CloudMixRtEq(:,k) = xz_CloudMixRtEq(:,k) + xza_CloudMixRtEq(:,k,s) 
     end do
  end do
! WL1973 的な計算方法. 
!  do k = RegZMin, RegZMax
!     do s = 1, GasNum
!        xza_CloudDens(:,k,s) = (xza_MixRtEq(:,k-1,s)  - xza_MixRtEq(:,k,s)) * xz_PressBasicZ(:,k) / ( DelZ * Grav)
!        xz_CloudDens(:,k)    = xz_CloudDens(:,k) + xza_CloudDens(:,k,s)
!     end do
!       xz_CloudMixRt(:,k) = xz_CloudDens(:,k) / xz_DensBasicZ(:,k) ! 比湿だけど
!  end do

  ! 湿潤断熱線の計算
  Hum = 1.0d0
  Idx = RegZMin
  ! 初期値の用意
  xz_TempMoist   = xz_TempBasicZ
  xz_PressMoist  = xz_PressBasicZ
  do i = DimXMin, DimXMax
     xza_MolFrMoist(i,:,:) = za_MolFrEq(:,:)
  end do
  do i = DimXMin, DimXMax
     call ECCM_Wet2(Idx, Hum, xz_TempMoist(i,:), xz_PressMoist(i,:), xza_MolFrMoist(i,:,:))
  end do
  do i = DimXMin, DimXMax
     do k = DimZMin, DimZMax
        do s = 1, SpcNum
           xza_MixRtMoist(i,k,s) = xza_MolFrMoist(i,k,s) * MolWtWet(s) / MolWtDry
        end do
     end do
  end do
  do k = DimZMin, DimZMax
     do i = DimXMin, DimXMax
        xz_MolWtMoist(i,k) = dot_product( MolWtWet(1:GasNum), xza_MolFrMoist(i,k,1:GasNum) )
     end do
  end do
  
  xz_StabTempMoist =                                           &
       &         Grav / xz_TempMoist                           &
       &           * (   xz_avr_xr( xr_dz_xz( xz_TempMoist) )  &
       &               + Grav / CpDry ) 
  xz_StabMolWtMoist =                                          &
       &       - Grav * xz_avr_xr( xr_dz_xz( xz_MolWtMoist ) ) &
       &         /  MolWtDry
  xz_StabMoist = xz_StabTempMoist + xz_StabMolWtMoist
  
  xz_CloudMixRtMoist = 0.0d0
  do k = RegZMin, RegZMax
     do s = 1, GasNum
        xza_CloudMixRtMoist(:,k,s) = xza_MixRtMoist(:,k-1,s)  - xza_MixRtMoist(:,k,s)
        xz_CloudMixRtMoist(:,k) = xz_CloudMixRtMoist(:,k) + xza_CloudMixRtMoist(:,k,s) 
     end do
  end do  

  !----------------------------------------------------------------------
  ! 解析値の計算開始
  !   時刻を進めながら, ファイルの値を得る
  !   適宜データを間引く (最初のデータは出力しない, 最大で 500 ステップ分). 
  !----------------------------------------------------------------------
!  do t = 1, int( TimeInt / TimeDisp ) + 1
  step = int( TimeInt / TimeDisp )
!!  STEPS: do while (step >= 500)
!!   write(*,*) step
!!   if (mod(step, 2) == 1) then 
!!       exit STEPS
!!    end if
!!    step = step / 2 
!!  end do STEPS
  write(*,*) "**** STEPS ***** ", int( TimeInt / TimeDisp ), " ==> ", step

  TIMESTEP: do tt = 0, int( TimeInt / TimeDisp) -1
     if ( mod(tt, int(TimeInt / TimeDisp / step)) /= 0 ) then 
        cycle TIMESTEP
     end if
     t = tt + 1
    
    !----------------------------------------------------------------
    ! ヒストリファイルを開き値を得る. 
    !----------------------------------------------------------------
    call AnalFile_Get(                                           &
      &       t,  AnalTime,                                      &
      &       xz_PotTemp, xz_Exner, pz_VelX, xr_VelZ, xza_MixRt )
    write(*,*) t, AnalTime    
  
    !----------------------------------------------------------------
    ! 初期化
    !----------------------------------------------------------------
    xza_MixRtAll = xza_MixRt + xza_MixRtBasicZ

    !----------------------------------------------------------------
    ! 温度・圧力の計算
    !----------------------------------------------------------------
    xz_PressAll = &
      & PressBasis * ((xz_Exner + xz_ExnerBasicZ ) ** (CpDry / GasRDry))
    
    xz_PotTempAll  = xz_PotTemp + xz_PotTempBasicZ
    xz_TempAll = ( xz_Exner + xz_ExnerBasicZ ) * xz_PotTempAll

    !----------------------------------------------------------------
    ! 密度, 仮温位の計算
    !----------------------------------------------------------------
    xza_MixRtDivMolWt = 0.0d0
    do s = 1, GasNum
      xza_MixRtDivMolWt(:,:,IdxG(s)) = xza_MixRtAll(:,:,IdxG(s)) / MolWtWet(IdxG(s))
    end do

    xz_EffMolWt = &
      & (1.0d0 + sum(xza_MixRtAll,3)) &
      & / (MolWtDry * ((1.0d0 / MolWtDry) + sum(xza_MixRtDivMolWt,3))) 

    xz_Dens = xz_PressAll * xz_EffMolWt / (GasRDry * xz_TempAll)
    xz_VPotTempAll = xz_PotTempAll / xz_EffMolWt
    xz_VTempAll = xz_TempAll / xz_EffMolWt

    !----------------------------------------------------------------
    ! 流線関数
    !----------------------------------------------------------------
    xr_Dens = xr_avr_xz( xz_Dens )
    pz_Dens = pz_avr_xz( xz_Dens )
    pq_StrmFunc = 0.0d0
    xz_StrmFunc = 0.0d0

    do i = RegXMax, DimXMin+1, -1    
      pq_StrmFunc(i-1,:) = pq_StrmFunc(i,:) - DelX * xr_Dens(i,:) * xr_VelZ(i,:)
    end do
    do k = RegZMax, DimZMin+1, -1
      pq_StrmFunc(:,k-1) = pq_StrmFunc(:,k) + DelZ * pz_Dens(:,k) * pz_VelX(:,k)
    end do

    xz_StrmFunc = pq_StrmFunc 
    xz_StrmFunc(DimXMin+1 : DimXMax, DimZMin+1 : DimZMax) =           &
      &  (                                                            &
      &     pq_StrmFunc(DimXMin   : DimXMax-1, DimZMin   : DimZMax-1) &
      &   + pq_StrmFunc(DimXMin+1 : DimXMax,   DimZMin   : DimZMax-1) &
      &   + pq_StrmFunc(DimXMin   : DimXMax-1, DimZMin+1 : DimZMax)   &
      &   + pq_StrmFunc(DimXMin+1 : DimXMax,   DimZMin+1 : DimZMax)   &
      &   ) * 2.5d-1

    call BoundaryXCyc_xz( xz_StrmFunc )
    call BoundaryZSym_xz( xz_StrmFunc )

    where (xz_StrmFunc < 1.0d-20 .AND. xz_StrmFunc > - 1.0d-20) 
      xz_StrmFunc = 1.0d-20
    end where

    !----------------------------------------------------------------
    ! 飽和蒸気圧と平衡定数
    !----------------------------------------------------------------
    do s = 1, CondNum
      !飽和蒸気圧
      xza_MixRtSat(:,:,IdxCG(s)) =                        &
        & xz_SvapPress(SpcWetID(IdxCC(s)), xz_TempAll)    &
        &  * MolWtWet(IdxCC(s))                           &
        &  / (MolWtDry * xz_PressAll)                     

      !相対湿度
      xza_Humidity(:,:,IdxCG(s)) =                        &
        & xza_MixRtAll(:,:,IdxCG(s)) / xza_MixRtSat(:,:,IdxCG(s)) * 100.0d0
    end do
    
    !平衡定数
    if ( IdxNH3 /= 0 ) then     
      xz_EqConstSat = 61.781d0 - 10834.0d0 / xz_TempAll - dlog(1.0d2)
      
      xz_EqConst =                                        &
        & dlog(                                           &
        &   ( xz_PressAll ** 2.0d0 )                      &
        &   * max( xza_MixRtAll(:,:,IdxNH3), 1.0d-20 )    &
        &   * max( xza_MixRtAll(:,:,IdxH2S), 1.0d-20 )    &
        &   * ( MolWtDry ** 2.0d0)                        &
        &   / ( MolWtWet(IdxNH3) )                        &
        &   / ( MolWtWet(IdxH2S) )                        &
        & )
    end if


    !----------------------------------------------------------------
    ! 相当温位
    !----------------------------------------------------------------
    ! 空気塊を断熱上昇させた時に実現する温度・物質分布を求める. 
!    MolFrIni = SpcWetMolFr(1:SpcNum) 
!    Humidity = 1.0
!    call ECCM_Wet( MolFrIni, Humidity, z_Temp, z_Press, z_MolWtMean, za_MolFr )
    
!    xz_EqPotTempAll = xz_PotTempAll * dexp( xz_LatentHeat * xz_MixRt / (CpDry * xz_TempAll))    
!    xa_SatEqPotTempAll = xz_PotTempAll * dexp( xz_LatentHeat * xz_MixRt / (CpDry * xz_TempAll))

    !----------------------------------------------------------------
    ! 安定度
    !----------------------------------------------------------------
    do s = 1, SpcNum
      xza_MolFrAll(:,:,s) = xza_MixRtAll(:,:,s) * MolWtDry / MolWtWet(s) 
    end do
    
    do k = DimZMin, DimZMax
      do i = DimXMin, DimXMax
        xz_MolWtWet(i,k) = dot_product( MolWtWet(1:GasNum), xza_MolFrAll(i,k,1:GasNum) )
      end do
    end do
    
    xz_StabTemp =                                           &
      &         Grav / xz_TempAll                           &
      &           * (   xz_avr_xr( xr_dz_xz( xz_TempAll ) ) &
      &               + Grav / CpDry ) 
    xz_StabMolWt =                                          &
      &       - Grav * xz_avr_xr( xr_dz_xz( xz_MolWtWet ) ) &
      &         /  MolWtDry    
    xz_Stab = xz_StabTemp + xz_StabMolWt

    where (xz_Stab < 1.0d-7) 
      xz_Stab = 1.0d-7
    end where
    

    !----------------------------------------------------------------    
    ! ファイル出力
    !----------------------------------------------------------------
    call AnalFile_OutPut( AnalTime )    

 end do TIMESTEP
 
    
  !----------------------------------------------------------------    
  ! ファイルを閉じる
  !----------------------------------------------------------------    
  call AnalFile_Close
 
contains
  
  subroutine AnalFile_Open( )
    !
    !解析ファイルの定義
    !
    use gtool_history, only: HistoryCreate, HistoryPut, HistoryAddVariable
    use fileset, only: exptitle, expsrc, expinst, HistoryFilePrefix    
    use gridset, only: FileNX, FileNZ, s_X, s_Z, &
      &                FileXMin, FileXMax, FileZMin, FileZMax, SpcNum
    use basicset, only: SpcWetSymbol
    
    !暗黙の型宣言禁止
    implicit none

    !変数定義
    character(150)  :: File
    integer        :: s
    
    File = trim(HistoryFilePrefix)// '_Analysis.nc'

    write(*,*) "A" 

    !-----------------------------------------------------------
    ! ヒストリー作成
    !-----------------------------------------------------------
    call HistoryCreate(                              &
      & file = trim(File),                           &
      & title = exptitle,                            &
      & source = expsrc,                             &
      & institution = expinst,                       &
      & dims=(/'x','z','t'/),                        &
      & dimsizes=(/FileNX, FileNZ, 0/),              &
      & longnames=(/'X-coordinate',                  &
      &             'Z-coordinate',                  &
      &             'Time        '/),                &
      & units=(/'m','m','s'/), origin=0.0,           &
      & interval=0.0)

    write(*,*) "B" 

    !-----------------------------------------------------------  
    ! 軸の出力
    !-----------------------------------------------------------
    call HistoryPut('x', s_X( FileXMin: FileXMax ))

    write(*,*) "C" 

    call HistoryPut('z', s_Z( FileZMin: FileZMax ))

    write(*,*) "D" 

    !-----------------------------------------------------------  
    ! 解析用の変数の出力
    !-----------------------------------------------------------  
    !温度
    call HistoryAddVariable(                          &
      & varname='TempAll', dims=(/'x','z','t'/),      &
      & longname='temperature',                       &
      & units='K', xtype='double' )

    !仮温位
    call HistoryAddVariable(                         &
      & varname='VTempAll', dims=(/'x','z','t'/),    &
      & longname='virtual temperature',              &
      & units='K', xtype='double')

    !温位
    call HistoryAddVariable(                         &
      & varname='PotTempAll', dims=(/'x','z','t'/),  &
      & longname='potential temperature',            &
      & units='K', xtype='double' )

    !仮温位
    call HistoryAddVariable(                         &
      & varname='VPotTempAll', dims=(/'x','z','t'/), &
      & longname='virtual potential temperature',    &
      & units='K', xtype='double')

    !圧力
    call HistoryAddVariable(                          &
      & varname='PressAll', dims=(/'x','z','t'/),     &
      & longname='Pressure',                          &
      & units='Pa', xtype='double' )
    
    !密度
    call HistoryAddVariable(                          &
      & varname='Dens', dims=(/'x','z','t'/),         &
      & longname='Density',                           &
      & units='kg/m/m"', xtype='double' )

    !静的安定度
    call HistoryAddVariable(                          &
      & varname='Stab', dims=(/'x','z','t'/),         &
      & longname='Stability',                         &
      & units='1/s/s"', xtype='double' )

    write(*,*) "J" 

    !静的安定度
    call HistoryAddVariable(                          &
      & varname='StabTemp', dims=(/'x','z','t'/),     &
      & longname='Stability (Temp)',                  &
      & units='1/s/s"', xtype='double' )

    !静的安定度
    call HistoryAddVariable(                          &
      & varname='StabMolWt', dims=(/'x','z','t'/),    &
      & longname='Stability (MolWt)',                 &
      & units='1/s/s"', xtype='double' )

    !静的安定度
    call HistoryAddVariable(                          &
      & varname='StabMoist', dims=(/'x','z','t'/),         &
      & longname='Stability',                         &
      & units='1/s/s"', xtype='double' )

    !静的安定度
    call HistoryAddVariable(                          &
      & varname='StabTempMoist', dims=(/'x','z','t'/),     &
      & longname='Stability (Temp)',                  &
      & units='1/s/s"', xtype='double' )

    write(*,*) "I" 

    !静的安定度
    call HistoryAddVariable(                          &
      & varname='StabMolWtMoist', dims=(/'x','z','t'/),    &
      & longname='Stability (MolWt)',                 &
      & units='1/s/s"', xtype='double' )

    ! NH4SH の圧平衡定数 (飽和)
    call HistoryAddVariable(                          &
      & varname='EqConstSat',                         &
      & dims=(/'x','z','t'/),                         &
      & longname='Saturated Equilibrium Constant',    &
      & units='1', xtype='double' )

    ! NH4SH の圧平衡定数 
    call HistoryAddVariable(                          &
      & varname='EqConst',                            &
      & dims=(/'x','z','t'/),                         &
      & longname='Equibrium Constant',      &
      & units='1', xtype='double' )

    write(*,*) "H" 

    !流線関数 
    call HistoryAddVariable(                              &
      & varname='StrmFunc', dims=(/'x','z','t'/),         &
      & longname='Stream Function',                       &
      & units='kg/m/m', xtype='double')

    !雲密度
    call HistoryAddVariable(                              &
      & varname='CloudMixRtMoist', dims=(/'x','z','t'/),         &
      & longname='Cloud Density',                       &
      & units='kg/m/m', xtype='double')

    call HistoryAddVariable(                              &
      & varname='CloudMixRtEq', dims=(/'x','z','t'/),         &
      & longname='Cloud Mixing ratio',                       &
      & units='kg/m/m', xtype='double')

    do s = 1, SpcNum
      !熱平衡状態での混合比
      call HistoryAddVariable(                               &
        & varname='D'//trim(SpcWetSymbol(s))//'DtAll',             &
        & dims=(/'x','z', 't'/),                             &
        & longname= trim(SpcWetSymbol(s))//' Mixing Ratio',  &
        & units='kg/kg', xtype='double')
    end do
    
    do s = 1, GasNum
      !熱平衡状態での混合比
      call HistoryAddVariable(                                    &
        & varname='D'//trim(SpcWetSymbol(IdxG(s)))//'DtEq',             &
        & dims=(/'x','z', 't'/),                                       &
        & longname='Equilibrium '//trim(SpcWetSymbol(IdxG(s)))//' Mixing Ratio',&
        & units='kg/kg', xtype='double' )
    end do

    write(*,*) "G" 

    do s = 1, CondNum
      !飽和混合比
      call HistoryAddVariable(                          &
        & varname='D'//trim(SpcWetSymbol(IdxCG(s))) // '_Sat',      &
        & dims=(/'x','z','t'/),                         &
        & longname='Saturated vapor pressure',          &
        & units='kg/kg', xtype='double')
      
      !相対湿度
      call HistoryAddVariable(                          &
        & varname='D'//trim(SpcWetSymbol(IdxCG(s))) // '_Hum',      &
        & dims=(/'x','z','t'/),                         &
        & longname='Humidity',                          &
        & units='%', xtype='double')
   end do

    write(*,*) "F" 

   do s = 1, GasNum
      !雲量
      call HistoryAddVariable(                          &
        & varname='D'//trim(SpcWetSymbol(s)) // '_MixRtMoist',      &
        & dims=(/'x','z','t'/),                         &
        & longname='Cloud mixing ratio',                &
        & units='kg/kg', xtype='double')
    end do

    write(*,*) "E" 
    
  end subroutine AnalFile_Open


  subroutine AnalFile_Close( )
    !
    !解析ファイルのクローズ
    !
    use gtool_history, only: HistoryClose

    call HistoryClose
    
  end subroutine AnalFile_Close
  
  
  subroutine AnalFile_OutPut( Time )

    use gtool_history, only: HistoryPut
    use gridset, only: FileXMin, FileXMax, FileZMin, FileZMax

    !暗黙の型宣言禁止
    implicit none
    
    !変数定義
    real(8), intent(in) :: Time    
 
    !----------------------------------------------------------------
    ! 値を出力
    !----------------------------------------------------------------
    call HistoryPut( 't', Time )

    call HistoryPut( 'TempAll',       &
      &            xz_TempAll(FileXMin:FileXMax, FileZMin:FileZMax) )

    call HistoryPut( 'VTempAll',       &
      &            xz_VTempAll(FileXMin:FileXMax, FileZMin:FileZMax) )
    
    call HistoryPut( 'PotTempAll',    &
      &            xz_PotTempAll(FileXMin:FileXMax, FileZMin:FileZMax))
   
    call HistoryPut( 'VPotTempAll',   &
      &            xz_VPotTempAll(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'PressAll',      &
      &            xz_PressAll(FileXMin:FileXMax, FileZMin:FileZMax))
    
    call HistoryPut( 'Stab',          &
      &            xz_Stab(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'StabTemp',          &
      &            xz_StabTemp(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'StabMolWt',          &
      &            xz_StabMolWt(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'StabMoist',          &
      &            xz_StabMoist(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'StabTempMoist',          &
      &            xz_StabTempMoist(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'StabMolWtMoist',          &
      &            xz_StabMolWtMoist(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'Dens',          &
      &            xz_Dens(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut(  'EqConstSat',   &
      & xz_EqConstSat(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'EqConst',       &
      & xz_EqConst(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'StrmFunc',      &
      &            xz_StrmFunc(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'CloudMixRtEq',      &
      &            xz_CloudMixRtEq(FileXMin:FileXMax, FileZMin:FileZMax))

    call HistoryPut( 'CloudMixRtMoist',      &
      &            xz_CloudMixRtMoist(FileXMin:FileXMax, FileZMin:FileZMax))

    do s = 1, SpcNum
      call HistoryPut( trim(SpcWetSymbol(s))//'DtAll',  &
        &           xza_MixRtAll(FileXMin:FileXMax, FileZMin:FileZMax, s))
    end do

    do s = 1, GasNum
      call HistoryPut( trim(SpcWetSymbol(IdxG(s)))//'DtEq',  &
        &           xza_MixRtEq(FileXMin:FileXMax, FileZMin:FileZMax, IdxG(s)))
    end do

    do s = 1, CondNum
      call HistoryPut(     &
        & trim(SpcWetSymbol(IdxCG(s))) // '_Sat', &
        & xza_MixRtSat(FileXMin:FileXMax, FileZMin:FileZMax, IdxCG(s)))

      call HistoryPut(     &
        & trim(SpcWetSymbol(IdxCG(s))) // '_Hum', &
        & xza_Humidity(FileXMin:FileXMax, FileZMin:FileZMax, IdxCG(s)))
   end do

   do s = 1, GasNum
      call HistoryPut(     &
        & trim(SpcWetSymbol(s)) // '_MixRtMoist', &
        & xza_CloudMixRtMoist(FileXMin:FileXMax, FileZMin:FileZMax, s))
   end do

  end subroutine AnalFile_OutPut
  


!!!------------------------------------------------------------------------------!!!
  subroutine AnalFile_Get(                                      &
    &       i, AnalTime,                                        &
    &       xz_PotTemp, xz_Exner, pz_VelX, xr_VelZ, xza_MixRt )
 
    use dc_string
    use gtool_history,   only : HistoryGet
    use fileset,       only : HistoryFile
    use gridset,       only : DimXMin, DimXMax, DimZMin, DimZMax, SpcNum, &
      &                       FileXMin, FileXMax, FileZMin, FileZMax
    use basicset,      only : SpcWetSymbol
    use boundary,      only : BoundaryXCyc_xz, BoundaryZSym_xz,   &
      &                       BoundaryXCyc_xza, BoundaryZSym_xza, &
      &                       BoundaryXCyc_pz, BoundaryZSym_pz,   &
      &                       BoundaryXCyc_xr, BoundaryZAntiSym_xr

    !暗黙の型宣言禁止
    implicit none

    !変数定義
    integer, intent(in)  :: i    
    real(8), intent(out) :: AnalTime
    real(8), intent(out) :: pz_VelX(DimXMin:DimXMax,DimZMin:DimZMax)
    real(8), intent(out) :: xr_VelZ(DimXMin:DimXMax,DimZMin:DimZMax)
    real(8), intent(out) :: xz_Exner(DimXMin:DimXMax,DimZMin:DimZMax)
    real(8), intent(out) :: xz_PotTemp(DimXMin:DimXMax,DimZMin:DimZMax)
    real(8), intent(out) :: xza_MixRt(DimXMin:DimXMax,DimZMin:DimZMax,1:SpcNum)
    character(30)        :: name               !変数名
    character(10)        :: step
    
    step = 't=^' // adjustl(toChar(i))

    !-------------------------------------------------------------
    !Get a Value from netCDF File
    !-------------------------------------------------------------
    name = "t"
    call HistoryGet( HistoryFile(1), name, AnalTime, step )

    !-------------------------------------------------------------    
    ! Get a Value from netCDF File 
    !-------------------------------------------------------------
    name = "Exner"
    call HistoryGet( HistoryFile(1), name, xz_Exner(FileXMin:FileXMax, FileZMin:FileZMax), range=step )
    call BoundaryXCyc_xz( xz_Exner )
    call BoundaryZSym_xz( xz_Exner )
    
    name = "PotTemp"
    call HistoryGet( HistoryFile(2), name, xz_PotTemp(FileXMin:FileXMax, FileZMin:FileZMax), range=step )
    call BoundaryXCyc_xz( xz_PotTemp )
    call BoundaryZSym_xz( xz_PotTemp )

    name = "VelX"
    call HistoryGet( HistoryFile(3), name, pz_VelX(FileXMin:FileXMax, FileZMin:FileZMax), range=step )    
    call BoundaryXCyc_pz( pz_VelX )
    call BoundaryZSym_pz( pz_VelX )
    
    name = "VelZ"
    call HistoryGet( HistoryFile(4), name, xr_VelZ(FileXMin:FileXMax, FileZMin:FileZMax), range=step )
    call BoundaryXCyc_xr( xr_VelZ )
    call BoundaryZAntiSym_xr( xr_VelZ )

!    name = "Km"
!    call HistoryGet( HistoryFile(5), name, xz_Km(FileXMin:FileXMax, FileZMin:FileZMax), range=step )
!    xz_Km = xz_BoundaryXCyc_xz( xz_Km )
!    xz_Km = xz_BoundaryZSym_xz( xz_Km )

    do s = 1, SpcNum
      name = trim(SpcWetSymbol(s))
      call HistoryGet( HistoryFile(8+s), name, xza_MixRt(FileXMin:FileXMax, FileZMin:FileZMax, s), range=step )
    end do

    call BoundaryXCyc_xza( xza_MixRt )
    call BoundaryZSym_xza( xza_MixRt )

  end subroutine AnalFile_Get



  subroutine AnalFile_BasicZ_Get( )

    use dc_string
    use gtool_history,   only: HistoryGet
    use fileset,       only: HistoryFile
    use basicset,      only: BasicSetArray_Init, SpcWetSymbol
    use gridset,       only: DimXMin, DimXMax, DimZMin, DimZMax, SpcNum, &
      &                      FileXMin, FileXMax, FileZMin, FileZMax
    use boundary,      only: BoundaryXCyc_xz, BoundaryZSym_xz,     &
      &                      BoundaryXCyc_xza,BoundaryZSym_xza, &
      &                      BoundaryXCyc_pz, BoundaryZSym_pz,     &
      &                      BoundaryXCyc_xr, BoundaryZAntiSym_xr

    !暗黙の型宣言禁止
    implicit none

    !変数定義
    real(8) :: xz_DensBZ(DimXMin:DimXMax, DimZMin:DimZMax)
    real(8) :: xz_PotTempBZ(DimXMin:DimXMax, DimZMin:DimZMax)
    real(8) :: xz_ExnerBZ(DimXMin:DimXMax, DimZMin:DimZMax)
    real(8) :: xza_MixRtBZ(DimXMin:DimXMax, DimZMin:DimZMax,1:SpcNum)
    real(8) :: xz_EffMolWtBZ(DimXMin:DimXMax, DimZMin:DimZMax)
    real(8) :: xz_PressBZ(DimXMin:DimXMax, DimZMin:DimZMax)
    real(8) :: xz_TempBZ(DimXMin:DimXMax, DimZMin:DimZMax)
    real(8) :: xz_VelSoundBZ(DimXMin:DimXMax, DimZMin:DimZMax)
    character(30)        :: name               !変数名
    

    !-------------------------------------------------------------
    ! 基本場の取得
    !-------------------------------------------------------------
    name = "TempBasicZ"
    call HistoryGet( HistoryFile(7), name, xz_TempBZ(FileXMin:FileXMax, FileZMin:FileZMax) )
    call BoundaryXCyc_xz( xz_TempBZ )
    call BoundaryZSym_xz( xz_TempBZ )

    name = "PressBasicZ"
    call HistoryGet( HistoryFile(7), name, xz_PressBZ(FileXMin:FileXMax, FileZMin:FileZMax) )
    call BoundaryXCyc_xz( xz_PressBZ )
    call BoundaryZSym_xz( xz_PressBZ )

    name = "ExnerBasicZ"
    call HistoryGet( HistoryFile(7), name, xz_ExnerBZ(FileXMin:FileXMax, FileZMin:FileZMax) )
    call BoundaryXCyc_xz( xz_ExnerBZ )
    call BoundaryZSym_xz( xz_ExnerBZ )

    name = "PotTempBasicZ"
    call HistoryGet( HistoryFile(7), name, xz_PotTempBZ(FileXMin:FileXMax, FileZMin:FileZMax) )
    call BoundaryXCyc_xz( xz_PotTempBZ )
    call BoundaryZSym_xz( xz_PotTempBZ )

    name = "DensBasicZ"
    call HistoryGet( HistoryFile(7), name, xz_DensBZ(FileXMin:FileXMax, FileZMin:FileZMax) )
    call BoundaryXCyc_xz( xz_DensBZ )
    call BoundaryZSym_xz( xz_DensBZ )

    name = "VelSoundBasicZ"
    call HistoryGet( HistoryFile(7), name, xz_VelSoundBZ(FileXMin:FileXMax, FileZMin:FileZMax) )
    call BoundaryXCyc_xz( xz_VelSoundBZ )
    call BoundaryZSym_xz( xz_VelSoundBZ )

    name = "EffMolWtBasicZ"
    call HistoryGet( HistoryFile(7), name, xz_EffMolWtBZ(FileXMin:FileXMax, FileZMin:FileZMax) )
    call BoundaryXCyc_xz( xz_EffMolWtBZ )
    call BoundaryZSym_xz( xz_EffMolWtBZ )

    do s = 1, SpcNum
      name = trim(SpcWetSymbol(s))//'BasicZ'
      call HistoryGet( HistoryFile(7), name, xza_MixRtBZ(FileXMin:FileXMax, FileZMin:FileZMax, s) )
    end do

    call BoundaryXCyc_xza( xza_MixRtBZ )
    call BoundaryZSym_xza( xza_MixRtBZ )

    !----------------------------------------------------------
    ! BasicSet モジュールに値を設定
    !----------------------------------------------------------
    call BasicSetArray_Init(                       &
      & xz_PressBZ,   xz_ExnerBZ,   xz_TempBZ,     &
      & xz_PotTempBZ, xz_DensBZ,    xz_VelSoundBZ, &
      & xza_MixRtBZ,  xz_EffMolWtBZ )

  end subroutine AnalFile_BasicZ_Get


  subroutine ArareAlloc

    use gridset,       only: DimXMin, DimXMax, DimZMin, DimZMax, SpcNum

    !基本場, 擾乱場の取得.
    allocate( &
      &       xz_PotTemp(DimXMin:DimXMax, DimZMin:DimZMax ),             &
      &       xz_PotTempAll(DimXMin:DimXMax, DimZMin:DimZMax ),          &
      &       xz_Exner(DimXMin:DimXMax, DimZMin:DimZMax ),               &
      &       pz_VelX(DimXMin:DimXMax, DimZMin:DimZMax ),                &
      &       xr_VelZ(DimXMin:DimXMax, DimZMin:DimZMax ),                &
      &       xza_MixRt(DimXMin:DimXMax, DimZMin:DimZMax, 1:SpcNum ),    &
      &       xza_MixRtAll(DimXMin:DimXMax, DimZMin:DimZMax, 1:SpcNum ), &
      &       xza_MixRtAll2(DimXMin:DimXMax, DimZMin:DimZMax, 1:SpcNum ), &
      &       xza_MixRtSat(DimXMin:DimXMax, DimZMin:DimZMax, 1:SpcNum ), &
      &       xza_MixRtEq(DimXMin:DimXMax, DimZMin:DimZMax, 1:SpcNum ),  &
      &       xza_MixRtMoist(DimXMin:DimXMax, DimZMin:DimZMax, 1:SpcNum ),  &
      &       xza_Humidity(DimXMin:DimXMax, DimZMin:DimZMax, 1:SpcNum ), &
      &       za_MolFrEq(DimZMin:DimZMax, 1:SpcNum ),                    &
      &       xz_VTempAll(DimXMin:DimXMax, DimZMin:DimZMax ),            &
      &       xz_VPotTempAll(DimXMin:DimXMax, DimZMin:DimZMax ),         &
      &       xz_EqPotTempAll(DimXMin:DimXMax, DimZMin:DimZMax ),        &
      &       xz_Dens(DimXMin:DimXMax, DimZMin:DimZMax),                 &
      &       xz_TempAll(DimXMin:DimXMax, DimZMin:DimZMax ),            &
      &       xz_PressAll(DimXMin:DimXMax, DimZMin:DimZMax ),           &
      &       xz_EqConstSat(DimXMin:DimXMax, DimZMin:DimZMax ),         &
      &       xz_EqConst(DimXMin:DimXMax, DimZMin:DimZMax ),            &
      !
      &       xz_EffMolWt(DimXMin:DimXMax, DimZMin:DimZMax ),           &
      &       xz_EffMolWtMoist(DimXMin:DimXMax, DimZMin:DimZMax ),           &
      &       xza_MixRtDivMolWt(DimXMin:DimXMax,DimZMin:DimZMax,SpcNum),&
      &       xza_LatentHeat(DimXMin:DimXMax,DimZMin:DimZMax,SpcNum),   &
      !
      &       xza_MolFrAll(DimXMin:DimXMax,DimZMin:DimZMax,SpcNum), &
      &       xz_MolWtWet(DimXMin:DimXMax,DimZMin:DimZMax),   &
      &       xz_MolWtMoist(DimXMin:DimXMax,DimZMin:DimZMax),   &
      &       xz_Stab(DimXMin:DimXMax,DimZMin:DimZMax),       &
      &       xz_StabTemp(DimXMin:DimXMax,DimZMin:DimZMax),   &
      &       xz_StabMolWt(DimXMin:DimXMax,DimZMin:DimZMax),  &
      &       xz_StabMoist(DimXMin:DimXMax,DimZMin:DimZMax),       &
      &       xz_StabTempMoist(DimXMin:DimXMax,DimZMin:DimZMax),   &
      &       xz_StabMolWtMoist(DimXMin:DimXMax,DimZMin:DimZMax),  &
!      &       xza_CloudDens(DimXMin:DimXMax,DimZMin:DimZMax,1:SpcNum),  &
!      &       xz_CloudDens(DimXMin:DimXMax,DimZMin:DimZMax),  &
      &       xz_CloudMixRtMoist(DimXMin:DimXMax,DimZMin:DimZMax),  &
      &       xza_CloudMixRtMoist(DimXMin:DimXMax,DimZMin:DimZMax,SpcNum),  &
      &       xz_CloudMixRtEq(DimXMin:DimXMax,DimZMin:DimZMax),  &
      &       xza_CloudMixRtEq(DimXMin:DimXMax,DimZMin:DimZMax,SpcNum),  &
      !
      &       xz_TempMoist(DimXMin:DimXMax,DimZMin:DimZMax),  &
      &       xz_PressMoist(DimXMin:DimXMax,DimZMin:DimZMax),  &
      &       xza_MolFrMoist(DimXMin:DimXMax,DimZMin:DimZMax,1:SpcNum),  &
      !
      &       MolFrIni(SpcNum), &
      &       xz_StrmFunc(DimXMin:DimXMax, DimZMin:DimZMax ),           &
      &       pq_StrmFunc(DimXMin:DimXMax, DimZMin:DimZMax ),           &
      &       xr_Dens(DimXMin:DimXMax, DimZMin:DimZMax ),           &
      &       pz_Dens(DimXMin:DimXMax, DimZMin:DimZMax )       )

    xz_StrmFunc = 0.0d0
    xza_MixRtSat = 0.0d0
    xza_MixRtDivMolWt = 0.0d0

  end subroutine ArareAlloc

end program ArareAnal
