function imagesOut = normalizeIntensity(imagesIn);
% normalizeIntensity: adjust a series of images so that each has the same mean intensity value.
% 
% Usage: imagesOut = normalizeIntensity(imagesIn);
%
% imagesIn is a cell-of-matrices containing the images to be normalized. imagesOut contains
% those images, normalized so that each image has the same mean value.
%
% 2/03 by ras
if ~iscell(imagesIn)
	tmp{1} = imagesIn;
	imagesIn = tmp;
end

numImages = length(imagesIn);

% find mean intensity for each image
for i = 1:numImages
	if size(imagesIn{i},3)==1
		meanVals(i) = mean(mean(imagesIn{i}));
	else
		meanVals(i) = mean(mean(mean(imagesIn{i})));
	end
end

% calculate offset of each image from the overall mean intensity
overallMean = mean(meanVals);
offset = meanVals - overallMean;

% normalize each image to overallMean
for i = 1:numImages
	tmp = double(imagesIn{i}) - offset(i);
	tmp(find(tmp>255)) = 255;
	tmp(find(tmp<0)) = 0;
	imagesOut{i} = uint8(tmp);
end

return
