!c Description:
!c  化学種のモル数と相番号からモル比を計算する 
!c
!c Current Code Owner: 
!c   sugiyama@gfd-dennou.org
!c
!c Histry: 
!c   Version    Date          Comment
!c   -------    ----------    --------
!c   1.0        2003-02-05    作成
!c
!c Copyright (C) SUGIYAMA Ko-ichiro, 2003, All rights reserved


module interface_molfraction
  interface

     subroutine molfraction(mol, phase, molfr)
       real(8), intent(in)               :: mol(:)    !モル数
       real(8), intent(out), allocatable :: molfr(:)  !モル比
       integer, intent(in)               :: phase(:)  !化学種の相番号
     end subroutine molfraction

  end interface
end module interface_molfraction



subroutine molfraction(mol, phase, molfr)
  implicit none
  real(8), intent(in)               :: mol(:)    !モル数
  real(8), intent(out), allocatable :: molfr(:)  !モル比
  integer, intent(in)               :: phase(:)  !化学種の相番号

  integer                           :: smax      !存在する化学種の数
  integer                           :: s

  
!!!
!!!配列の初期化
!!!
  smax = size(mol, 1)
  if (allocated(molfr)) deallocate(molfr)
  allocate(molfr(smax))
  molfr = 0.0D0


!!!
!!!モル比の計算 (4 なら単体. 1--3 は混合物)
!!!
  do s = 1, smax
     if (phase(s) /= 4) then 
        molfr(s) = mol(s) / sum(mol, phase == phase(s)) 
     else
        molfr(s) = 1.0d0
     end if
  end do

!!!
!!!値の確認
!!!
  if (maxval(molfr) > 1.0D0 ) then
     write(*,*) "Warning: MolFraction.f90, molfr > 1.0"
     write(*,*) mol
     stop
  end if

  if (minval(mol) < 0.0D0) then
     write(*,*) "Warning: MolFraction.f90, mol < 0.0"
     write(*,*) mol
     stop
  end if

end subroutine molfraction



