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

subroutine ANVarInquire(var, xtype, ndims, alldims, name, url, allcount)
    use an_types, only: AN_VARIABLE
    use an_generic, only: ANXTypeName
    use an_file, only: ANFileName
    use dc_string, only: VSTRING, assignment(=), var_str
    use dc_url, only: UrlMerge
    use netcdf_f77
    implicit none
    type(AN_VARIABLE), intent(in):: var
    type(VSTRING), intent(out), optional:: xtype, name, url
    integer, intent(out), optional:: ndims, alldims, allcount
    integer:: stat, i_xtype
    character(len = NF_MAX_NAME):: varname
    intrinsic count
    if (present(xtype)) then
        stat = nf_inq_vartype(var%fileid, var%varid, xtype=i_xtype)
        if (stat /= NF_NOERR) i_xtype = 0
        call ANXTypeName(i_xtype, xtype)
    endif
    if (present(ndims)) then
        if (associated(var%count)) then
            ndims = count(var%count > 1)
        else
            ndims = 0
        endif
    endif
    if (present(alldims)) then
        if (associated(var%count)) then
            alldims = size(var%count)
        else
            alldims = 0
        endif
    endif
    if (present(name)) then
        call getname(var, varname)
        name = trim(varname)
    endif
    if (present(url)) then
        call getname(var, varname)
        url = UrlMerge(file=ANFileName(var%fileid), var=var_str(trim(varname)))
    endif
    if (present(allcount)) then
        if (.not. associated(var%allcount)) then
            allcount = -1
        else if (size(var%allcount) == 1) then
            allcount = var%allcount(1)
            if (var%growable == 1) allcount = 0
        else
            allcount = -1
        endif
    endif
    return
contains

    subroutine getname(var, name)
        type(AN_VARIABLE), intent(in):: var
        character(len = *), intent(out):: name
        if (var%varid > 0) then
            stat = nf_inq_varname(var%fileid, var%varid, varname)
        else
            stat = nf_inq_dimname(var%fileid, var%dimid, varname)
        endif
        if (stat /= NF_NOERR) varname = ""
        name = trim(varname)
    end subroutine

end subroutine
