!= Module ReStartFileIO
!
! Authors::   SUGIYAMA Ko-ichiro, ODAKA Masatsugu
! Version::   $Id: restartfileio.f90,v 1.17 2014/07/08 00:59:55 sugiyama Exp $ 
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2007. All rights reserved.
! License::   See COPYRIGHT[link:../../COPYRIGHT]


module ReStartFileIO
  !
  !リスタート用の場の情報を netCDF ファイルに出力するためのルーチン
  !

  !モジュール読み込み
  use gtool_history
  use dc_types,    only : DP, STRING
  use dc_message,  only : MessageNotify
  use dc_string,   only : toChar
  use dc_iounit,   only : FileOpen
  use mpi_wrapper, only: myrank, FLAG_LIB_MPI
  use axesset,     only: x_X,        &!X 座標軸(スカラー格子点)
    &                    y_Y,        &!Y 座標軸(スカラー格子点)
    &                    z_Z          !Z 座標軸(スカラー格子点)
  use gridset,  only: &
    &                 imin,           &!X 方向の配列の下限
    &                 imax,           &!X 方向の配列の上限
    &                 jmin,           &!Y 方向の配列の下限
    &                 jmax,           &!Y 方向の配列の上限
    &                 kmin,           &!Z 方向の配列の下限
    &                 kmax,           &!Z 方向の配列の上限
    &                 ncmax              !凝縮成分の数
  use timeset,  only: DelTimeLong, RestartTime 
  use fileset,  only: &
    &                 filetitle,        &!データの表題
    &                 filesource,       &!データを作成する手順
    &                 FileInstitution    !最終変更者・組織
  use basicset, only: basicset_init 
  use namelist_util, only: namelist_filename

  !暗黙の型宣言禁止
  implicit none
  
  !関数を public に指定
  public ReStartFileIO_init
  public ReStartFileio_Finalize
  public ReStartFileio_BasicZ_Get
  public ReStartFileio_Var_Get

  type(GT_HISTORY), save, public   :: rstat
  character(STRING), save, private :: InitialFile = ""
  character(STRING), save, private :: InputFile   = ""
  character(STRING), save, private :: OutputFile  = "output.nc"
  
