!= 地表面データ生成モジュール
!
!= Surface data data generation module
!
! Authors::   Yasuhiro MORIKAWA
! Version::   $Id: surface_data.f90,v 1.11 2008-03-02 14:22:09 morikawa Exp $
! Tag Name::  $Name: dcpam4-20080427 $
! Copyright:: Copyright (C) GFD Dennou Club, 2007. All rights reserved.
! License::   See COPYRIGHT[link:../../COPYRIGHT]
!

module surface_data
  !
  != 地表面データ生成モジュール
  !
  != Surface data data generation module
  !
  ! <b>Note that Japanese and English are described in parallel.</b>
  !
  ! GCM で用いる地表面データを生成します.
  ! ファイルへの出力は主プログラムで行うことを想定しています.
  ! 現在は暫定的に Hosaka et al. (1998) の SST 分布を与えます.
  !
  ! Surface data for GCM is generated.
  ! File output is expected to done by a main program.
  ! Now, SST profile in Hosaka et al. (1998) is provided tentatively.
  !
  !== Procedures List
  !
  ! SurfDataCreate        :: SRFDAT 型変数の初期設定
  ! SurfDataGetAxes       :: 座標軸データの取得
  ! SurfDataGet           :: 地表面データの取得
  ! SurfDataClose         :: SRFDAT 型変数の終了処理
  ! SurfDataPutLine       :: SRFDAT 型変数に格納されている情報の印字
  ! SurfDataInitialized   :: SRFDAT 型変数が初期設定されているか否か
  ! ------------  :: ------------
  ! SurfDataCreate        :: Constructor of "SRFDAT"
  ! SurfDataGetAxes       :: Get axes data
  ! SurfDataGet           :: Get surface data
  ! SurfDataClose         :: Deconstructor of "SRFDAT"
  ! SurfDataPutLine       :: Print information of "SRFDAT"
  ! SurfDatainitialized   :: Check initialization of "SRFDAT"
  !
  !== Usage
  !
  ! 始めに, SRFDAT 型の変数を定義し, SurfDataCreate で初期設定を行います.
  ! 初期設定後, SurfDataGet によって地表面データを読み込んでください.
  ! 軸データを読み込む場合には SurfDataGetAxes を用いてください.
  ! 最後に, SRFDAT 型の変数の終了処理を SurfDataClose にて行います.
  !
  ! First, initialize "SRFDAT" by "SurfDataCreate".
  ! Then, get surface data by "SurfDataGet".
  ! If axes data is needed, get it by "SurfDataGetAxes".
  ! Finally, terminate "SRFDAT" by "SurfDataClose".
  !

  use dc_types, only: TOKEN, DP
  implicit none
  private
  public:: SRFDAT, SurfDataCreate, SurfDataGetAxes, SurfDataGet
  public:: SurfDataClose, SurfDataPutLine, SurfDataInitialized

  type SRFDAT
    !
    ! まず, SurfDataCreate で "SRFDAT" 型の変数を初期設定して下さい.
    ! 初期化された "SRFDAT" 型の変数を再度利用する際には,
    ! SurfDataClose によって終了処理を行ってください.
    !
    ! Initialize "SRFDAT" variable by "SurfDataCreate" before usage.
    ! If you reuse "SRFDAT" variable again for another application, 
    ! terminate by "SurfDataClose".
    !
    logical:: initialized = .false.    ! initialization flag
    character(TOKEN):: pattern
                              ! 地表面データのパターン. 
                              ! 以下のパターンを選択可能. 
                              ! 
                              ! Surface data pattern. 
                              ! Available patterns are as follows.
                              ! 
                              ! * "Hosaka et al. (1998)"
                              ! * "Homogeneous"
                              ! 
    integer:: nmax ! 最大全波数. 
                   ! Maximum truncated wavenumber
    integer:: imax ! 経度格子点数. 
                   ! Number of grid points in longitude
    integer:: jmax ! 緯度格子点数. 
                   ! Number of grid points in latitude
    real(DP):: PI        ! $ \pi $ .    円周率.         Circular constant
    real(DP), pointer:: x_Lon (:) =>null()
                              ! 経度. Longitude
    real(DP), pointer:: x_Lon_Weight (:) =>null()
                              ! 経度積分用座標重み. 
                              ! Weight for integration in longitude
    real(DP), pointer:: y_Lat (:) =>null()
                              ! 緯度. Latitude
    real(DP), pointer:: y_Lat_Weight (:) =>null()
                              ! 緯度積分用座標重み. 
                              ! Weight for integration in latitude

    real(DP):: TempBase
                              ! $ T $ . 温度の基本場. Basic state temperature
    real(DP), pointer:: xy_SurfTemp (:,:) =>null()
                              ! 地表面温度. 
                              ! Surface temperature
  end type SRFDAT

  character(*), parameter:: version = &
    & '$Name: dcpam4-20080427 $' // &
    & '$Id: surface_data.f90,v 1.11 2008-03-02 14:22:09 morikawa Exp $'

  !-----------------------------------------------------------------
  !  公開手続
  !  Public procedures
  !-----------------------------------------------------------------

  interface SurfDataCreate
    module procedure SurfDataCreate
  end interface

  interface SurfDataGetAxes
    module procedure SurfDataGetAxes
  end interface

  interface SurfDataGet
    module procedure SurfDataGet
  end interface

  interface SurfDataClose
    module procedure SurfDataClose
  end interface

  interface SurfDataPutLine
    module procedure SurfDataPutLine
  end interface

  interface SurfDataInitialized
    module procedure SurfDataInitialized
  end interface

  !-----------------------------------------------------------------
  !  非公開手続
  !  Private procedures
  !-----------------------------------------------------------------

  interface NmlRead
    module procedure SurfDataNmlRead
  end interface

