subroutine nbi_dransort(drndm,indxs,n,ierr)
!
  use iso_c_binding, only: fp => c_double
  use dep_mpi_split     ! use this module to deposit cx tracks for statistics improvement
                        ! does not interfer with depall
  use nbi_random_pll
  use nbi_mpi_com
  use logmod
  implicit none
!
  integer,intent(in) :: n
  real(fp), intent(out) :: drndm(n)
  integer, intent(out) :: indxs(n)
  integer, intent(out) :: ierr     ! exit status, 0=ok
!
  real(fp), dimension(:), allocatable :: zindx,ichk
!
  integer i,indx,idum
!
!  return an array containing n random numbers chosen from a
!  flat distribution over [0,1] and sorted in ascending order.
!
!  that is, if j.lt.k then drndm(iorder(j)).le.drndm(iorder(k))
!
  real(fp), parameter :: zero = 0.0_fp
!
  indxs = 0
!
  allocate(zindx(n),ichk(n))
!
  ichk = 0
  !
  do i=1,n
     zindx(i)= i + 0.5_fp
     drndm(i)=nbrandm_pll(idum)
     if(drndm(i).lt.zero) then
        call warnlog( ' nbi_dransort: negative drndm reset to zero.')
        drndm(i)=zero
     endif
  enddo
!
!  use netlib routine
!
  call tr_dsort(drndm,zindx,n,2)
      !
  ierr = 0
  do i=1,n
     indx=zindx(i)
     if(ichk(indx).gt.0) then
        call errorlog(' nbi_dransort: algorithm failure! ')
        ierr = ierr + 1
        if(ierr.gt.10) exit
     endif
     ichk(indx)=i
     indxs(i)=indx
  enddo
  
  deallocate(zindx,ichk)
  
  return
end subroutine nbi_dransort
