!== Open GD_NC_VARIABLE of dimension by dimord
!
! Authors::   Yasuhiro MORIKAWA, Eizi TOYODA
! Version::   $Id: gdncvaropenbydimord.f90,v 1.2 2009-05-25 09:51:59 morikawa Exp $
! Tag Name::  $Name:  $
! Copyright:: Copyright (C) GFD Dennou Club, 2000-2006. All rights reserved.
! License::   See COPYRIGHT[link:../../COPYRIGHT]
!

subroutine GDNcVarOpenByDimOrd(var, src_var, dimord, err)
  !
  ! æ—¢ã«é–‹ã‹ã‚ŒãŸå¤‰æ•° *src_var* ã® *dimord* ç•ªç›®ã®æ¬¡å…ƒã«ã‚ãŸã‚‹å¤‰æ•°ã‚’
  ! é–‹ã *var* ã«æ ¼ç´ã—ã¾ã™ã€‚
  !
  ! å¤‰æ•°ã‚’é–‹ãéš›ã«ã‚¨ãƒ©ãƒ¼ãŒç”Ÿã˜ãŸå ´åˆã€ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ã‚’å‡ºåŠ›ã—ã¦ãƒ—ãƒã‚°ãƒ©ãƒ ã¯
  ! å¼·åˆ¶çµ‚äº†ã—ã¾ã™ã€‚*err* ã‚’ä¸Žãˆã¦ã‚ã‚‹å ´åˆã«ã¯ã“ã®å¼•æ•°ã« .true.
  ! ãŒè¿”ã‚Šã€ãƒ—ãƒã‚°ãƒ©ãƒ ã¯çµ‚äº†ã—ã¾ã›ã‚“ã€‚
  !
  use gtdata_netcdf_types, only: GD_NC_VARIABLE, GD_NC_VARIABLE_ENTRY, GD_NC_VARIABLE_SEARCH
  use gtdata_netcdf_internal, only: vtable_lookup, vtable_add
  use gtdata_netcdf_file_generic, only: GDNcFileReopen, GDNcFileClose
  use netcdf, only: NF90_MAX_NAME, NF90_NOERR, NF90_EINVAL, NF90_ENOTVAR, &
    & NF90_INQUIRE_DIMENSION, NF90_INQ_VARID
  use dc_error
  implicit none
  type(GD_NC_VARIABLE), intent(out):: var
  type(GD_NC_VARIABLE), intent(in):: src_var
  integer, intent(in):: dimord
  logical, intent(out), optional:: err
  type(GD_NC_VARIABLE_ENTRY):: src_ent
  type(GD_NC_VARIABLE_SEARCH):: ent
  character(len = NF90_MAX_NAME):: dimname
  integer:: stat
continue
  stat = vtable_lookup(src_var, src_ent)
  if (stat /= NF90_NOERR) goto 999
  !
  if (dimord <= 0) then
    !
    ! dimord == 0 ã®ç‰¹åˆ¥æ‰±ã„ã¯å»ƒæ¢ (gtdata å±¤ã§ã‚„ã‚‹)ã€‚
    ! (åŒã˜ãƒãƒ³ãƒ‰ãƒ«ã‚’è¿”ã™ã¨å‚ç…§ã‚«ã‚¦ãƒ³ãƒˆãŒå¢—ãˆãªã„ã®ã§å¤šé‡ã‚¯ãƒãƒ¼ã‚ºãŒ
    ! ç¦æ¢ã•ã‚Œã¦ã—ã¾ã„ã€Open ã®ã‚»ãƒžãƒ³ãƒ†ã‚£ã‚¯ã‚¹ã«ä¸é©åˆãªãŸã‚ã€‚)
    !
    var = src_var
    stat = NF90_EINVAL
    goto 999
  endif
  if (.not. associated(src_ent%dimids)) then
    stat = GT_ENOMOREDIMS
    goto 999
  else if (dimord > size(src_ent%dimids)) then
    stat = GT_ENOMOREDIMS
    goto 999
  endif
  !
  ! æ±ºå®šã•ã‚ŒãŸæ¬¡å…ƒ id ã‚’ä½¿ã£ã¦å¤‰æ•° id ã®ç¢ºå®šã‚’è©¦ã¿ã‚‹
  !
  ent%fileid = src_ent%fileid
  ent%dimid = src_ent%dimids(dimord)
  stat = NF90_INQUIRE_DIMENSION(ent%fileid, ent%dimid, name = dimname)
  if (stat /= NF90_NOERR) goto 999
  stat = NF90_INQ_VARID(ent%fileid, dimname, ent%varid)
  if (stat == NF90_ENOTVAR) then
    ! å¤‰æ•°ãŒå¯¾å¿œã—ãªã‘ã‚Œã°ç„¡è¦–ã™ã‚‹ã ã‘
    ent%varid = 0
    stat = NF90_NOERR
  else if (stat /= NF90_NOERR) then
    goto 999
  endif
  !
  ! æˆåŠŸã—ãã†ãªã®ã§å‚ç…§ã‚«ã‚¦ãƒ³ãƒˆå€¤ã‚’å¢—ã‚„ã™
  call GDNcFileReopen(ent%fileid)
  ! ä¸é©åˆãªå¤‰æ•°ãŒé–‹ã‹ã‚Œã¦ã„ã‚‹å ´åˆã¯ vtable_add ãŒå¤‰æ•°éƒ¨ã‚’ç„¡è¦–ã™ã‚‹ã€‚
  stat = vtable_add(var, ent)
  if (stat /= NF90_NOERR) then
    call GDNcFileClose(ent%fileid)
    goto 999
  endif

999 continue
  call StoreError(stat, 'GDNcVarOpenByDimOrd', err, cause_i=dimord)
end subroutine