contains

  subroutine SurfDataCreate( srf_dat, &
    & nmax, imax, jmax, &
    & PI, &
    & TempBase, &
    & pattern, &
    & nmlfile, err )
    !
    ! SRFDAT 型の変数の初期設定を行います.
    ! 他のサブルーチンを使用する前に必ずこのサブルーチンによって
    ! SRFDAT 型の変数を初期設定してください.
    !
    ! オプショナル引数 *PI* は度数をラジアン変換する際に使用されます.
    ! この引数を与えない場合, 
    ! constants モジュールから得られるデフォルト値が使用されます.
    !
    ! なお, 与えられた *srf_dat* が既に初期設定されている場合,
    ! プログラムはエラーを発生させます.
    !
    ! NAMELIST を利用する場合には引数 *nmlfile* に NAMELIST ファイル名
    ! を与えてください. NAMELIST 変数群の詳細に関しては 
    ! NAMELIST#surface_data_nml を参照してください. 
    !
    ! Constructor of "SRFDAT".
    ! Initialize *srf_dat* by this subroutine, 
    ! before other procedures are used, 
    !
    ! Optinal argument *PI* is used for conversion of degree into radian.
    ! If this argument is not given, 
    ! default valuse provided by "constants" module is used instead.
    !
    ! Note that if *srf_dat* is already initialized 
    ! by this procedure, error is occurred.
    !
    ! In order to use NAMELIST, specify a NAMELIST filename to 
    ! argument *nmlfile*. See "NAMELIST#surface_data_nml"
    ! for details about a NAMELIST group.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_types, only: STRING, STDOUT, DP
    use dc_error, only: DC_NOERR, DC_EALREADYINIT, DC_ENEGATIVE, DC_ENOFILEREAD
    use dcpam_error, only: StoreError, DCPAM_EBADPATTERN
    use constants, only: CONST, Create, Get
    use dc_present, only: present_and_not_empty, present_and_true
    use dc_string, only: LChar
    use dc_message, only: MessageNotify
    use w_module, only: w_Initial, &
      & x_Lon_spml => x_Lon, y_Lat_spml => y_Lat, &
      & x_Lon_Weight_spml => x_Lon_Weight, &
      & y_Lat_Weight_spml => y_Lat_Weight
    implicit none
    type(SRFDAT), intent(inout):: srf_dat
    integer, intent(in):: nmax ! 最大全波数. 
                               ! Maximum truncated wavenumber
    integer, intent(in):: imax ! 経度格子点数. 
                               ! Number of grid points in longitude
    integer, intent(in):: jmax ! 緯度格子点数. 
                               ! Number of grid points in latitude
    real(DP), intent(in), optional:: PI  ! $ \pi $ .    円周率.         Circular constant
    real(DP), intent(in), optional:: TempBase
                              ! $ T $ . 温度の基本場. Basic state temperature
    character(*), intent(in), optional:: pattern
                              ! 地表面データのパターン. 
                              ! 以下のパターンを選択可能. 
                              ! 
                              ! Surface data pattern. 
                              ! Available patterns are as follows.
                              ! 
                              ! * "Hosaka et al. (1998)"
                              ! * "Homogeneous"
                              ! 
    character(*), intent(in), optional :: nmlfile
                              ! NAMELIST ファイルの名称. 
                              ! この引数に空文字以外を与えた場合, 
                              ! 指定されたファイルから 
                              ! NAMELIST 変数群を読み込みます. 
                              ! ファイルを読み込めない場合にはエラーを
                              ! 生じます.
                              !
                              ! NAMELIST 変数群の詳細に関しては 
                              ! NAMELIST#surface_data_nml 
                              ! を参照してください. 
                              !
                              ! NAMELIST file name. 
                              ! If nonnull character is specified to
                              ! this argument, 
                              ! NAMELIST group name is loaded from the 
                              ! file. 
                              ! If the file can not be read, 
                              ! an error occurs.
                              ! 
                              ! See "NAMELIST#surface_data_nml" 
                              ! for details about a NAMELIST group.
                              ! 
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 

    !-----------------------------------
    !  作業変数 (Hosaka et al. (1998))
    !  Work variables (Hosaka et al. (1998))
    real(DP):: TempEq         ! 赤道上 (正確には LatCenter 上) での温度.
                              ! Temperature on the equator 
                              ! (on LatCenter, to be exact)
    real(DP):: LatCenter      ! 温度最高の緯度. 
                              ! Latitude on which temperature is maximum.
    real(DP):: LatFlatWidth   ! 温度が平坦化される緯度幅. 
                              ! Latitude width in which temperature is flattened
    integer:: jp
    integer:: jm

    real(DP):: LatA, Alpha, Beta, Gamma

    real(DP):: Phi1, AlphaBeta4, Phi, LatAPlus, LatAMinus
    real(DP):: SurfTempMx
    real(DP):: xy_SurfTemp (0:imax-1, 0:jmax-1)
    real(DP):: y_Lat (0:jmax-1)
                              ! 緯度. Latitude

    !-----------------------------------
    !  作業変数
    !  Work variables
    type(CONST):: const_earth
    integer:: j               ! DO ループ用作業変数
                              ! Work variables for DO loop
    integer:: stat
    character(STRING):: cause_c
    character(*), parameter:: subname = 'SurfDataCreate'
  continue
    call BeginSub(subname, version)
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------
    if (srf_dat % initialized) then
      stat = DC_EALREADYINIT
      cause_c = 'SRFDAT'
      goto 999
    end if

    !-----------------------------------------------------------------
    !  格子点の設定
    !  Configure grid point
    !-----------------------------------------------------------------
    srf_dat % nmax = nmax
    srf_dat % imax = imax
    srf_dat % jmax = jmax

    !-----------------------------------------------------------------
    !  初期値データのパターンを引数から取得
    !  Get initial data pattern from argument
    !-----------------------------------------------------------------
    if ( present(pattern) ) then
      srf_dat % pattern = pattern
    else
      srf_dat % pattern = ''
    end if

    !---------------------------------------------------------
    !  物理定数の準備
    !  Prepare physical constants
    !---------------------------------------------------------
    call Create( const_earth ) ! (inout)
    call Get( constant = const_earth, & ! (inout)
      & PI = srf_dat % PI )             ! (out)

    if ( present(PI) ) srf_dat % PI = PI

    if ( present(TempBase) ) then
      srf_dat % TempBase = TempBase
    else
      srf_dat % TempBase = 302.0_DP
    end if

    !-----------------------------------------------------------------
    !  NAMELIST からの値を取得
    !  Get values from NAMELIST
    !-----------------------------------------------------------------
    if ( present_and_not_empty(nmlfile) ) then
      call MessageNotify( 'M', subname, &
        & 'Loading NAMELIST file "%c" ...', &
        & c1=trim(nmlfile) )
      call NmlRead ( nmlfile = nmlfile, &      ! (in)
!!$        & nmax = srf_dat % nmax, &   ! (inout)
!!$        & imax = srf_dat % imax, &   ! (inout)
!!$        & jmax = srf_dat % jmax, &   ! (inout)
!!$        & PI = srf_dat % PI, &   ! (inout)
        & TempBase = srf_dat % TempBase, & ! (inout)
        & pattern_ = srf_dat % pattern, &  ! (inout)
        & err = err )                          ! (out)
      if ( present_and_true(err) ) then
        call MessageNotify( 'W', subname, &
          & '"%c" can not be read.', &
          & c1=trim(nmlfile) )
        stat = DC_ENOFILEREAD
        cause_c = nmlfile
        goto 999
      end if
    end if

    !-----------------------------------------------------------------
    !  引数の正当性のチェック
    !  Validation of arguments
    !-----------------------------------------------------------------
    if (srf_dat % nmax < 1) then
      stat = DC_ENEGATIVE
      cause_c = 'nmax'
      goto 999
    end if
    if (srf_dat % imax < 1) then
      stat = DC_ENEGATIVE
      cause_c = 'imax'
      goto 999
    end if
    if (srf_dat % jmax < 1) then
      stat = DC_ENEGATIVE
      cause_c = 'jmax'
      goto 999
    end if

    !-----------------------------------------------------------------
    !  地表面データのパターン
    !  Surface data pattern
    !-----------------------------------------------------------------
    if ( trim(srf_dat % pattern) == '' ) then
      srf_dat % pattern = 'Hosaka et al. (1998)'  ! 現在は暫定的に Hosaka et al. (1998) をデフォルトにする
    else
      select case ( LChar( trim(srf_dat % pattern) ) )
      case ( 'hosaka et al. (1998)' )
      case ( 'homogeneous' )
      case default
        stat = DCPAM_EBADPATTERN
        cause_c = trim(srf_dat % pattern)
        goto 999
      end select
    end if

    !-----------------------------------------------------------------
    !  座標軸データ作成
    !  Create axes data
    !-----------------------------------------------------------------
    call w_Initial( srf_dat % nmax, srf_dat % imax, srf_dat % jmax )
    allocate( srf_dat % x_Lon (0:srf_dat%imax-1) )
    srf_dat % x_Lon = x_Lon_spml
    allocate( srf_dat % x_Lon_Weight (0:srf_dat%imax-1) )
    srf_dat % x_Lon_Weight = x_Lon_Weight_spml

    allocate( srf_dat % y_Lat (0:srf_dat%jmax-1) )
    srf_dat % y_Lat = y_Lat_spml
    y_Lat = srf_dat % y_Lat
    allocate( srf_dat % y_Lat_Weight (0:srf_dat%jmax-1) )
    srf_dat % y_Lat_Weight = y_Lat_Weight_spml

    !-----------------------------------------------------------------
    !  地表面データ作成
    !  Create surface data
    !-----------------------------------------------------------------
    select case ( LChar( trim(srf_dat % pattern) ) )
    case ( 'homogeneous' )

      allocate( srf_dat % xy_SurfTemp(0:srf_dat%imax-1, 0:srf_dat%jmax-1) )
      srf_dat % xy_SurfTemp = srf_dat % TempBase

    case ( 'hosaka et al. (1998)' )

      TempEq       = srf_dat % TempBase
      LatCenter    =   0.0_DP
      LatFlatWidth =   7.0_DP

      LatA         =  30.0_DP
      Alpha        =  60.0_DP
      Beta         =  32.0_DP
      Gamma        =   0.0_DP

      Phi1 = abs( LatA * PI / 180.0_DP )
      AlphaBeta4  = 2.0_DP *( Phi1**3 ) * ( Beta / Alpha )

      do j = 0, jmax - 1
        Phi = abs( y_Lat(j) - LatCenter * PI / 180.0_DP )
        xy_SurfTemp (:,j) = &
          & TempEq &
          & - Alpha / 2.0_DP &
          &   * ( Phi - max( sqrt( Phi1**2 + AlphaBeta4 ) - sqrt( ( Phi - Phi1 )**2 + AlphaBeta4 ), 0.0_DP ) ) &
          & + Gamma * ( Phi**3 )
      end do

      !----- 中心 LatCenter +/- LatFlatWidth の間を平坦に ------
      if ( LatFlatWidth < 0.0_DP ) then
        LatFlatWidth = - LatFlatWidth
      end if
      LatAPlus = ( LatCenter + LatFlatWidth ) * PI / 180.0_DP
      LatAMinus = ( LatCenter - LatFlatWidth ) * PI / 180.0_DP

      jp = 0
      jm = jmax - 1
      do  j = 0, jmax - 1
        if ( y_Lat(j) <= LatAPlus ) then
          jp = j
          if ( j == jmax - 1 ) jp = jp - 1
        end if
        if ( y_Lat(j) < LatAMinus ) then
          jm = j
          if ( j == jmax - 1 ) jm = jm - 1
        end if
      end do

      SurfTempMx = &
        & (   xy_SurfTemp(1,jm) * ( y_Lat(jm+1) - LatAMinus ) &
        &   + xy_SurfTemp(1,jm+1) * ( LatAMinus - y_Lat(jm) ) &
        & ) &
        & / ( y_Lat(jm+1) - y_Lat(jm) )

      xy_SurfTemp(:,jm+1:jp) = SurfTempMx

      allocate( srf_dat % xy_SurfTemp(0:srf_dat%imax-1, 0:srf_dat%jmax-1) )
      srf_dat % xy_SurfTemp = xy_SurfTemp

    end select

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
    srf_dat % initialized = .true.
