!
!= 谺｡蜈��霑ｽ蜉�
!
! Authors::   Eizi TOYODA, Yasuhiro MORIKAWA
! Version::   $Id: gtvaradddim.f90,v 1.3 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 縺九ｉ gtdata_generic#Add_dim
! 縺ｨ縺励※謠蝉ｾ帙＆繧後∪縺吶�

subroutine GTVarAddDim(var, dimord, dimvar, err)
  !
  !== 谺｡蜈��霑ｽ蜉�
  !
  ! 螟画焚 *var* 縺ｮ *dimord* 逡ｪ逶ｮ縺ｮ菴咲ｽｮ縺ｫ谺｡蜈� *dimvar*
  ! 繧定ｿｽ蜉�縺励∪縺吶�*dimord* 逡ｪ逶ｮ莉･髯阪�谺｡蜈�� 1 縺､蠕後ｍ縺ｫ縺壹ｌ縺ｾ縺吶�
  ! 繧ゅ＠ *dimord* 縺� *var* 縺ｮ譛牙柑谺｡蜈�焚繧医ｊ繧ょ､ｧ縺阪＞蝣ｴ蜷医�
  ! (譛牙柑谺｡蜈�焚 + 1) 縺御ｸ弱∴繧峨ｌ縺溘ｂ縺ｮ縺ｨ隕九↑縺輔ｌ縺ｾ縺吶�
  !
  ! 繧ｨ繝ｩ繝ｼ縺檎函縺倥◆蝣ｴ蜷医√Γ繝�そ繝ｼ繧ｸ繧貞�蜉�
  ! 縺励※繝励Ο繧ｰ繝ｩ繝�縺ｯ蠑ｷ蛻ｶ邨ゆｺ�＠縺ｾ縺吶�*err* 繧剃ｸ弱∴縺ｦ縺ゅｋ蝣ｴ蜷医↓縺ｯ
  ! 縺ｮ蠑墓焚縺ｫ .true. 縺瑚ｿ斐ｊ縲√�繝ｭ繧ｰ繝ｩ繝�縺ｯ邨ゆｺ�＠縺ｾ縺帙ｓ縲�
  !
  use gtdata_types, only: GT_VARIABLE
  use gtdata_generic, only: inquire
  use gtdata_internal_map, only: map_lookup, gt_dimmap, map_set_ndims, map_set, map_resize
  use dc_trace, only: beginsub, endsub, DbgMessage
  implicit none
  type(GT_VARIABLE), intent(in):: var
  type(GT_VARIABLE), intent(in):: dimvar
  integer, intent(in):: dimord
  logical, intent(out):: err
  type(gt_dimmap), pointer:: map(:)
  type(gt_dimmap):: tmpmap
  integer:: id, nd, ndimsp, stat, vid
  character(*), parameter:: subname = 'GTVarAddDim'
continue
  err = .true.
  call beginsub(subname)

  if (dimord < 1) then
    call endsub(subname, "negative dimord=%d invalid", i=(/dimord/))
    return
  endif

  ! dimvar 繧偵メ繧ｧ繝�け縺励�繝��險ｭ螳壹ｒ tmpmap 縺ｫ菫晏ｭ�
  call map_lookup(dimvar, vid=vid, ndims=nd)
  if (vid < 0) then
    call endsub(subname, "dimvar invalid")
    return
  endif
  if (nd <= 0) then
    call endsub(subname, "dimvar nondimensional")
    return
  else if (nd > 1) then
    call endsub(subname, "dimvar multidimensional")
    return
  endif
  allocate(map(nd))
  call map_lookup(dimvar, map=map)
  tmpmap = map(1)
  deallocate(map)

  ! dimord 逡ｪ逶ｮ (縺溘□縺� ndimsp + 1 繧定ｶ翫∴縺ｪ縺�) 縺ｫ謖ｿ蜈･縺吶ｋ髫咎俣繧偵≠縺代ｋ
  call map_lookup(var, ndims=ndimsp)
  if (dimord > ndimsp + 1) then
    id = ndimsp + 1
  else
    id = dimord
  endif
  allocate(map(nd + 1))
  call map_resize(var, nd + 1)
  call map_lookup(var, map=map)
  map(id+1: nd+1) = map(id: nd)

  ! 譁ｰ縺励＞谺｡蜈�∈縺ｮ蜿ら�繧呈諺蜈･
  map(id)%dimno = -1
  call inquire(dimvar, url=map(id)%url)
  map(id)%allcount = tmpmap%allcount
  map(id)%offset = tmpmap%offset
  map(id)%step = tmpmap%step
  map(id)%start = tmpmap%start
  map(id)%count = tmpmap%count
  map(id)%stride = tmpmap%stride

  ! 逋ｻ骭ｲ
  call map_set(var, map=map, stat=stat)
  if (stat /= 0) goto 999
  call map_set_ndims(var, ndims=ndimsp + 1, stat=stat)

999 continue
  err = (stat /= 0)
  call endsub(subname)
end subroutine GTVarAddDim