!= ヒストリデータ出力
!
!= History data output
!
! Authors::   Yasuhiro MORIKAWA
! Version::   $Id: gridset.f90,v 1.5 2007/06/09 13:12:30 sugiyama Exp $ 
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2008. All rights reserved.
! License::   See COPYRIGHT[link:../../../COPYRIGHT]
!

module history_file_io
  !
  != ヒストリデータ出力
  !
  != History data output
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  ! ヒストリデータ出力の初期化, 時刻進行, 登録変数の表示と
  ! 終了処理を行います. 
  ! [gt4f90io ライブラリ]{http://www.gfd-dennou.org/library/gtool4} の 
  ! gt4_historyauto モジュールを用います. 
  ! 
  ! 各データの出力は, モデルの各プログラム内において, 
  ! gt4_historyauto モジュールから提供される
  ! HistoryAutoAddVariable および HistoryAutoPut を用います. 
  !

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

  ! 格子点設定
  ! Grid points settings
  !
  use gridset, only: nmax, & ! 最大全波数. 
                             ! Maximum truncated wavenumber
    &                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. 
    &                 TOKEN  ! キーワード.   Keywords. 

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

  ! 宣言文 ; Declaration statements
  !
  implicit none
  private

  ! 公開手続き
  ! Public procedure
  !
  public:: HistoryFileOpen, HistoryFileClose, HistoryFileProgress
  public:: HistoryFilePutLine

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

  ! 非公開変数
  ! Private variables
  !

!!$  namelist /history_file_io_nml/ 

  character(*), parameter:: module_name = 'history_file_io'
                              ! モジュールの名称. 
                              ! Module name
  character(*), parameter:: version = &
    & '$Name:  $' // &
    & '$Id:  $'
                              ! モジュールのバージョン
                              ! Module version

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

  interface HistoryFileClose
    module procedure HistoryFileClose
  end interface

  interface HistoryFileProgress
    module procedure HistoryFileProgress
  end interface

  interface HistoryFilePutLine
    module procedure HistoryFilePutLine
  end interface

contains

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

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

    ! 物理定数設定
    ! Physical constants settings
    !
    use constants, only: PI   ! $ \pi $ .
                              ! 円周率.  Circular constant

    ! 座標データ設定
    ! Axes data settings
    !
    use axesset, only: &
      & x_Lon, &
                              ! $ \lambda $ [rad.] . 経度. Longitude
      & x_Lon_Weight, &
                              ! $ \Delta \lambda $ [rad.] . 
                              ! 経度座標重み. 
                              ! Weight of longitude
      & y_Lat, &
                              ! $ \varphi $ [rad.] . 緯度. Latitude
      & y_Lat_Weight, &
                              ! $ \Delta \varphi $ [rad.] . 
                              ! 緯度座標重み. 
                              ! Weight of latitude
      & z_Sigma, &
                              ! $ \sigma $ レベル (整数). 
                              ! Full $ \sigma $ level
      & r_Sigma, &
                              ! $ \sigma $ レベル (半整数). 
                              ! Half $ \sigma $ level
      & z_DelSigma
                              ! $ \Delta \sigma $ (整数). 
                              ! $ \Delta \sigma $ (Full)

    ! 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

    ! 宣言文 ; Declaration statements
    !
    implicit none

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

    ! 実行文 ; Executable statement
    !

    if ( history_file_io_inited ) return
    call InitCheck

    ! NAMELIST の読み込み
    ! NAMELIST is input
    !
!!$    call FileOpen( unit_nml, &          ! (out)
!!$      & namelist_filename, mode = 'r' ) ! (in)
!!$
!!$    rewind( unit_nml )
!!$    read( unit_nml, &         ! (in)
!!$      & nml = history_file_io_nml, &  ! (out)
!!$      & iostat = iostat_nml ) ! (out)
!!$    close( unit_nml )
!!$
!!$    call NmlutilMsg( iostat_nml, module_name ) ! (in)
!!$    if ( iostat_nml == 0 ) write( STDOUT, nml = history_file_io_nml )

    ! モデルの時刻取得
    ! Initialization by "HistoryAutoCreate"
    !
    call TimesetGetCurrentTime( current_time, & ! (out)
      &                         'sec' )         ! (in)

    call TimesetGetDelTime( delta_time, &   ! (out)
      &                     'sec' )         ! (in)

    ! HistoryAutoCreate による初期化
    ! Initialization by "HistoryAutoCreate"
    !
    call HistoryAutoCreate( &
      &     title = trim(FileTitle) // ' history data', &          ! (in)
      &    source = FileSource, institution = FileInstitution, &   ! (in)
      &      dims = StoA( 'lon', 'lat', 'sig', 'sigm', &
      &                   'wn' ), &                                ! (in)
      &  dimsizes = (/ imax, jmax, kmax, kmax + 1, &
      &                (nmax+1)**2 /), &                           ! (in)
      & longnames = StoA( 'longitude', 'latitude', &
      &                   'sigma at layer midpoints', &
      &                   'sigma at layer end-points (half level)', &
      &                   'subscript of spectral data' ), &        ! (in)
      &     units = StoA( 'degree_east', 'degree_north', &
      &                   '1', '1', '1' ), &                ! (in)
!!$      &      slice_start  = (/ 1, 1, 1, 1, 1 /), &          ! (in) optional
!!$      &      slice_end    = (/ 0, 0, 0, 0, 0 /), &          ! (in) optional
!!$      &      slice_stride = (/ 1, 1, 1, 1, 1 /), &          ! (in) optional
!!$      & namelist_filename = namelist_filename, &            ! (in) optional
!!$      &            origin = real( current_time ), &         ! (in) optional
!!$      &          terminus = real( delta_time * 100 ), &     ! (in) optional
!!$      &          interval = real( delta_time ), &           ! (in) optional
!!$      &  newfile_interval = real( delta_time * 10 ), &      ! (in) optional
!!$      &              node = '01', &                         ! (in) optional
      &      current_time = real( current_time ), &         ! (in) optional
      &        delta_time = real( delta_time ) )            ! (in) optional


    ! 座標データへの属性の設定
    ! Attributes of axes data settings
    !
    call HistoryAutoAddAttr( &
      & varname = 'lon', attrname = 'standard_name', &   ! (in)
      & value = 'longitude' )                            ! (in)
    call HistoryAutoAddAttr( &
      & varname = 'lat', attrname = 'standard_name', &   ! (in)
      & value = 'latitude' )                             ! (in)
    call HistoryAutoAddAttr( &
      & varname = 'sig', attrname = 'standard_name', &   ! (in)
      & value = 'atmosphere_sigma_coordinate' )          ! (in)
    call HistoryAutoAddAttr( &
      & varname = 'sigm', attrname = 'standard_name', &  ! (in)
      & value = 'atmosphere_sigma_coordinate' )          ! (in)
    call HistoryAutoAddAttr( &
      & varname = 'sig', attrname = 'positive', &        ! (in)
      & value = 'down' )                                 ! (in)
    call HistoryAutoAddAttr( &
      & varname = 'sigm', attrname = 'positive', &       ! (in)
      & value = 'down' )                                 ! (in)

    ! 座標データの設定
    ! Axes data settings
    !
    call HistoryAutoPutAxes( &
      & varname = 'lon', &               ! (in)
      & array = x_Lon / PI * 180.0_DP )  ! (in)
    call HistoryAutoPutAxes( &
      & varname = 'lat', &               ! (in)
      & array = y_Lat / PI * 180.0_DP )  ! (in)
    call HistoryAutoPutAxes( &
      & varname = 'sig', &               ! (in)
      & array = z_Sigma )                ! (in)
    call HistoryAutoPutAxes( &
      & varname = 'sigm', &              ! (in)
      & array = r_Sigma )                ! (in)
    call HistoryAutoPutAxes( &
      & varname = 'wn', &                ! (in)
      & array = w_Number )               ! (in)

    ! 座標重みの設定
    ! Axes weights settings
    !
    call HistoryAutoAddVariable( &
      & varname = 'lon_weight', &                           ! (in)
      & dims = StoA('lon'), &                               ! (in)
      & longname = 'weight for integration in longitude', & ! (in)
      & units = 'radian', xtype = 'float' )                 ! (in)
    call HistoryAutoAddAttr( &
      & varname = 'lon', attrname = 'gt_calc_weight', &     ! (in)
      & value = 'lon_weight' )                              ! (in)
    call HistoryAutoPutAxes( &
      & varname = 'lon_weight', array = x_Lon_Weight )      ! (in)

    call HistoryAutoAddVariable( &
      & varname = 'lat_weight', &                           ! (in)
      & dims = StoA('lat'), &                               ! (in)
      & longname = 'weight for integration in latitude', &  ! (in)
      & units = 'radian', xtype = 'float' )                 ! (in)
    call HistoryAutoAddAttr( &
      & varname = 'lat', attrname = 'gt_calc_weight', &     ! (in)
      & value = 'lat_weight' )                              ! (in)
    call HistoryAutoPutAxes( &
      & varname = 'lat_weight', array = y_Lat_Weight )      ! (in)

    call HistoryAutoAddVariable( &
      & varname = 'sig_weight', &                           ! (in)
      & dims = StoA('sig'), &                               ! (in)
      & longname = 'weight for integration in sigma', &     ! (in)
      & units = '1', xtype = 'float' )                      ! (in)
    call HistoryAutoAddAttr( &
      & varname = 'sig', attrname = 'gt_calc_weight', &     ! (in)
      & value = 'sig_weight' )                              ! (in)
    call HistoryAutoPutAxes( &
      & varname = 'sig_weight', array = z_DelSigma )        ! (in)

    ! 印字 ; Print
    !
    call MessageNotify( 'M', module_name, '----- Initialization Messages -----' )
    call MessageNotify( 'M', module_name, '-- version = %c', c1 = trim(version) )

    history_file_io_inited = .true.
  end subroutine HistoryFileOpen

  subroutine HistoryFileClose
    !
    ! ヒストリデータファイル出力の終了処理を行います. 
    !
    ! Terminate history data files output. 

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

    ! 宣言文 ; Declaration statements
    !
    implicit none

    ! 作業変数
    ! Work variables
    !

    ! 実行文 ; Executable statement
    !

  end subroutine HistoryFileClose

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

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

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

    ! 実行文 ; Executable statement
    !

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

  end subroutine InitCheck

end module history_file_io