contains

  subroutine ReStartFileio_Init ( FlagInitData )
    !
    !リスタートファイルの書き出し
    !
   
    !暗黙の型宣言禁止
    implicit none

    !変数定義
    logical, intent(in), optional :: FlagInitData  ! 初期値生成プログラムの場合は .true.

    real(4)            :: SpcID(ncmax)
    integer            :: N, L, M
    integer            :: s    
    integer            :: unit     !装置番号
     
    !NAMELIST から情報を取得
    NAMELIST /restartfileio_nml/ InitialFile, InputFile, OutputFile
    
    call FileOpen(unit, file=namelist_filename, mode='r')
    read(unit, NML=restartfileio_nml)
    close(unit)

    !確認
    if (myrank == 0) then 
      call MessageNotify( "M", &
        & "restartfileioIO_init", "InitialFile  = %c", c1=trim(InitialFile) )
      call MessageNotify( "M", &
        & "restartfileioIO_init", "InputFile  = %c", c1=trim(InputFile) )
      call MessageNotify( "M", &
        & "restartfileioIO_init", "OutputFile = %c", c1=trim(OutputFile) )
    end if

    ! InputFile が空の場合は, 初期値ファイルを使う. 
    if ( InputFile == "" ) then 
      InputFile = InitialFile
    end if

    !初期値生成の場合には, outputfile 名を変更
    if ( present( FlagInitData ) ) then 
      if ( FlagInitData ) then 
        if ( .NOT. InitialFile == "" ) then  ! ファイル名が空ならば
          InputFile  = ""
          OutputFile = InitialFile
        end if
      end if
    end if

    !確認
    if (myrank == 0) then 
      call MessageNotify( "M", &
        & "restartfileioIO_init", "INPUT  = %c", c1=trim(InputFile) )
      call MessageNotify( "M", &
        & "restartfileioIO_init", "OUTPUT = %c", c1=trim(OutputFile) )
    end if

    SpcID = 0.0d0
    do s = 1, ncmax
      SpcID(s) = real( s, 4 )
    end do
    
    N = size(x_X, 1)
    L = size(y_Y, 1)
    M = size(z_Z, 1)
    
    !-------------------------------------------------------------    
    ! ヒストリー作成
    !-------------------------------------------------------------  
    call HistoryCreate(                              &
      & file = Outputfile,                           &
      & title = filetitle,                           &
      & source = filesource,                         &
      & institution = FileInstitution,               &
      & dims=(/'x','z','s','t'/),                    &
      & dimsizes=(/N, M, ncmax, 0/),                 &
      & longnames=(/'X-coordinate',                  &
      &             'Z-coordinate',                  &
      &             'Species Num ',                  &
      &             'Time        '/),                &
      & units=(/'m  ','m  ','1  ','sec'/),           &
      & xtypes=(/'double', 'double', 'double', 'double'/), &
      & flag_mpi_split = FLAG_LIB_MPI,               &
      & origin=0.0, interval=1.0,                    &
      & history=rstat, quiet=.true. )
    
    !-------------------------------------------------------------  
    ! 変数出力
    !-------------------------------------------------------------
    call HistoryPut('x', x_X, rstat )
    call HistoryPut('z', z_Z, rstat )
    call HistoryPut('s', real(SpcID, 4), rstat )

    !無次元圧力の基本場
    call HistoryAddVariable(                             &
      & varname='ExnerBasicZ', dims=(/'x','z'/),      &
      & longname='nondimensional pressure', units='1',&
      & xtype='double', history=rstat )
    
    !温位の基本場
    call HistoryAddVariable(                            &
      & varname='PotTempBasicZ', dims=(/'x','z'/),    &
      & longname='potential temperature',            &
      & units='K', xtype='double', history=rstat ) 

    !温位の基本場
    call HistoryAddVariable(                            &
      & varname='VPotTempBasicZ', dims=(/'x','z'/),    &
      & longname='virtual potential temperature',            &
      & units='K', xtype='double', history=rstat ) 
    
    !密度の基本場
    call HistoryAddVariable(                            &
      & varname='DensBasicZ', dims=(/'x','z'/),      &
      & longname='density',                          &
      & units='Kg.m-3', xtype='double', history=rstat )
    
    !音波速度の基本場
    call HistoryAddVariable(                            &
      & varname='VelSoundBasicZ', dims=(/'x','z'/),  &
      & longname='sound velocity',                   &
      & units='m.s-2', xtype='double', history=rstat )

    !温度の基本場
    call HistoryAddVariable(                            &
      & varname='TempBasicZ', dims=(/'x','z'/),  &
      & longname='Temperature of basic state',       &
      & units='K', xtype='double', history=rstat ) 
    
    !圧力の基本場
    call HistoryAddVariable(                            &
      & varname='PressBasicZ', dims=(/'x','z'/),  &
      & longname='Pressure of basic state',             &
      & units='Pa', xtype='double', history=rstat ) 
    
    !水蒸気混合比の基本場
    call HistoryAddVariable(                            &
      & varname='MixRtBasicZ', dims=(/'x','z','s'/),  &
      & longname='Mixing ratio of Condensible volatiles',        &
      & units='kg.kg-1', xtype='double', history=rstat ) 
    
    !分子量効果
    call HistoryAddVariable(                         &
      & varname='EffMolWtBasicZ', dims=(/'x','z'/),  &
      & longname='Effect of Mole Weight',            &
      & units='1', xtype='double', history=rstat ) 

    !分子量効果
    call HistoryAddVariable(                        &
      & varname='HumBasicZ', dims=(/'x','z','s'/),  &
      & longname='Humidity',                        &
      & units='1', xtype='double', history=rstat ) 
    
    !速度
    call HistoryAddVariable(                         &
      & varname='VelX', dims=(/'x','z','t'/),        &
      & longname='zonal velocity',                   &
      & units='m.s-1',                                 &
      & xtype='double', history=rstat )
    
    !速度
    call HistoryAddVariable(                         &
      & varname='VelY', dims=(/'x','z','t'/),        &
      & longname='meridional velocity',              &
      & units='m.s-1',                                 &
      & xtype='double', history=rstat )
    
    !速度
    call HistoryAddVariable(                         &
      & varname='VelZ', dims=(/'x','z','t'/),        &
      & longname='vertical velocity',                &
      & units='m.s-1',                                 &
      & xtype='double', history=rstat )
    
    !無次元圧力
    call HistoryAddVariable(                         &
      & varname='Exner', dims=(/'x','z','t'/),       &
      & longname='nondimensional pressure',          &
      & units='1',                                   &
      & xtype='double', history=rstat )
    
    !温位の擾乱
    call HistoryAddVariable(                         &
      & varname='PotTemp', dims=(/'x','z','t'/),     &
      & longname='virtual potential temperature',    &
      & units='K',                                   &
      & xtype='double', history=rstat )
    
    !渦粘性係数
    call HistoryAddVariable(                         &
      & varname='Km', dims=(/'x','z','t'/),      &
      & longname='Km',                               &
      & units='m2.s-1',                              &
      & xtype='double', history=rstat )
    
    !渦粘性係数
    call HistoryAddVariable(                         &
      & varname='Kh', dims=(/'x','z','t'/),      &
      & longname='Kh',                               &
      & units='m2.s-1',                              &
      & xtype='double', history=rstat )

    !雲密度
    call HistoryAddVariable(                         &
      & varname='CDens', dims=(/'x','z','t'/),   &
      & longname='CDens',                            &
      & units='m2.s-1',                              &
      & xtype='double', history=rstat )
    
    !混合比
    call HistoryAddVariable(                         &
      & varname='MixRt', dims=(/'x','z','s','t'/),&
      & longname='Mixing Ratio',                     &
      & units='kg.kg-1"',                            & 
      & xtype='double', history=rstat )
    
  end subroutine ReStartFileio_Init
  
  
  subroutine ReStartFileIO_Finalize
    !
    !リスタートファイルのクローズ
    !
    
    !モジュール読み込み
    use gtool_history
    
    !暗黙の型宣言禁止
    implicit none
    
    !ファイルを閉じる
    call HistoryClose(rstat, quiet=.true.)
    
  end subroutine ReStartFileIO_Finalize
  

  subroutine ReStartFileio_Var_Get(   &
    & pz_VelXB,  pz_VelXN,    & ! (in)
    & xr_VelZB,  xr_VelZN,    & ! (in)
    & xz_PotTempB, xz_PotTempN,   & ! (in)
    & xz_ExnerB, xz_ExnerN,   & ! (in)
    & xza_MixRtB, xza_MixRtN,   & ! (in)
    & xz_KmB,    xz_KmN,      & ! (in)
    & xz_KhB,    xz_KhN       & ! (in)
    & ) 
    !
    !リスタートファイルから情報取得
    !

    !暗黙の型宣言禁止
    implicit none

    !変数定義
    real(DP), intent(out) :: pz_VelXN &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xr_VelZN &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xz_ExnerN &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xz_PotTempN &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xz_KmN &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xz_KhN &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xza_MixRtN &
      &              (imin:imax,kmin:kmax,ncmax)
    real(DP), intent(out) :: pz_VelXB &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xr_VelZB &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xz_ExnerB &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xz_PotTempB &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xz_KmB &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xz_KhB &
      &                     (imin:imax,kmin:kmax)
    real(DP), intent(out) :: xza_MixRtB &
      &              (imin:imax,kmin:kmax,ncmax)

    character(STRING)    :: name               !変数名
    character(STRING)    :: TimeN = ""
    character(STRING)    :: TimeB = ""

    !-------------------------------------------------------------
    ! Get a Value from netCDF File
    !-------------------------------------------------------------    
    if (RestartTime /= 0.0d0) then
      timeB = 't=' // toChar( RestartTime - DelTimeLong)
      timeN = 't=' // toChar( RestartTime  )
    else
      timeB = 't=' // toChar( RestartTime )
      timeN = 't=' // toChar( RestartTime )
    end if

