!
!= æ¬¡å…ƒé †åºç•ªå·ã®äº¤æ›
!
! Authors::   Eizi TOYODA, Yasuhiro MORIKAWA
! Version::   $Id: gtvarexchdim.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#Exch_dim
! ã¨ã—ã¦æä¾›ã•ã‚Œã¾ã™ã€‚

subroutine GTVarExchDim(var, dimord1, dimord2, count_compact, err)
  !
  !== æ¬¡å…ƒé †åºç•ªå·ã®äº¤æ›
  !
  ! å¤‰æ•° *var* ã®æ¬¡å…ƒé †åºç•ªå· <b>dimord1</b>, <b>dimord2</b> ã®ãã‚Œãžã‚Œã«
  ! å¯¾å¿œã™ã‚‹æ¬¡å…ƒã‚’å…¥ã‚Œæ›¿ãˆã¾ã™ã€‚
  !
  ! *count_compact* ã« .true. ã‚’æ¸¡ã™ã¨ã€ç¸®é€€ã—ãŸæ¬¡å…ƒã‚‚å«ã‚ã¦
  ! å‹•ä½œã—ã¾ã™ã€‚
  !
  ! ã‚¨ãƒ©ãƒ¼ãŒç”Ÿã˜ãŸå ´åˆã€ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ã‚’å‡ºåŠ›
  ! ã—ã¦ãƒ—ãƒã‚°ãƒ©ãƒ ã¯å¼·åˆ¶çµ‚äº†ã—ã¾ã™ã€‚*err* ã‚’ä¸Žãˆã¦ã‚ã‚‹å ´åˆã«ã¯
  ! ã®å¼•æ•°ã« .true. ãŒè¿”ã‚Šã€ãƒ—ãƒã‚°ãƒ©ãƒ ã¯çµ‚äº†ã—ã¾ã›ã‚“ã€‚
  !
  use gtdata_types, only: GT_VARIABLE
  use gtdata_internal_map, only: map_lookup, gt_dimmap, map_set_ndims, map_set, &
    & dimord_skip_compact
  use dc_trace, only: beginsub, endsub, DbgMessage
  implicit none
  type(GT_VARIABLE), intent(in):: var
  integer, intent(in):: dimord1, dimord2
  logical, intent(in), optional:: count_compact
  logical, intent(out):: err
  type(gt_dimmap), allocatable:: map(:)
  type(gt_dimmap):: tmpmap
  integer:: ndimsp, stat, idim1, idim2
  logical:: direct_mode
  character(*), parameter:: subname = 'GTVarExchDim'
continue
  err = .true.
  direct_mode = .false.
  if (present(count_compact)) then
    direct_mode = count_compact
  endif
  call beginsub(subname)
  if (dimord1 < 1 .or. dimord2 < 1) then
    call endsub(subname, "negative dimord=%d %d invalid", i=(/dimord1, dimord2/))
    return
  endif
  call map_lookup(var, ndims=ndimsp)
  if (ndimsp <= 0) then
    call endsub(subname, "variable invalid")
    return
  else if (dimord1 > ndimsp .or. dimord2 > ndimsp) then
    call endsub(subname, "dimord=%d %d not exist", i=(/dimord1, dimord2/))
    return
  endif

  allocate(map(ndimsp))
  call map_lookup(var, map=map)

  if (.not. direct_mode) then
    idim1 = dimord_skip_compact(dimord1, map)
    idim2 = dimord_skip_compact(dimord2, map)
    if (idim1 < 0 .or. idim2 < 0) then
      call endsub(subname, "dimord=%d %d not found after compaction", &
        & i=(/dimord1, dimord2/))
      deallocate(map)
      return
    endif
  else
    idim1 = dimord1
    idim2 = dimord2
  endif

  tmpmap = map(idim1)
  map(idim1) = map(idim2)
  map(idim2) = tmpmap
  call map_set(var, map, stat)
  deallocate(map)

  err = stat /= 0
  call endsub(subname)
end subroutine GTVarExchDim