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

! あるファイル名 urlBase に依存する変数すべてを取得するにはまず
! var_search(iter, urlbase) を呼び出してから無限ループの中で
! attr_next(iter, url, end) を呼び出す。url がひとつ
! ひとつの属性名を与える。end が真にになったとき、
! すべての属性を探索し終えたことになる。

subroutine ANVarSearchInit(iter, urlBase)
    use dc_types, only: string
    use an_types, only: AN_VARIABLE_SEARCH
    use dc_url, only: UrlSplit
    use an_file, only: ANFileOpen
    use dc_trace, only: beginsub, endsub, message
    implicit none
    type(AN_VARIABLE_SEARCH), intent(out):: iter
    character(len = *), intent(in):: urlBase
    character(len = string):: file
    logical:: err
    call beginsub('anvarsearchinit', 'urlbase=<%c>', c1=trim(urlbase))
    call UrlSplit(trim(urlbase), file=file)
    call ANFileOpen(iter%fileid, filename=file, writable=.FALSE., err=err)
    if (err) iter%fileid = -1
    iter%varid = 0
    iter%dimid = 0 
    call endsub('anvarsearchinit', 'file=%d', i=(/iter%fileid/))
end subroutine

subroutine ANVarSearchNext(iter, url, end)
    use an_types, only: AN_VARIABLE_SEARCH
    use dc_types, only: string
    use netcdf_f77
    use dc_url, only: UrlMerge
    use an_file, only: inquire, AnFileClose
    use dc_trace, only: beginsub, endsub, message
    implicit none
    type(AN_VARIABLE_SEARCH), intent(inout):: iter
    character(len = *), intent(out):: url
    logical, intent(out):: end
    character(len = string):: filename
    character(len = NF_MAX_NAME):: varname
    integer:: stat, varid_tmp
continue
    call beginsub('anvarsearchnext')
    if (iter%fileid <= 0) then
        end = .TRUE.
        url = ''
        call endsub('anvarsearchnext', "bad file %d", i=(/iter%fileid/))
        return
    endif
    if (iter%varid >= 0) then
        iter%varid = iter%varid + 1
        stat = NF_INQ_VARNAME(iter%fileid, iter%varid, varname)
        if (stat == NF_NOERR) goto 900
        iter%varid = -1
    endif
    do while (iter%dimid >= 0)
        iter%dimid = iter%dimid + 1
        ! --- 指定番号の次元がなければエラー ---
        stat = NF_INQ_DIMNAME(iter%fileid, iter%dimid, varname)
        if (stat /= NF_NOERR) exit
        ! --- 指定番号の次元と同名の変数があれば却下、次番号へ ---
        stat = NF_INQ_VARID(iter%fileid, varname, varid_tmp)
        if (stat /= NF_NOERR) goto 900
    enddo
    end = .TRUE.
    url = ""
    call ANFileClose(iter%fileid)
    iter%dimid = -1
    call endsub('anvarsearchnext', "end file %d", i=(/iter%fileid/))
    return

900 continue
    call inquire(iter%fileid, name=filename)
    url = UrlMerge(file=trim(filename), var=trim(varname))
    end = .FALSE.
    call endsub('anvarsearchnext', "file=%d url=<%c>", &
        & i=(/iter%fileid/), c1=trim(url))
    return
end subroutine
