! gtvaropen.f90 - gtool4 file interface
! Copyright (C) GFD Dennou Club, 2000.  All rights reserved

subroutine GTVarOpen(var, url, writable, err)
    use dc_string, only: StrHead
    use dc_types, only: string
    use gtdata_types, only: GT_VARIABLE
    use gtdata_generic, only: limit
    use gt_map, only: map_create, vtb_class_netcdf, vtb_class_memory, gtvar_dump
    use an_generic, only: ANVarOpen, an_variable, inquire
    use dc_url, only: url_chop_iorange
    use dc_error, only: StoreError, GT_EFAKE
    use dc_trace, only: beginsub, endsub
    implicit none
    type(GT_VARIABLE), intent(inout):: var
    character(*), intent(in):: url
    logical, intent(in), optional:: writable
    logical, intent(out), optional:: err
    integer:: ndims
    integer, allocatable:: dimlen(:)
    type(an_variable):: an
    character(len = string):: filevar, iorange
continue
    call beginsub('gtvaropen', fmt='<%c>', c1=trim(url))
    call url_chop_iorange(url, iorange=iorange, remainder=filevar)
    if (StrHead(filevar, "memory:")) then
        call StoreError(GT_EFAKE, "GTVarOpen(memory:)", err)
        var = gt_variable(-1)
    else
        call ANVarOpen(an, filevar, writable, err)
        call inquire(an, ndims=ndims)
        allocate(dimlen(max(1, ndims)))
        call inquire(an, dimlen=dimlen)
        call map_create(var, vtb_class_netcdf, an%id, ndims, dimlen)
        deallocate(dimlen)
    endif
    call limit(var, trim(iorange))
    call gtvar_dump(var)
    call endsub('gtvaropen', 'mapid=%d', i=(/var%mapid/))
end subroutine
