function [ bin_ave, bin_count ] = histogramize ( n, x, bin_min, bin_max, ...
  bin_num )

%*****************************************************************************80
%
%% HISTOGRAMIZE sorts data into histogram bins.
%
%  Discussion:
%
%    The function defines a number of equal width bins between BIN_MIN
%    and BIN_MAX.
%
%    Values in a data vector which fall with the range of bin I will
%    increment the value of BIN_COUNT(I).
%
%    The resulting vectors BIN_AVE and BIN_COUNT can be displayed as a bar 
%    chart, which will actually be a histogram of the original data.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    19 July 2018
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer N, the number of data values.
%
%    real X(N), the data.
%
%    real BIN_MIN, BIN_MAX, the minimum and maximum values for the bins.
%
%    integer BIN_NUM, the number of bins.
%
%  Output:
%
%    real BIN_AVE(BIN_NUM), the value associated with the midpoint
%    of each bin.
%
%    integer BIN_COUNT(BIN_NUM), returns the number of data values 
%    within each bin.
%
  bindex = 1 + floor ( bin_num * ( x - bin_min ) / ( bin_max - bin_min ) );

  for i = 1 : n
    if ( bindex(i) == bin_num + 1 && x(i) < bin_max + eps * ( bin_max - bin_min ) )
      bindex(i) = bin_num;
    end
  end

  bin_ave = zeros ( bin_num, 1 );
  bin_count = zeros ( bin_num, 1 );
   
  for i = 1 : bin_num
    bin_ave(i) = bin_min + ( 2 * i - 1 ) * ( bin_max - bin_min ) / 2.0 / bin_num;
    bin_count(i) = sum ( bindex == i );
  end

  return
end
