function doGrayWorld(infile, outfile)

% Usage: doGrayWorld(infile, outfile)
%
% A simple implementation of an algorithm based on the gray
% world assumption. This function takes in a gamma-corrected
% tiff image and generates a gamma-corrected, color-balanced
% picture. Actual data manipulation occurs in linear RGB space.
%
% KLY 98

load /local/class/psych221/tutorials/cMatch/monitorGam;

[r g b] = tiffread(infile);

imgSize = size(r);

r = reshape(r, 1, imgSize(1)*imgSize(2))';
g = reshape(g, 1, imgSize(1)*imgSize(2))';
b = reshape(b, 1, imgSize(1)*imgSize(2))';

rgb = [r,g,b];
maxQ = size(monitorGam,1);
rgb = scale(rgb,1,maxQ);
linrgb = monitorGam(round(rgb));

% Display averages

disp('Image averages...')
averagergb = sum(linrgb)
averageGray = sum(averagergb)./3
scaleFactors = averageGray./averagergb;

linrgb = linrgb*diag(scaleFactors);

maxQ = size(monitorInvGam,1);
rgb = scale(linrgb,1,maxQ);
rgb = monitorInvGam(round(rgb))./255;

r = reshape(rgb(:,1), imgSize(1), imgSize(2));
g = reshape(rgb(:,2), imgSize(1), imgSize(2));
b = reshape(rgb(:,3), imgSize(1), imgSize(2));

tiffwrite(r, g, b, outfile);



