!******************** start file randbl.for ; group dep ****************
!---------------------------------------------------------------------
!  randbl_box -- for beam in box deposition
!  returns -- lsbeam, ldep, nb, ien
!
!  select random beam species beamline and energy species
!   first the beamline selection is made based on number of ptcls/sec
!   injected weighting
!  then the energy species (full / half / third) based on the input
!   energy fractions for the selected beamline
!
subroutine randbl_box(ib,ien,ierr)
  !
  use nbi_com
  use nbi_random_dep
  !
  use nbdep_debug                   ! debug module
  !
  !  beamline select
  !   xninj= tot no. of ptcls injected n/sec
  !   xninja(ib) = no. of ptcls coming in ib'th beamline
  !
  !============
  implicit none
  integer :: ien,ib,idum,ibl,ierr,is0,is,ibox,ii
  !============
  real(fp) :: zzn,zzns,zznsp,zx,zznt,zznts,zzntsp
  !============
  ierr=0
  !
  if(nbdep_debug_active.and.nbdep_set_beam.ne.0) then

     ib=nbdep_set_beam              ! preset for debugging purpose

  else
     !
     !  normal path: random selection weighted by total beam current
     !
     zznt=nbrandm_dep(idum)*xninj_box
     is0=0
     zznts=0
     do is=1,nsbeam
        if(nlfprod(is))cycle
        if(xninjs_box(is).gt.0.0_fp) then
           is0=is
           zzntsp=zznts
           zznts=zznts+xninjs_box(is)
           if((zzntsp.le.zznt).and.(zznts.gt.zznt)) exit
        end if

     end do
     lsbeam=is0
     if((lsbeam.le.0).or.(lsbeam.gt.nsbeam)) then
        write(nonlin,9002) xninj_box,(xninjs_box(is),is=1,nsbeam)
9002    format(' ? error in randbl_box --'/ &
             '   beam ptcl count error, xninj_box=',1pe12.5, &
             ' xninjs_box='/ &
             6(1x,1pe12.5))
        ierr=1
        return

     end if
     !
     !
     !  normal path: random selection weighted by beam current
     !
     zzn=nbrandm_dep(idum)*xninjs_box(lsbeam)
     !
     ldep=0
     zzns=0.0_fp
     do ii=1,nbbox
        if(nbsbox(ii).eq.0) cycle
        ldep=ii
        zznsp=zzns
        zzns=zzns+xninja_box(ii)
        if((zznsp.le.zzn).and.(zzns.gt.zzn)) goto 236
     end do
     !  in trouble?
     if(zzns.gt.1.001_fp*xninj_box) then

        write(nonlin,9001) xninj_box,(xninja_box(ib),ib=1,nbbox)
9001    format(' ? error in randbl_box --'/ &
             '   beam ptcl count error, xninj_box=',1pe12.5, &
             '   xninja_box='/6(1x,1pe12.5))
        ierr=1
        return
     end if
     !
236  continue
  end if
  nsample_box(ldep)=nsample_box(ldep)+1
  if(ldep.lt.1.or.ldep.gt.nbbox) then
     write(nonlin,9003) ldep,nbbox
9003 format(' ? error in randbl_box --'/ &
          '   beam ptcl count error, box id =',i5/ &
          '   must be 0 < ldep <=',i5)
     ierr=1
     return
  end if

  ib=nbsbox(ldep)
  ien=nbebox(ldep)
  !
  return
end subroutine randbl_box
!******************** end file randbl.for ; group dep ******************