999 continue
    call StoreError(stat, subname, err, cause_c)
    call EndSub(subname)
  end subroutine SurfDataCreate

  subroutine SurfDataGetAxes( srf_dat, &
    & x_Lon, x_Lon_Weight, y_Lat, y_Lat_Weight, &
    & err )
    !
    ! 座標軸データを返します.
    !
    ! なお, 与えられた *srf_dat* が Create によって初期設定
    ! されていない場合, プログラムはエラーを発生させます.
    !
    ! Return axes data.
    !
    ! If *srf_dat* is not initialized by "Create" yet,
    ! error is occurred.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_types, only: STRING, STDOUT, DP
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
    implicit none
    type(SRFDAT), intent(inout):: srf_dat
    real(DP), intent(out), optional:: x_Lon (0:srf_dat % imax-1)
                              ! 経度. Longitude
    real(DP), intent(out), optional:: x_Lon_Weight (0:srf_dat%imax-1)
                              ! 経度積分用座標重み. 
                              ! Weight for integration in longitude
    real(DP), intent(out), optional:: y_Lat (0:srf_dat % jmax-1)
                              ! 緯度. Latitude
    real(DP), intent(out), optional:: y_Lat_Weight (0:srf_dat%jmax-1)
                              ! 緯度積分用座標重み. 
                              ! Weight for integration in latitude
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 

    integer:: stat
    character(STRING):: cause_c
    character(*), parameter:: subname = 'SurfDataGetAxes'
  continue
    call BeginSub(subname)
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------
    if (.not. srf_dat % initialized) then
      stat = DC_ENOTINIT
      cause_c = 'SRFDAT'
      goto 999
    end if

    !-----------------------------------------------------------------
    !  地表面データの取り出し
    !  Fetch surface data
    !-----------------------------------------------------------------
    if ( present(x_Lon       ) ) x_Lon        = srf_dat % x_Lon
    if ( present(x_Lon_Weight) ) x_Lon_Weight = srf_dat % x_Lon_Weight
    if ( present(y_Lat       ) ) y_Lat        = srf_dat % y_Lat
    if ( present(y_Lat_Weight) ) y_Lat_Weight = srf_dat % y_Lat_Weight

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
999 continue
    call StoreError(stat, subname, err, cause_c)
    call EndSub(subname)
  end subroutine SurfDataGetAxes


  subroutine SurfDataGet( srf_dat, &
    & xy_SurfTemp, &
    & err )
    !
    ! GCM 用の地表面データを返します.
    !
    ! なお, 与えられた *srf_dat* が Create によって初期設定
    ! されていない場合, プログラムはエラーを発生させます.
    !
    ! Return surface data for GCM.
    !
    ! If *srf_dat* is not initialized by "Create" yet,
    ! error is occurred.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_types, only: STRING, STDOUT, DP
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
    implicit none
    type(SRFDAT), intent(inout):: srf_dat
    real(DP), intent(out):: xy_SurfTemp (0:srf_dat%imax-1, 0:srf_dat%jmax-1)
                              ! 地表面温度. 
                              ! Surface temperature
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 

    integer:: stat
    character(STRING):: cause_c
    character(*), parameter:: subname = 'SurfDataGet'
  continue
    call BeginSub(subname)
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------
    if (.not. srf_dat % initialized) then
      stat = DC_ENOTINIT
      cause_c = 'SRFDAT'
      goto 999
    end if

    !-----------------------------------------------------------------
    !  地表面データの取り出し
    !  Fetch surface data
    !-----------------------------------------------------------------
    xy_SurfTemp = srf_dat % xy_SurfTemp

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
999 continue
    call StoreError(stat, subname, err, cause_c)
    call EndSub(subname)
  end subroutine SurfDataGet

  subroutine SurfDataClose( srf_dat, err )
    !
    ! SRFDAT 型の変数の終了処理を行います.
    ! なお, 与えられた *srf_dat* が Create によって初期設定
    ! されていない場合, プログラムはエラーを発生させます.
    !
    ! Deconstructor of "SRFDAT".
    ! Note that if *srf_dat* is not initialized by "Create" yet,
    ! error is occurred.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_types, only: STRING, STDOUT
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
    implicit none
    type(SRFDAT), intent(inout):: srf_dat
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 
    integer:: stat
    character(STRING):: cause_c
    character(*), parameter:: subname = 'SurfDataClose'
  continue
    call BeginSub(subname)
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------
    if (.not. srf_dat % initialized) then
      stat = DC_ENOTINIT
      cause_c = 'SRFDAT'
      goto 999
    end if

    !-----------------------------------------------------------------
    !  "SRFDAT" の設定の消去
    !  Clear the settings for "DYNSP"
    !-----------------------------------------------------------------
    deallocate( srf_dat % xy_SurfTemp )
    deallocate( srf_dat % x_Lon )
    deallocate( srf_dat % x_Lon_Weight )
    deallocate( srf_dat % y_Lat )
    deallocate( srf_dat % y_Lat_Weight )

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
    srf_dat % initialized = .false.
