!c Description:
!c   phase の値を調整
!c
!c Current Code Owner: 
!c   sugiyama@gfd-dennou.org
!c
!c Histry: 
!c   Version    Date          Comment
!c   -------    ----------    --------
!c   1.0        2003-03-02    作成
!c
!c Copyright (C) SUGIYAMA Ko-ichiro, 2003, All rights reserved

module interface_phase_pack
  interface
     
     subroutine phase_pack(phase)
       integer, intent(inout)  :: phase(:)     !化学種の相番号
     end subroutine phase_pack

  end interface
end module interface_phase_pack




subroutine phase_pack(phase)
  implicit none
  integer, intent(inout)  :: phase(:)     !化学種の相番号

  integer, allocatable    :: phase_tmp(:)
  integer                 :: s, N
  integer                 :: min
  integer                 :: max
  integer                 :: nstep


!!!
!!!定数の初期化
!!!
  nstep = 1
  N = size(phase)

  !配列の形状の定義
  allocate(phase_tmp(N))


!!!
!!!配列のうち phase 番号が 4 のものを化学種の番号に変更
!!!
  do s = 1, N
     if (phase(s) == 4) then  
        phase(s) = s       
     end if
  end do
  max = maxval(phase)
  
  
!!!
!!!配列のうち, 値の小さなものを順次 do ループの回数に入れ換える. 
!!!
  pack: do 
     min = minval(phase, 1, phase >= nstep) 
     
     phase_tmp = nstep             
     phase = merge(phase_tmp, phase, phase == min)     
     
     nstep = nstep + 1
     if (min == max) exit pack
  end do pack
  
!!!
!!!後かたづけ
!!!
  deallocate(phase_tmp)


end subroutine phase_pack


