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

recursive subroutine ANVarOpen(var, url, writable, err)
    use dc_types, only: string
    use an_types
    use an_vartable, only: vtable_add
    use an_file
    use dc_url
    use dc_error
    use dc_trace, only: beginsub, endsub
    use netcdf_f77
    implicit none
    type(AN_VARIABLE), intent(out):: var
    character(len = string), intent(in):: url
    logical, intent(in), optional:: writable
    logical, intent(out), optional:: err
    character(len = string):: filename, varname
    character(len = NF_MAX_NAME):: dimname
    integer:: stat, nvars, i
    type(an_variable_search):: e
continue
    call beginsub('anvaropen')
    call UrlSplit(url, file=filename, var=varname)
    if (filename == "") filename = "gtool.nc"
    call ANFileOpen(e%fileid, trim(filename), stat=stat, writable=writable)
    if (stat /= 0) goto 999
    !
    ! 名前から変数を探し出す
    !
    if (varname /= '') then
        e%varid = 0
        stat = nf_inq_varid(e%fileid, trim(varname), e%varid)
        if (stat == NF_ENOTVAR) then
            e%varid = 0
            stat = NF_NOERR
        endif
    else
        ! 名前が空ならできれば次元変数でない最初の変数をとりだす
        stat = nf_inq_nvars(e%fileid, nvars)
        if (stat /= 0) goto 999
        e%varid = 1
        do, i = 1, nvars
            stat = nf_inq_varname(e%fileid, i, dimname)
            if (stat /= NF_NOERR) goto 999
            stat = nf_inq_dimid(e%fileid, dimname, e%dimid)
            if (stat == NF_NOERR) cycle
            if (stat /= NF_EBADDIM) goto 999
            e%varid = i
            stat = NF_NOERR
            exit
        enddo
    endif
    if (stat /= NF_NOERR) goto 999
    !
    ! 次元id を調べる
    !
    stat = nf_inq_dimid(e%fileid, trim(varname), e%dimid)
    if (stat /= NF_NOERR) then
        if (e%varid <= 0) goto 999
        e%dimid = 0
    endif
    !
    stat = vtable_add(var, e)
    if (stat /= NF_NOERR) goto 999
    call endsub('anvaropen', 'an=%d file=%d var=%d', i=(/var%id, e%fileid, e%varid/))
    call StoreError(stat, 'ANVarOpen', err)
    return
    !
    ! エラー処理 (正常完了時も呼ぶ)
    !
999 continue
    var = an_variable(-1)
    call endsub('anvaropen', 'an=%d err', i=(/var%id/))
    call StoreError(stat, 'ANVarOpen', err, cause_c=url)
end subroutine