999 continue
    call StoreError(stat, subname, err, cause_c)
    call EndSub(subname)
  end subroutine SurfDataClose

  subroutine SurfDataPutLine( srf_dat, unit, indent, err )
    !
    ! 引数 *srf_dat* に設定されている情報を印字します.
    ! デフォルトではメッセージは標準出力に出力されます. 
    ! *unit* に装置番号を指定することで, 出力先を変更することが可能です.
    !
    ! Print information of *srf_dat*.
    ! By default messages are output to standard output.
    ! Unit number for output can be changed by *unit* argument.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_types, only: STRING, STDOUT
    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
    use dc_string, only: Printf, PutLine
    implicit none
    type(SRFDAT), intent(inout):: srf_dat
    integer, intent(in), optional:: unit
                              ! 出力先の装置番号.
                              ! デフォルトの出力先はは標準出力.
                              !
                              ! Unit number for output.
                              ! Default value is standard output.
    character(*), intent(in), optional:: indent
                              ! 表示されるメッセージの字下げ.
                              !
                              ! Indent of displayed messages.
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 
    integer:: stat
    character(STRING):: cause_c
    integer:: out_unit
    integer:: indent_len
    character(STRING):: indent_str
    character(*), parameter:: subname = 'SurfDataPutLine'
  continue
    call BeginSub(subname)
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  初期設定のチェック
    !  Check initialization
    !-----------------------------------------------------------------
    if (present(unit)) then
      out_unit = unit
    else
      out_unit = STDOUT
    end if

    indent_len = 0
    indent_str = ''
    if (present(indent)) then
      if (len(indent) /= 0) then
        indent_len = len(indent)
        indent_str(1:indent_len) = indent
      end if
    end if


    !-----------------------------------------------------------------
    !  "SRFDAT" の設定の印字
    !  Print the settings for "SRFDAT"
    !-----------------------------------------------------------------
    if (srf_dat % initialized) then
      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & '#<SRFDAT:: @initialized=%y @pattern="%c"', &
        & c1 = trim( srf_dat % pattern ), &
        & l = (/srf_dat % initialized/))

      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & ' @nmax=%d @imax=%d @jmax=%d', &
        & i = (/srf_dat % nmax, srf_dat % imax, srf_dat % jmax/) )

      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & ' @PI=%f', &
        & d = (/srf_dat % PI/) )

      call PutLine( srf_dat % x_Lon, unit = out_unit, &
        & lbounds = lbound(srf_dat % x_Lon), &
        & ubounds = ubound(srf_dat % x_Lon), &
        & indent = indent_str(1:indent_len) // &
        & ' @x_Lon=' )

      call PutLine( srf_dat % y_Lat, unit = out_unit, &
        & lbounds = lbound(srf_dat % y_Lat), &
        & ubounds = ubound(srf_dat % y_Lat), &
        & indent = indent_str(1:indent_len) // &
        & ' @y_Lat=' )

      call PutLine( srf_dat % xy_SurfTemp, unit = out_unit, &
        & lbounds = lbound(srf_dat % xy_SurfTemp), &
        & ubounds = ubound(srf_dat % xy_SurfTemp), &
        & indent = indent_str(1:indent_len) // &
        & ' @xy_SurfTemp=' )

      call Printf(out_unit, &
        & indent_str(1:indent_len) // &
        & '>' )
    else
      call Printf( out_unit, &
        & indent_str(1:indent_len) // &
        & '#<SRFDAT:: @initialized=%y>', &
        & l = (/srf_dat % initialized/))
    end if

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
999 continue
    call StoreError(stat, subname, err, cause_c)
    call EndSub(subname)
  end subroutine SurfDataPutLine

  logical function SurfDataInitialized( srf_dat ) result(result)
    !
    ! *srf_dat* が初期設定されている場合には .true. が,
    ! 初期設定されていない場合には .false. が返ります.
    !
    ! If *srf_dat* is initialized, .true. is returned.
    ! If *srf_dat* is not initialized, .false. is returned.
    !
    implicit none
    type(SRFDAT), intent(in):: srf_dat
  continue
    result = srf_dat % initialized
  end function SurfDataInitialized

  subroutine SurfDataNmlRead( nmlfile, &
!!$    & nmax, imax, jmax, &
!!$    & PI, &
    & TempBase, &
    & pattern_, &
    & err )
    !
    ! NAMELIST ファイル *nmlfile* から値を入力するための
    ! 内部サブルーチンです. Create 内で呼び出されることを
    ! 想定しています.
    !
    ! 値が NAMELIST ファイル内で指定されていない場合には,
    ! 入力された値がそのまま返ります.
    !
    ! なお, *nmlfile* に空文字が与えられた場合, または
    ! 与えられた *nmlfile* を読み込むことができない場合, 
    ! プログラムはエラーを発生させます.
    !
    ! This is an internal subroutine to input values from 
    ! NAMELIST file *nmlfile*. This subroutine is expected to be
    ! called by "Create".
    !
    ! A value not specified in NAMELIST file is returned
    ! without change.
    !
    ! If *nmlfile* is empty, or *nmlfile* can not be read, 
    ! error is occurred.
    !
    use dc_trace, only: BeginSub, EndSub
    use dc_types, only: DP, STRING, TOKEN, STDOUT
    use dc_iounit, only: FileOpen
    use dc_message, only: MessageNotify
    use dc_present, only: present_and_true
    use dc_error, only: StoreError, DC_NOERR, DC_ENOFILEREAD
    implicit none
    character(*), intent(in):: nmlfile
                              ! NAMELIST ファイルの名称. 
                              ! NAMELIST file name
