!= 初期値データファイル生成プログラムのサンプル
!
!= Initial data file generation sample program
!
! Authors::   Yasuhiro MORIKAWA
! Version::   $Id: init_sample.f90,v 1.7 2008-02-20 09:32:49 morikawa Exp $
! Tag Name::  $Name: dcpam4-20080427 $
! Copyright:: Copyright (C) GFD Dennou Club, 2007. All rights reserved.
! License::   See COPYRIGHT[link:../../COPYRIGHT]
!

program init_sample
  !
  ! 初期値生成のための実行プログラムのサンプルです.
  !
  ! This is sample executable program for initial data generation.
  !

  !---------------------------------------------------------
  !  初期値生成
  !  Generate initial data
  !---------------------------------------------------------
  use initial_data, only: INIDAT, IniDataCreate, &
    & IniDataGetAxes, IniDataGet, IniDataClose, IniDataPutLine

  !---------------------------------------------------------
  !  物理定数
  !  Physical constants
  !---------------------------------------------------------
  use constants, only: CONST, Create, Get

  !---------------------------------------------------------
  !  データ I/O
  !  Data I/O
  !---------------------------------------------------------
  use gt4_history, only: GT_HISTORY, &
    & HistoryCreate, HistoryAddVariable, HistoryPut, HistoryClose, &
    & HistoryAddAttr

  !---------------------------------------------------------
  !  汎用ユーティリティ
  !  Common utilities
  !---------------------------------------------------------
  use dc_types, only: DP, STRING, TOKEN, STDOUT
  use dc_args, only: ARGS, DCArgsOpen, DCArgsHelpMsg, DCArgsOption, &
    & DCArgsDebug, DCArgsHelp, DCArgsStrict, DCArgsClose
  use dc_trace, only: DbgMessage, BeginSub, EndSub
  use dc_message,only: MessageNotify
  use dc_string, only: StoA, toChar
  use dc_clock, only: CLOCK, DCClockCreate, DCClockClose, DCClockStart, &
    & DCClockStop, DCClockResult, &
    & DCClockPredict, operator(+)
  use dc_iounit, only: FileOpen
  implicit none


  !-------------------------------------------------------------------
  !  実験の表題, モデルの名称, 所属機関名
  !  Title of a experiment, name of model, sub-organ
  !-------------------------------------------------------------------
  character(*), parameter:: title = &
    & 'init_sample $Name: dcpam4-20080427 $ :: ' // &
    & 'DCPAM sample program: initial data file generation'
  character(*), parameter:: source = &
    & 'dcpam4 (See http://www.gfd-dennou.org/library/dcpam)'
  character(*), parameter:: institution = &
    & 'GFD Dennou Club (See http://www.gfd-dennou.org)'

  !-------------------------------------------------------------------
  !  格子点数・最大全波数
  !  Grid points and maximum truncated wavenumber
  !-------------------------------------------------------------------
  integer:: nmax = 10         ! 最大全波数. 
                              ! Maximum truncated wavenumber
  integer:: imax = 32         ! 経度格子点数. 
                              ! Number of grid points in longitude
  integer:: jmax = 16         ! 緯度格子点数. 
                              ! Number of grid points in latitude
  integer:: kmax = 12         ! 鉛直層数. 
                              ! Number of vertical level

  namelist /init_sample_grid_nml/ &
    & nmax, imax, jmax, kmax
                              ! 格子点, 最大波数の設定. 
                              !
                              ! Configure grid points and maximum truncated wavenumber

  !-------------------------------------------------------------------
  !  ファイル名
  !  Filename
  !-------------------------------------------------------------------
  character(STRING):: init_nc = 'init_T10L12.nc'
                              ! 初期値データ netCDF ファイル. 
                              ! NetCDF file for initial data

  namelist /init_sample_file_nml/ &
    & init_nc
                              ! ファイル名の設定. 
                              !
                              ! Configure filename

  !---------------------------------------------------------
  !  物理定数
  !  Physical constants
  !---------------------------------------------------------
  real(DP):: PI               ! $ \pi $ .    円周率.         Circular constant

  !---------------------------------------------------------
  !  配列の定義
  !  Declaration of array
  !---------------------------------------------------------

  !-------------------------------------
  !  座標変数
  !  Coordinate variables
  real(DP), allocatable:: x_Lon (:) ! 経度. Longitude
  real(DP), allocatable:: x_Lon_Weight (:)
                                    ! 経度積分用座標重み. 
                                    ! Weight for integration in longitude
  real(DP), allocatable:: y_Lat (:) ! 緯度. Latitude
  real(DP), allocatable:: y_Lat_Weight (:)
                                    ! 緯度積分用座標重み. 
                                    ! Weight for integration in latitude
  real(DP), allocatable:: z_Sigma (:)
                              ! $ \sigma $ レベル (整数). 
                              ! Full $ \sigma $ level
  real(DP), allocatable:: r_Sigma (:)
                              ! $ \sigma $ レベル (半整数). 
                              ! Half $ \sigma $ level

  !-------------------------------------
  !  予報変数
  !  Prediction variables
  real(DP), allocatable:: xyz_U (:,:,:)
                              ! $ U $ .     東西風速. Zonal wind
  real(DP), allocatable:: xyz_V (:,:,:)
                              ! $ V $ .     南北風速. Meridional wind
  real(DP), allocatable:: xyz_Vor (:,:,:)
                              ! $ \zeta $ . 渦度. Vorticity
  real(DP), allocatable:: xyz_Div (:,:,:)
                              ! $ D $ .     発散. Divergence
  real(DP), allocatable:: xyz_Temp (:,:,:)
                              ! $ T $ .     温度. Temperature
  real(DP), allocatable:: xyz_QVap (:,:,:)
                              ! $ q $ .     比湿. Specific humidity
  real(DP), allocatable:: xy_Ps (:,:)
                              ! $ P_s $ .   地表面気圧. Surface pressure

  !---------------------------------------------------------
  !  作業変数
  !  Work variables
  !---------------------------------------------------------
  type(ARGS):: arg            ! コマンドライン引数. 
                              ! command line options
  logical:: OPT_namelist      ! -N, --namelist オプションの有無. 
                              ! Existence of '-N', '--namelist' option
  character(STRING):: VAL_namelist
                              ! -N, --namelist オプションの値. 
                              ! Value of '-N', '--namelist' option
  integer:: unit_nml          ! NAMELIST ファイルオープン用装置番号. 
                              ! Unit number for NAMELIST file open
  integer:: iostat_nml        ! NAMELIST 読み込み時の IOSTAT. 
                              ! IOSTAT of NAMELIST read
  type(CONST):: const_earth   ! 物理定数. Physical constants.
  type(INIDAT):: ini_dat      ! 初期値データ生成
                              ! Generation of initial data
  type(GT_HISTORY):: gthist_init
                              ! 初期値データ出力. 
                              ! Output of initial data
  type(CLOCK):: clk_setup, clk_histput
                              ! CPU 時間モニター. 
                              ! CPU time monitor

  character(*), parameter:: version = &
    & '$Name: dcpam4-20080427 $' // &
    & '$Id: init_sample.f90,v 1.7 2008-02-20 09:32:49 morikawa Exp $'
  character(STRING),  parameter:: subname = "init_sample"