!    write(*,*) TimeN, TimeB

    name = "PotTemp"
    call HistoryGet( InputFile, name, xz_PotTempB, range=TimeB, flag_mpi_split = FLAG_LIB_MPI )
    call HistoryGet( InputFile, name, xz_PotTempN, range=TimeN, flag_mpi_split = FLAG_LIB_MPI )

    name = "VelX"
    call HistoryGet( InputFile, name, pz_VelXB, range=TimeB, flag_mpi_split = FLAG_LIB_MPI )
    call HistoryGet( InputFile, name, pz_VelXN, range=TimeN, flag_mpi_split = FLAG_LIB_MPI )

    name = "VelZ"
    call HistoryGet( InputFile, name, xr_VelZB, range=TimeB, flag_mpi_split = FLAG_LIB_MPI )
    call HistoryGet( InputFile, name, xr_VelZN, range=TimeN, flag_mpi_split = FLAG_LIB_MPI )

    name = "Exner"
    call HistoryGet( InputFile, name, xz_ExnerB, range=TimeB, flag_mpi_split = FLAG_LIB_MPI )
    call HistoryGet( InputFile, name, xz_ExnerN, range=TimeN, flag_mpi_split = FLAG_LIB_MPI )

    name = "Km"
    call HistoryGet( InputFile, name, xz_KmB, range=TimeB, flag_mpi_split = FLAG_LIB_MPI )
    call HistoryGet( InputFile, name, xz_KmN, range=TimeN, flag_mpi_split = FLAG_LIB_MPI )
    
    name = "Kh"
    call HistoryGet( InputFile, name, xz_KhB, range=TimeB, flag_mpi_split = FLAG_LIB_MPI )
    call HistoryGet( InputFile, name, xz_KhN, range=TimeN, flag_mpi_split = FLAG_LIB_MPI )

    name = "MixRt"
    call HistoryGet( InputFile, name, xza_MixRtB, range=TimeB, flag_mpi_split = FLAG_LIB_MPI )
    call HistoryGet( InputFile, name, xza_MixRtN, range=TimeN, flag_mpi_split = FLAG_LIB_MPI )
    
  end subroutine ReStartFileio_Var_Get
       


  subroutine ReStartFileio_BasicZ_Get()
    !
    !リスタートファイルから情報取得
    !

    !暗黙の型宣言禁止
    implicit none

    !変数定義
    real(DP)              :: Var3D(imin:imax,kmin:kmax)
    real(DP)              :: Var4D(imin:imax,kmin:kmax,ncmax)
    real(DP)              :: xz_ExnerBasicZ(imin:imax,kmin:kmax)
                                               !基本場のエクスナー関数
    real(DP)              :: xz_DensBasicZ(imin:imax,kmin:kmax)
                                               !基本場の密度
    real(DP)              :: xz_PotTempBasicZ(imin:imax,kmin:kmax)
                                               !基本場の温位
    real(DP)              :: xz_VelSoundBasicZ(imin:imax,kmin:kmax)
                                               !基本場の音速
    real(DP)              :: xz_PressBasicZ(imin:imax,kmin:kmax)
                                               !基本場の圧力
    real(DP)              :: xz_TempBasicZ(imin:imax,kmin:kmax)
                                               !基本場の温度
    real(DP)              :: xza_MixRtBasicZ(imin:imax,kmin:kmax, ncmax)
                                               !基本場の混合比
    real(DP)              :: xz_EffMolWtBasicZ(imin:imax,kmin:kmax)
                                               !基本場の分子量効果
    character(STRING)    :: name               !変数名

    !-------------------------------------------------------------
    ! 基本場の取得
    !
    name = "ExnerBasicZ"
    call HistoryGet( InputFile, name, Var3D, flag_mpi_split = FLAG_LIB_MPI )
    xz_ExnerBasicZ = Var3D
    
    name = "PotTempBasicZ"
    call HistoryGet( InputFile, name, Var3D, flag_mpi_split = FLAG_LIB_MPI )
    xz_PotTempBasicZ = Var3D
    
    name = "DensBasicZ"
    call HistoryGet( InputFile, name, Var3D, flag_mpi_split = FLAG_LIB_MPI )
    xz_DensBasicZ = Var3D
    
    name = "VelSoundBasicZ"
    call HistoryGet( InputFile, name, Var3D, flag_mpi_split = FLAG_LIB_MPI )
    xz_VelSoundBasicZ = Var3D
    
    name = "TempBasicZ"
    call HistoryGet( InputFile, name, Var3D, flag_mpi_split = FLAG_LIB_MPI )
    xz_TempBasicZ = Var3D
    
    name = "PressBasicZ"
    call HistoryGet( InputFile, name, Var3D, flag_mpi_split = FLAG_LIB_MPI )
    xz_PressBasicZ = Var3D
    
    name = "MixRtBasicZ"
    call HistoryGet( InputFile, name, Var4D, flag_mpi_split = FLAG_LIB_MPI )
    xza_MixRtBasicZ = Var4D
    
    name = "EffMolWtBasicZ"
    call HistoryGet( InputFile, name, Var3D, flag_mpi_split = FLAG_LIB_MPI )
    xz_EffMolWtBasicZ = Var3D
    
    !----------------------------------------------------------
    ! BasicSet モジュールに値を設定
    !----------------------------------------------------------
    call basicset_init(    &
      & xz_PressBasicZ,    &
      & xz_ExnerBasicZ,    &
      & xz_TempBasicZ,     &
      & xz_PotTempBasicZ,  &
      & xz_DensBasicZ,     &
      & xz_VelSoundBasicZ, &
      & xza_MixRtBasicZ,   &
      & xz_EffMolWtBasicZ  &
      & )
    
  end subroutine ReStartFileio_BasicZ_Get
       
end module ReStartFileIO