!!$    integer, intent(inout):: nmax ! 最大全波数. 
!!$                               ! Maximum truncated wavenumber
!!$    integer, intent(inout):: imax ! 経度格子点数. 
!!$                               ! Number of grid points in longitude
!!$    integer, intent(inout):: jmax ! 緯度格子点数. 
!!$                               ! Number of grid points in latitude
!!$    real(DP), intent(inout), optional:: PI        ! $ \pi $ .    円周率.         Circular constant
    real(DP), intent(inout):: TempBase
                              ! $ T $ . 温度の基本場. Basic state temperature
    character(*), intent(inout):: pattern_
    character(TOKEN):: pattern
                              ! 地表面データのパターン. 
                              ! 以下のパターンを選択可能. 
                              ! 
                              ! Surface data pattern. 
                              ! Available patterns are as follows.
                              ! 
                              ! * "Hosaka et al. (1998)"
                              ! * "Homogeneous"
                              ! 
    logical, intent(out), optional:: err
                              ! 例外処理用フラグ.
                              ! デフォルトでは, この手続き内でエラーが
                              ! 生じた場合, プログラムは強制終了します.
                              ! 引数 *err* が与えられる場合,
                              ! プログラムは強制終了せず, 代わりに
                              ! *err* に .true. が代入されます.
                              !
                              ! Exception handling flag. 
                              ! By default, when error occur in 
                              ! this procedure, the program aborts. 
                              ! If this *err* argument is given, 
                              ! .true. is substituted to *err* and 
                              ! the program does not abort. 

    namelist /surface_data_nml/ &
