function cout = hist_flat(img)
% hist_flat
%   INPUT
%       img - a color image
%   OUTPUT
%       cout - a color image with the grayscale intensities flattened out


gray = sum(img,3);
gray = gray/3;
gray = uint8(gray);
V = reshape(gray, size(gray,1)*size(gray,2),1);
[Gs, Is] = sort(V);
O = zeros(size(V));
Z = size(gray,1)*size(gray,2)/256;
for i =1:256
    O(Is(Z*(i-1)+1:Z*i)) = i-1;
    i
end
out = reshape(O,size(gray,1),size(gray,2));

grayd = double(gray);
imgd = double(img);
outd = double(out);

r = imgd(:,:,1)./grayd;
g = imgd(:,:,2)./grayd;
b = imgd(:,:,3)./grayd;

R = r.*outd;
G = g.*outd;
B = b.*outd;

cout = zeros(size(img));
cout(:,:,1) = R;
cout(:,:,2) = G;
cout(:,:,3) = B;

cout = uint8(cout);
imshow(cout);
