!
!= å¤‰æ•°ã®çµ‚äº†å‡¦ç†
!
! Authors::   Yasuhiro MORIKAWA, Eizi TOYODA
! Version::   $Id: gtvarclose.f90,v 1.5 2009-05-25 09:55:58 morikawa Exp $
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2000-2005. All rights reserved.
! License::   See COPYRIGHT[link:../../COPYRIGHT]
!
! ä»¥ä¸‹ã®ã‚µãƒ–ãƒ«ãƒ¼ãƒãƒ³, é–¢æ•°ã¯ gtdata_generic ã‹ã‚‰æä¾›ã•ã‚Œã¾ã™ã€‚
!

subroutine GTVarClose(var, err)
  !
  !== å¤‰æ•°ã®çµ‚äº†å‡¦ç†
  !
  ! å¤‰æ•° *var* ã®çµ‚äº†å‡¦ç†ã‚’è¡Œã„ã¾ã™ã€‚Open ã¾ãŸã¯ Create ã•ã‚ŒãŸã‚‚ã®ã¯
  ! ãƒ—ãƒã‚°ãƒ©ãƒ ã®æœ€å¾Œã«å¿…ãšã“ã®ã‚µãƒ–ãƒ«ãƒ¼ãƒãƒ³ã‚’ç”¨ã„ã¦çµ‚äº†å‡¦ç†ã‚’è¡Œã£ã¦ãã ã•ã„ã€‚
  !
  ! çµ‚äº†å‡¦ç†ã®éš›ã«ã‚¨ãƒ©ãƒ¼ãŒç”Ÿã˜ãŸå ´åˆã€ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ã‚’å‡ºåŠ›ã—ã¦ãƒ—ãƒã‚°ãƒ©ãƒ ã¯
  ! å¼·åˆ¶çµ‚äº†ã—ã¾ã™ã€‚*err* ã‚’ä¸Žãˆã¦ã‚ã‚‹å ´åˆã«ã¯ã“ã®å¼•æ•°ã« .true.
  ! ãŒè¿”ã‚Šã€ãƒ—ãƒã‚°ãƒ©ãƒ ã¯çµ‚äº†ã—ã¾ã›ã‚“ã€‚
  !
  use gtdata_types, only: GT_VARIABLE
  use gtdata_internal_map, only: vtb_class_netcdf, vtb_class_memory, &
    & maptabdelete, map_lookup
  use gtdata_internal_vartable, only: vartabledelete, vartablelookup
  use gtdata_netcdf_generic, only: Close
  use gtdata_netcdf_types, only: GD_NC_VARIABLE
  use dc_error, only: StoreError, GT_EBADVAR, dc_noerr
  use dc_trace, only: beginsub, endsub, DbgMessage
  use gtdata_memory_generic, only: Close
  use gtdata_memory_types, only: GD_MEM_VARIABLE
  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 DbgMessage('refcount decrement only, no close internal var')
    goto 999
  else if (class == vtb_class_netcdf) then
    call Close(GD_NC_VARIABLE(cid), myerr)
    if (myerr) goto 999
  else if (class == vtb_class_memory) then
    call Close(GD_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 GTVarClose