!!$      & nmax, imax, jmax, &
!!$      & PI, &
      & TempBase, &
      & pattern
                              ! surface_data モジュール用
                              ! NAMELIST 変数群名.
                              !
                              ! surface_data#Create を使用する際に, 
                              ! オプショナル引数 *nmlfile* へ NAMELIST 
                              ! ファイル名を指定することで, そのファイルから
                              ! この NAMELIST 変数群を読み込みます.
                              !
                              ! NAMELIST group name for
                              ! "surface_data" module.
                              ! 
                              ! If a NAMELIST filename is specified to 
                              ! an optional argument *nmlfile* 
                              ! when "surface_data#Create" is used, 
                              ! this NAMELIST group is loaded from 
                              ! the file.

    !-----------------------------------
    !  作業変数
    !  Work variables
    integer:: stat
    character(STRING):: cause_c
    integer:: unit_nml        ! NAMELIST ファイルオープン用装置番号. 
                              ! Unit number for NAMELIST file open
    integer:: iostat_nml      ! NAMELIST 読み込み時の IOSTAT. 
                              ! IOSTAT of NAMELIST read
    character(*), parameter:: subname = 'SurfDataNmlRead'
  continue
    call BeginSub( subname )
    stat = DC_NOERR
    cause_c = ''

    !-----------------------------------------------------------------
    !  文字型引数を NAMELIST 変数群へ代入
    !  Substitute character arguments to NAMELIST group
    !-----------------------------------------------------------------
    pattern = pattern_

    !----------------------------------------------------------------
    !  NAMELIST ファイルのオープン
    !  Open NAMELIST file
    !----------------------------------------------------------------
    call FileOpen( unit = unit_nml, & ! (out)
      & file = nmlfile, mode = 'r', & ! (in)
      & err = err )                   ! (out)
    if ( present_and_true(err) ) then
      stat = DC_ENOFILEREAD
      cause_c = nmlfile
      goto 999
    end if


    !-----------------------------------------------------------------
    !  NAMELIST 変数群の取得
    !  Get NAMELIST group
    !-----------------------------------------------------------------
    read( unit = unit_nml, & ! (in)
      & nml = surface_data_nml, iostat = iostat_nml ) ! (out)
    if ( iostat_nml == 0 ) then
      call MessageNotify( 'M', subname, &
        & 'NAMELIST group "%c" is loaded from "%c".', &
        & c1='surface_data_nml', c2=trim(nmlfile) )
      write(STDOUT, nml = surface_data_nml)
    else
      call MessageNotify( 'W', subname, &
        & 'NAMELIST group "%c" is not found in "%c" (iostat=%d).', &
        & c1='surface_data_nml', c2=trim(nmlfile), &
        & i=(/iostat_nml/) )
    end if

    close( unit_nml )

    !-----------------------------------------------------------------
    !  NAMELIST 変数群を文字型引数へ代入
    !  Substitute NAMELIST group to character arguments
    !-----------------------------------------------------------------
    pattern_ = pattern

    !-----------------------------------------------------------------
    !  終了処理, 例外処理
    !  Termination and Exception handling
    !-----------------------------------------------------------------
