! gtvarclose.f90
! Copyright (C) TOYODA Eizi, 2000.  All rights reserved.

subroutine GTVarClose(var, err)
    use gtdata_types, only: GT_VARIABLE
    use gt_map, only: vtb_class_netcdf, vtb_class_memory, &
        & maptabdelete, map_lookup
    use gt_vartable, only: vartabledelete, vartablelookup
    use an_generic, only: ANVarClose, an_variable
    use dc_error, only: StoreError, GT_EBADVAR, nf_enotvar, dc_noerr
    use dc_trace, only: beginsub, endsub, message
    use gt_mem
    implicit none
    type(GT_VARIABLE), intent(in), target:: var
    logical, intent(out), optional:: err
    integer:: vid, class, cid
    logical:: action, myerr
continue
    call beginsub('gtvarclose', fmt='var=%d', i=(/var%mapid/))
    call map_lookup(var, vid=vid)
    call maptabdelete(var, myerr)
    if (myerr) goto 999
    ! vid が 0 になるのは dup_dimmap で作られたハンドル
    if (vid == 0) goto 999
    call vartablelookup(vid, class, cid)
    call vartabledelete(vid, action, myerr)
    if (myerr) goto 999
    if (.not. action) then
        call message('refcount decrement only, no close internal var')
        goto 999
    else if (class == vtb_class_netcdf) then
        call ANVarClose(an_variable(cid), myerr)
        if (myerr) goto 999
    else if (class == vtb_class_memory) then
        call Close(mem_variable(cid))
        myerr = .false.
    else
        call StoreError(GT_EBADVAR, "GTVarClose", err)
        call endsub('GTVarClose', 'badvar')
        myerr = .true.
    endif
999 continue
    call endsub('gtvarclose')
    if (present(err)) err = myerr
end subroutine
