module m_get_mod_nrens
! Finds how many ensemble members there are by counting ocean
! and ice restart files. 
! 
! If an optional integer vector 'enslist' is submitted, the 
! numbers of the 'still living' members is returned.
!
#if defined (QMPI)
   use qmpi, only : stop_mpi, master
#else
   use qmpi_fake, only : stop_mpi, master
#endif

contains

subroutine get_mod_nrens(nrens, enslist)
   implicit none

   ! In/out
   integer,               intent(inout) :: nrens
   integer, dimension(:), intent(out), optional :: enslist

   ! Local variables
   logical                ex
   integer                iens          ! loop var
   character(len=3)    :: cens          ! contains '1xx' of member
   character(len=99)   :: path2mod='./' ! should model output be somewhere else
   integer             :: maxnrens=899  ! max nr of members we're looking for
#if defined (ICE)
   integer                nrice         ! ice file counter
#endif

   ! restart files will have been moved to path2mod and be called
   ! 'forecast_ice_XXX.nc' where XXX is the enseble identifier (101-)

   ! Count members. Assumed nrens at most 1000.
   nrens = 0
   do iens=1,maxnrens
      write(cens,'(i3.3)') iens+100
      inquire(exist=ex,file=trim(path2mod)//'forecast_oce_'//cens//'.nc')
      if (ex) then
         nrens = nrens + 1
         if (present(enslist)) enslist(nrens) = iens
      end if
   end do

   ! Warn if arbitrary max. limit of nrens is reached.
   if ( ( nrens.eq.maxnrens ).and.(master) ) then
      print *,'WARNING:'
      print *,'WARNING: Ensemble sizes above ',maxnrens,' are not recognized.'
      print *,'WARNING: Adjust m_get_mod_nrens.F90 to go bigger.'
      ! Don't forget to adjust also length of cens.
      print *,'WARNING:'
   endif

#if defined (ICE)
   ! Count ice members. Assumed nrens at most maxnrens.
   nrice = 0
   do iens=1,maxnrens
      write(cens,'(i3.3)') iens+100
      inquire(exist=ex,file=trim(path2mod)//'forecast_ice_'//cens//'.nc')
      if (ex) nrice = nrice + 1
   end do

   if (nrice /= nrens) then
      if (master) then
         print *,'(get_mod_nrens) Error: Different number of ocean and ice restarts!!!'
         print *,'Ocean restarts : ',nrens
         print *,'Ice restarts   : ',nrice
      end if
      call stop_mpi()
   end if
#endif

end subroutine get_mod_nrens
end module m_get_mod_nrens
