module wei_hist
  use wei_util
  use wei_process
  !---------------
  implicit none

  real, dimension(:), pointer, private :: hist
  integer, private :: nhist  !! # of elements in histogram

contains
  !----------------------------------------------------------------  
  subroutine weihist_init()
    integer :: er
    integer :: mpierr

    !! # of elements in histogram
    if(pro%mpi_ithread==0) call from_param("nhist" ,nhist,10)
    if(pro%mpi_nthread >0) call MPI_BCAST(nhist, 1,MPI_INTEGER,0,MPI_COMM_WORLD,mpierr)

    allocate(hist(nhist),stat=er)
    if(er/=0) call seperr('cant allocate hist')
    
  end subroutine weihist_init
  !----------------------------------------------------------------
  !! return the most popular value of a vector
  real function weihist(izs,vector,ivmin,ivmax) result(popular)
    integer, intent(in) :: izs
    real, dimension(:), pointer :: vector
    integer,         intent(in) :: ivmin, ivmax

    real    :: vmin,vmax,dv
    integer :: iv
    integer :: ihist, ihistmax
    real    :: histmax

    vmin = minval(vector(ivmin:ivmax))
    vmax = maxval(vector(ivmin:ivmax))
    dv = (vmax-vmin)/nhist !! bin size

    !! create the histogram
    hist=0
    do iv=ivmin,ivmax
       ihist = 1+floor( (vector(iv)-vmin)/dv )
       if(ihist>nhist .or. ihist<1) cycle
       hist(ihist) = hist(ihist) + 1
    end do

    !! find the most populated bin in the histogram
    ihistmax=1
    histmax=hist(ihistmax)
    do ihist=1,nhist
       if(hist(ihist)>histmax) then
          ihistmax = ihist
          histmax = hist(ihistmax)
       end if
    end do

    popular = vmin + (ihistmax-.5)*dv
  end function weihist
  !----------------------------------------------------------------
end module wei_hist