continue
  !-------------------------------------------------------------------
  !  コマンドライン引数の取得
  !  Command line options handling
  !-------------------------------------------------------------------
  call cmdline_optparse  ! これは内部サブルーチン. This is an internal subroutine

  call BeginSub(subname, version=version)

  !-------------------------------------------------------------------
  !  CPU 時間モニターの初期設定
  !  Configure the settings for CPU time monitor
  !-------------------------------------------------------------------
  call DCClockCreate( &
    &         clk_setup, &    ! (out)
    &         'Setup')        ! (in)
  call DCClockCreate( &
    &         clk_histput, &  ! (out)
    &         'HistoryPut')   ! (in)

  call DCClockStart(clk_setup) ! (inout)

  !-------------------------------------------------------------------
  !  物理定数の設定
  !  Configure the physical constants
  !-------------------------------------------------------------------
  call Create( constant = const_earth ) ! (inout)
  call Get( constant = const_earth, &  ! (inout)
    & PI = PI )                         ! (out)

  !-------------------------------------------------------------------
  !  格子点数・最大全波数の設定
  !  Configure the grid points and maximum truncated wavenumber
  !-------------------------------------------------------------------

  !-------------------------
  !  NAMELIST の読み込み
  !  Load NAMELIST
  if ( .not. trim(VAL_namelist) == '' ) then
    call FileOpen( unit = unit_nml, &      ! (out)
      & file = VAL_namelist, mode = 'r' )  ! (in)
    read( unit = unit_nml, & ! (in)
      & nml = init_sample_grid_nml, iostat = iostat_nml ) ! (out)
    if ( iostat_nml == 0 ) then
      call MessageNotify( 'M', subname, &
        & 'NAMELIST group "%c" is loaded from "%c".', &
        & c1='init_sample_grid_nml', c2=trim(VAL_namelist) )
      write(STDOUT, nml = init_sample_grid_nml)
    else
      call MessageNotify( 'W', subname, &
        & 'NAMELIST group "%c" is not found in "%c" (iostat=%d).', &
        & c1='init_sample_grid_nml', c2=trim(VAL_namelist), &
        & i=(/iostat_nml/) )
    end if
    close( unit_nml )
  end if

  !-------------------------------------------------------------------
  !  出力ファイル名の設定
  !  Configure the output filename
  !-------------------------------------------------------------------

  !-------------------------
  !  NAMELIST の読み込み
  !  Load NAMELIST
  if ( .not. trim(VAL_namelist) == '' ) then
    call FileOpen( unit = unit_nml, &      ! (out)
      & file = VAL_namelist, mode = 'r' )  ! (in)
    read( unit = unit_nml, & ! (in)
      & nml = init_sample_file_nml, iostat = iostat_nml ) ! (out)
    if ( iostat_nml == 0 ) then
      call MessageNotify( 'M', subname, &
        & 'NAMELIST group "%c" is loaded from "%c".', &
        & c1='init_sample_file_nml', c2=trim(VAL_namelist) )
      write(STDOUT, nml = init_sample_file_nml)
    else
      call MessageNotify( 'W', subname, &
        & 'NAMELIST group "%c" is not found in "%c" (iostat=%d).', &
        & c1='init_sample_file_nml', c2=trim(VAL_namelist), &
        & i=(/iostat_nml/) )
    end if
    close( unit_nml )
  end if

  !-------------------------------------------------------------------
  !  初期値データ出力の設定
  !  Configure the settings for initial data generation
  !-------------------------------------------------------------------
  call IniDataCreate( ini_dat = ini_dat, &                  ! (inout)
    & nmax = nmax, imax = imax, jmax = jmax, kmax = kmax, & ! (in)
    & nmlfile = VAL_namelist )                              ! (in)

  !-------------------------------------------------------------------
  !  緯度経度データ, 鉛直レベルの設定
  !  (リスタートファイル, ヒストリファイル出力用)
  !  Configure the data of latitude and longitude and vertical level
  !  for output of restart file and history files
  !-------------------------------------------------------------------
  allocate( x_Lon(0:imax-1) )
  allocate( x_Lon_Weight (0:imax-1) )
  allocate( y_Lat(0:jmax-1) )
  allocate( y_Lat_Weight (0:jmax-1) )
  allocate( z_Sigma(0:kmax-1) )
  allocate( r_Sigma(0:kmax) )

  call IniDataGetAxes( ini_dat = ini_dat, &         ! (inout)
    & x_Lon = x_Lon, x_Lon_Weight = x_Lon_Weight, & ! (out)
    & y_Lat = y_Lat, y_Lat_Weight = y_Lat_Weight, & ! (out)
    & z_Sigma = z_Sigma, r_Sigma = r_Sigma )        ! (out)

  !-------------------------------------------------------------------
  !  予報変数の割付
  !  Allocations of prediction variables
  !-------------------------------------------------------------------
  allocate( xyz_U(0:imax-1, 0:jmax-1, 0:kmax-1) )
  allocate( xyz_V(0:imax-1, 0:jmax-1, 0:kmax-1) )
  allocate( xyz_Vor(0:imax-1, 0:jmax-1, 0:kmax-1) )
  allocate( xyz_Div(0:imax-1, 0:jmax-1, 0:kmax-1) )
  allocate( xyz_Temp(0:imax-1, 0:jmax-1, 0:kmax-1) )
  allocate( xyz_QVap(0:imax-1, 0:jmax-1, 0:kmax-1) )
  allocate( xy_Ps(0:imax-1, 0:jmax-1) )

  !-------------------------------------------------------------------
  !  初期値データの取得
  !  Get initial data
  !-------------------------------------------------------------------
  call IniDataGet( ini_dat = ini_dat, &           ! (inout)
    &    xyz_U = xyz_U,       xyz_V = xyz_V, &    ! (out)
    &  xyz_Vor = xyz_Vor,   xyz_Div = xyz_Div, &  ! (out)
    & xyz_Temp = xyz_Temp, xyz_QVap = xyz_QVap, & ! (out)
    &    xy_Ps = xy_Ps )                          ! (out)

  call DCClockStop(clk_setup)   ! (inout)

  !-------------------------------------------------------------------
  !  初期値ファイルへのデータ出力設定
  !  Configure the settings for initial data output
  !-------------------------------------------------------------------
  call DCClockStart(clk_histput)   ! (inout)

  call HistoryCreate( &
    & history = gthist_init, &                           ! (out)
    & file = init_nc, title = title, &                   ! (in)
    & source = source, institution = institution, &      ! (in)
    & dims = StoA('lon', 'lat', 'sig', 'sigm'), &        ! (in)
    & dimsizes = (/imax, jmax, kmax, kmax + 1/), &       ! (in)
    & longnames = &
    &  StoA('longitude', 'latitude', &
    &       'sigma at layer midpoints', &
    &       'sigma at layer end-points (half level)'), & ! (in)
    & units = StoA('degree_east', 'degree_north', &
    &              '1', '1') )                           ! (out)

  call HistoryPut( &
    & history = gthist_init, &                         ! (out)
    & varname = 'lon', array = x_Lon / PI * 180.0_DP ) ! (in)
  call HistoryPut( &
    & history = gthist_init, &                         ! (out)
    & varname = 'lat', array = y_Lat / PI * 180.0_DP ) ! (in)
  call HistoryPut( &
    & history = gthist_init, &           ! (out)
    & varname = 'sig', array = z_Sigma ) ! (in)
  call HistoryPut( &
    & history = gthist_init, &            ! (out)
    & varname = 'sigm', array = r_Sigma ) ! (in)

  call HistoryAddAttr( &
    & history = gthist_init, &                       ! (inout)
    & varname = 'lon', attrname = 'standard_name', & ! (in)
    & value = 'longitude' )                          ! (in)
  call HistoryAddAttr( &
    & history = gthist_init, &                       ! (inout)
    & varname = 'lat', attrname = 'standard_name', & ! (in)
    & value = 'latitude' )                           ! (in)
  call HistoryAddAttr( &
    & history = gthist_init, &                         ! (inout)
    & varname = 'sig', attrname = 'standard_name', &   ! (in)
    & value = 'atmosphere_sigma_coordinate' )          ! (in)
  call HistoryAddAttr( &
    & history = gthist_init, &                         ! (inout)
    & varname = 'sigm', attrname = 'standard_name', &  ! (in)
    & value = 'atmosphere_sigma_coordinate' )          ! (in)
  call HistoryAddAttr( &
    & history = gthist_init, &                    ! (inout)
    & varname = 'sig', attrname = 'positive', &   ! (in)
    & value = 'down' )                            ! (in)
  call HistoryAddAttr( &
    & history = gthist_init, &                    ! (inout)
    & varname = 'sigm', attrname = 'positive', &  ! (in)
    & value = 'down' )                            ! (in)

  call HistoryAddVariable( &
    & history = gthist_init, &                            ! (inout)
    & varname = 'lon_weight', &                           ! (in)
    & dims = StoA('lon'), &                               ! (in)
    & longname = 'weight for integration in longitude', & ! (in)
    & units = 'radian', xtype = 'double' )                ! (in)
  call HistoryAddAttr( &
    & history = gthist_init, &                        ! (inout)
    & varname = 'lon', attrname = 'gt_calc_weight', & ! (in)
    & value = 'lon_weight' )                          ! (in)
  call HistoryPut( &
    & history = gthist_init, &                       ! (inout)
    & varname = 'lon_weight', array = x_Lon_Weight ) ! (in)

  call HistoryAddVariable( &
    & history = gthist_init, &                           ! (inout)
    & varname = 'lat_weight', &                          ! (in)
    & dims = StoA('lat'), &                              ! (in)
    & longname = 'weight for integration in latitude', & ! (in)
    & units = 'radian', xtype = 'double' )               ! (in)
  call HistoryAddAttr( &
    & history = gthist_init, &                        ! (inout)
    & varname = 'lat', attrname = 'gt_calc_weight', & ! (in)
    & value = 'lat_weight' )                          ! (in)
  call HistoryPut( &
    & history = gthist_init, &                       ! (inout)
    & varname = 'lat_weight', array = y_Lat_Weight ) ! (in)

  call HistoryAddVariable( &
    & history = gthist_init, &                      ! (inout)
    & varname = 'U', &                              ! (in)
    & dims = StoA('lon', 'lat', 'sig'), &           ! (in)
    & longname = 'eastward wind', &                 ! (in)
    & units = 'm s-1', xtype = 'double' )           ! (in)
  call HistoryAddAttr(&
    & history = gthist_init, &                       ! (inout)
    & varname = 'U', attrname = 'standard_name', &   ! (in)
    & value = 'eastward_wind' )                      ! (in)

  call HistoryAddVariable( &
    & history = gthist_init, &                      ! (inout)
    & varname = 'V', &                              ! (in)
    & dims = StoA('lon', 'lat', 'sig'), &           ! (in)
    & longname = 'northward wind', &                ! (in)
    & units = 'm s-1', xtype = 'double' )           ! (in)
  call HistoryAddAttr(&
    & history = gthist_init, &                       ! (inout)
    & varname = 'V', attrname = 'standard_name', &   ! (in)
    & value = 'northward_wind' )                     ! (in)

  call HistoryAddVariable( &
    & history = gthist_init, &                      ! (inout)
    & varname = 'Vor', &                            ! (in)
    & dims = StoA('lon', 'lat', 'sig'), &           ! (in)
    & longname = 'vorticity', &                     ! (in)
    & units = 's-1', xtype = 'double' )             ! (in)
  call HistoryAddAttr(&
    & history = gthist_init, &                       ! (inout)
    & varname = 'Vor', attrname = 'standard_name', & ! (in)
    & value = 'atmosphere_relative_vorticity' )      ! (in)

  call HistoryAddVariable( &
    & history = gthist_init, &                      ! (inout)
    & varname = 'Div', &                            ! (in)
    & dims = StoA('lon', 'lat', 'sig'), &           ! (in)
    & longname = 'divergence', &                    ! (in)
    & units = 's-1', xtype = 'double' )             ! (in)
  call HistoryAddAttr(&
    & history = gthist_init, &                       ! (inout)
    & varname = 'Div', attrname = 'standard_name', & ! (in)
    & value = 'divergence_of_wind' )                 ! (in)

  call HistoryAddVariable( &
    & history = gthist_init, &                      ! (inout)
    & varname = 'Temp', &                           ! (in)
    & dims = StoA('lon', 'lat', 'sig'), &           ! (in)
    & longname = 'temperature', &                   ! (in)
    & units = 'K', xtype = 'double' )               ! (in)
  call HistoryAddAttr(&
    & history = gthist_init, &                        ! (inout)
    & varname = 'Temp', attrname = 'standard_name', & ! (in)
    & value = 'air_temperature' )                     ! (in)

  call HistoryAddVariable( &
    & history = gthist_init, &                      ! (inout)
    & varname = 'QVap', &                           ! (in)
    & dims = StoA('lon', 'lat', 'sig'), &           ! (in)
    & longname = 'specific humidity', &             ! (in)
    & units = '1', xtype = 'double' )               ! (in)
  call HistoryAddAttr(&
    & history = gthist_init, &                        ! (inout)
    & varname = 'QVap', attrname = 'standard_name', & ! (in)
    & value = 'specific_humidity' )                   ! (in)

  call HistoryAddVariable( &
    & history = gthist_init, &                ! (inout)
    & varname = 'Ps', &                       ! (in)
    & dims = StoA('lon', 'lat'), &            ! (in)
    & longname = 'surface pressure', &        ! (in)
    & units = 'Pa', xtype = 'double' )        ! (in)
  call HistoryAddAttr(&
    & history = gthist_init, &                      ! (inout)
    & varname = 'Ps', attrname = 'standard_name', & ! (in)
    & value = 'surface_air_pressure' )              ! (in)

  !----------------------------------------------------------------
  !  初期値ファイルへのデータ出力
  !  Initial data output
  !----------------------------------------------------------------
  call HistoryPut( &
    & history = gthist_init, &              ! (inout)
    & varname = 'U', array = xyz_U )        ! (in)
  call HistoryPut( &
    & history = gthist_init, &              ! (inout)
    & varname = 'V', array = xyz_Div )      ! (in)
  call HistoryPut( &
    & history = gthist_init, &              ! (inout)
    & varname = 'Vor', array = xyz_Vor )    ! (in)
  call HistoryPut( &
    & history = gthist_init, &              ! (inout)
    & varname = 'Div', array = xyz_Div )    ! (in)
  call HistoryPut( &
    & history = gthist_init, &                ! (inout)
    & varname = 'Temp', array = xyz_Temp )    ! (in)
  call HistoryPut( &
    & history = gthist_init, &                ! (inout)
    & varname = 'QVap', array = xyz_QVap )    ! (in)
  call HistoryPut( &
    & history = gthist_init, &           ! (inout)
    & varname = 'Ps', array = xy_Ps )    ! (in)

  !----------------------------------------------------------------
  !  初期値ファイルへのデータ出力の終了処理
  !  Terminate initial data output
  !----------------------------------------------------------------
  call HistoryClose( history = gthist_init )  ! (inout)

  call DCClockStop(clk_histput)   ! (inout)

  !----------------------------------------------------------------
  !  ファイル出力に関してメッセージを表示
  !  Print message of file output
  !----------------------------------------------------------------
  call MessageNotify( 'M', subname, &
    & 'Initial data file "%c" is generated.', &
    & c1=trim(init_nc) )

  !----------------------------------------------------------------
  !  CPU 時間の総計を表示
  !  Print total CPU time
  !----------------------------------------------------------------
  call DCClockResult( &
    & clks = (/clk_setup, clk_histput/), &       ! (in)
    & total_auto = .true.)                       ! (in)

  call EndSub(subname)

