function [ out_image ] = equalize( image_matrix, NumOfBins )
% Create a function that: 
% ? realizes a histogram equalizer, 
% ? parameters of this function should be as follows: 
%     ? input1: image matrix, 
%     ? input2: number of bins, 
%     ? output: the matrix of the equalized image, 
% ? it should work with grayscale images (check if this holds).

if (size(image_matrix,3) ~= 1)
    error 'This picture is not grayscale!'
end

[N1, N2] = size(image_matrix);

column_threshold = N1*N2 / NumOfBins;
columns = floor(linspace(0, 255, NumOfBins));

out_image = zeros(N1, N2);
pixel_counter = 0;
column_counter = 1;
current_threshold = column_threshold;

for k = 1:255
    mask = (image_matrix == k);
    out_image(mask) = columns(column_counter);
    pixel_counter = pixel_counter + sum(sum(mask));
    if (pixel_counter > current_threshold)
        current_threshold = column_threshold - (pixel_counter - current_threshold);
        column_counter = column_counter + 1;
        pixel_counter = 0;
    end
end

out_image = uint8(out_image);

end

