!******************** start file randbl.for ; group dep ****************
!---------------------------------------------------------------------
!  randbl
!
!  select random 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(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
  !============
  real(fp) :: zzn,zzns,zznsp,zx

  !============
  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 beam current
     !
     zzn=nbrandm_dep(idum)*xninjs(lsbeam)

     !
     ibl=0
     zzns=0.0_fp
     do ib=1,nbeam
        if(lsbeama(ib).eq.lsbeam) then
           ibl=ib
           zznsp=zzns
           zzns=zzns+xninja(ib)
           if((zznsp.le.zzn).and.(zzns.gt.zzn)) goto 236
        end if

     end do
     !  in trouble?
     if(zzns.gt.1.001_fp*xninj) then

        write(nonlin,9001) xninj,(xninja(ib),ib=1,nbeam)
9001    format(' ? error in randbl --'/ &
             '   beam ptcl count error, xninj=',1pe12.5,' xninja='/ &
             6(1x,1pe12.5))
        ierr=1
        return
     else
        ib=ibl
     end if
     !
236  continue
  end if
  !
  !  choose beam ptcl energy (full/half/third)
  !   ffulla, fhalfa give energy fractions by beamline
  !
  if(nbdep_debug_active.and.nbdep_set_ien.ne.0) then

     ien=nbdep_set_ien              ! preset for debugging purpose

  else
     !
     !  normal path:  random selection weighted by fraction data
     !
     zx=nbrandm_dep(idum)
     ien=1
     if(zx.gt.ffulla(ib)) ien=2
     if(zx.gt.(ffulla(ib)+fhalfa(ib))) ien=3
  end if
  !
  return
end subroutine randbl
!******************** end file randbl.for ; group dep ******************