contains

  subroutine cmdline_optparse
    !
    ! コマンドライン引数の処理を行います
    !
    ! Handle command line options
    !
    call DCArgsOpen( arg = arg )               ! (out)

    call DCArgsHelpMsg( arg = arg, &           ! (inout)
      & category = 'Title', msg = title )      ! (in)
    call DCArgsHelpMsg( arg = arg, &           ! (inout)
      & category = 'Usage', &                  ! (in)
      & msg = './' // trim(subname) // &
      &       ' [Options]' )                   ! (in)
    call DCArgsHelpMsg( arg = arg, &           ! (inout)
      & category = 'Description', &            ! (in)
      & msg = &                                ! (in)
      &   'This program generates an initial data file. ' // &
      &   'By default, the filename is "' // trim(init_nc) // '", and ' // &
      &   'the resolution is T' // trim(toChar(nmax)) // 'L' // trim(toChar(kmax)) // '. ' // &
      &   'In order to change the settings, use NAMELIST file. ' // &
      &   'Some samples are prepared as init_sample_***.nml .' )
    call DCArgsHelpMsg( arg = arg, &           ! (inout)
      & category = 'Source', msg = source )    ! (in)
    call DCArgsHelpMsg( arg = arg, &           ! (inout)
      & category = 'Institution', &            ! (in)
      & msg = institution )                    ! (in)
    call DCArgsOption( arg = arg, &           ! (inout)
      & options = StoA('-N', '--namelist'), & ! (in)
      & flag = OPT_namelist, &                ! (out)
      & value = VAL_namelist, &               ! (out)
      & help = "NAMELIST filename")           ! (in)

    call DCArgsDebug( arg = arg )  ! (inout)
    call DCArgsHelp( arg = arg )   ! (inout)
    call DCArgsStrict( arg = arg ) ! (inout)

    call DCArgsClose( arg = arg )  ! (inout)

  end subroutine cmdline_optparse


end program init_sample
