! ansearchdim.f90 - search_dim(an_variable, name)
! Copyright (C) GFD Dennou Club, 2001.  All rights reserved
!
integer function an_search_dim(var, name) result(result)
    use an_types, only: AN_VARIABLE, an_variable_entry, an_variable_search
    use an_vartable, only: vtable_lookup
    use an_file
    use netcdf_f77
    use dc_error
    use dc_trace, only: beginsub, endsub
    implicit none
    type(AN_VARIABLE), intent(in):: var
    character(len = *), intent(in):: name
    type(an_variable_entry):: ent
    integer:: stat, dimid, i
continue
    call beginsub('an_search_dim', 'var=%d name=%c', i=(/var%id/), c1=trim(name))
    result = nf_ebaddim
    stat = vtable_lookup(var, ent)
    if (stat /= NF_NOERR) goto 999

    stat = nf_inq_dimid(ent%fileid, name, dimid)
    if (stat /= NF_NOERR) goto 999

    if (dimid == ent%dimid) then
        result = 1
        goto 999
    endif

    if (.not. associated(ent%dimids)) then
        stat = gt_enomoredims
        goto 999
    endif
    do, i = 1, size(ent%dimids)
        if (ent%dimids(i) == dimid) then
            result = i
            goto 999
        endif
    enddo

999 continue
    call endsub('an_search_dim', 'result=%d', i=(/result/))
    return
end function
