! Copyright (C) GFD Dennou Club, 2000.  All rights reserved.

!
! 次元変数 create
!
! create(var, url, xtype, length, [overwrite], [err]) は
! 長さ length の次元変数を作成する。
!
subroutine ANVarCreateD(var, url, xtype, length, overwrite, err)
    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
    integer:: stat
    integer:: nc_xtype
    !
    ! --- ファイルを用意 ---
    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
    call StoreError(NF_NOERR, 'ANVarCreateD', err)
    return

999 continue
    call StoreError(stat, 'ANVarCreateD', err)
    var = an_variable(-1)
end subroutine
