!
!= netCDF ファイルへ次元変数作成
!
! Authors::   Eizi TOYODA, Yasuhiro MORIKAWA
! Version::   $Id: anvarcreated.f90,v 1.2 2006/01/22 16:30:47 morikawa Exp $
! Tag Name::  $Name: gt4f90io-20060123 $
! Copyright:: Copyright (C) GFD Dennou Club, 2000-2005. All rights reserved.
! License::   See COPYRIGHT[link:../../COPYRIGHT]
!
! 以下のサブルーチン、関数は an_generic から an_generic#Create
! として提供されます。

subroutine ANVarCreateD(var, url, xtype, length, overwrite, err)
  !
  !== 次元変数 create
  !
  ! create(var, url, xtype, length, [overwrite], [err]) は
  ! 長さ length の次元変数を作成すします。
  !
  use an_types, only: an_variable, an_variable_search
  use an_vartable, only: vtable_add
  use dc_string, only: strieq
  use dc_types, only: string
  use dc_url, only: UrlSplit
  use netcdf_f77, only: nf_noerr, nf_real, nf_int, nf_double, &
    & nf_def_var, nf_def_dim
  use an_file, only: anfileopen, anfiledefinemode
  use dc_error, only: StoreError, gt_enomem
  implicit none
  type(an_variable), intent(out):: var
  character(len = *), intent(in):: url
  character(len = *), intent(in):: xtype
  integer, intent(in):: length
  logical, intent(in), optional:: overwrite
  logical, intent(out), optional:: err
  type(an_variable_search):: ent
  character(len = string):: filename, varname, cause_c
  integer:: stat
  integer:: nc_xtype
  character(len = *), parameter:: subname = "ANVarCreateD"
continue
  cause_c = trim(url)
  !
  ! --- ファイルを用意 ---
  call UrlSplit(url, file=filename, var=varname)
  call ANFileOpen(ent%fileid, filename, stat=stat, writable=.TRUE., &
    & overwrite=overwrite)
  if (stat /= NF_NOERR) goto 999
  stat = ANFileDefineMode(ent%fileid)
  if (stat /= NF_NOERR) goto 999
  !
  ! --- 型の決定 ---
  nc_xtype = NF_REAL
  if (strieq(xtype, "double") .or. &
    & strieq(xtype, "DOUBLEPRECISION")) then
    nc_xtype = NF_DOUBLE
  endif
  if (strieq(xtype, "int") .or. strieq(xtype, "INTEGER")) then
    nc_xtype = NF_INT
  endif
  !
  ! --- 次元変数の作成 ---
  stat = nf_def_dim(ent%fileid, trim(varname), len=length, &
    & dimid=ent%dimid)
  if (stat /= NF_NOERR) goto 999
  stat = nf_def_var(ent%fileid, trim(varname), &
    & xtype=nc_xtype, ndims=1, dimids=(/ent%dimid/), varid=ent%varid)
  if (stat /= NF_NOERR) goto 999
  !
  stat = vtable_add(var, ent)
  if (stat /= NF_NOERR) goto 999

999 continue
  call StoreError(stat, subname, err, cause_c=cause_c)
  if (stat /= NF_NOERR) var = an_variable(-1)
end subroutine ANVarCreateD