999 continue
    call StoreError( stat, subname, err, cause_c )
    call EndSub( subname )
  end subroutine SurfDataNmlRead

!!$  subroutine SurfDataSample( srf_dat, err )
!!$    !--
!!$    ! SurfDataSample の要約を記述してください.
!!$    !++
!!$    ! なお, 与えられた *srf_dat* が Create によって初期設定
!!$    ! されていない場合, プログラムはエラーを発生させます.
!!$    !--
!!$    ! Describe brief of SurfDataSample
!!$    !++
!!$    ! If *srf_dat* is not initialized by "Create" yet,
!!$    ! error is occurred.
!!$    !
!!$    use dc_trace, only: BeginSub, EndSub
!!$    use dc_types, only: DP, STRING, TOKEN, STDOUT
!!$    use dc_error, only: StoreError, DC_NOERR, DC_ENOTINIT
!!$    implicit none
!!$    type(SRFDAT), intent(inout):: srf_dat
!!$    logical, intent(out), optional:: err
!!$                              ! 例外処理用フラグ.
!!$                              ! デフォルトでは, この手続き内でエラーが
!!$                              ! 生じた場合, プログラムは強制終了します.
!!$                              ! 引数 *err* が与えられる場合,
!!$                              ! プログラムは強制終了せず, 代わりに
!!$                              ! *err* に .true. が代入されます.
!!$                              !
!!$                              ! Exception handling flag. 
!!$                              ! By default, when error occur in 
!!$                              ! this procedure, the program aborts. 
!!$                              ! If this *err* argument is given, 
!!$                              ! .true. is substituted to *err* and 
!!$                              ! the program does not abort. 
!!$
!!$!!$    integer:: param_i
!!$!!$    real(DP):: param_r
!!$!!$    character(STRING):: param_c
!!$
!!$    !-----------------------------------
!!$    !  作業変数
!!$    !  Work variables
!!$    integer:: stat
!!$    character(STRING):: cause_c
!!$    character(*), parameter:: subname = 'SurfDataSample'
!!$  continue
!!$    call BeginSub( subname )
!!$    stat = DC_NOERR
!!$    cause_c = ''
!!$
!!$    !-----------------------------------------------------------------
!!$    !  初期設定のチェック
!!$    !  Check initialization
!!$    !-----------------------------------------------------------------
!!$    if ( .not. srf_dat % initialized ) then
!!$      stat = DC_ENOTINIT
!!$      cause_c = 'SRFDAT'
!!$      goto 999
!!$    end if
!!$
!!$    !-----------------------------------------------------------------
!!$    !  *srf_dat* に格納されている設定値の取り出し
!!$    !  Fetch setting values stored in *srf_dat*
!!$    !-----------------------------------------------------------------
!!$!!$    param_i = srf_dat % param_i
!!$!!$    param_r = srf_dat % param_r
!!$!!$    param_c = srf_dat % param_c
!!$
!!$
!!$    !-----------------------------------------------------------------
!!$    !  終了処理, 例外処理
!!$    !  Termination and Exception handling
!!$    !-----------------------------------------------------------------
!!$999 continue
!!$    call StoreError( stat, subname, err, cause_c )
!!$    call EndSub( subname )
!!$  end subroutine SurfDataSample


end module surface_data

