function doPerfectReflector(infile, outfile)

% Usage: doPerfectReflector(infile, outfile)
%
% A simple implementation of an algorithm based on the perfect
% reflector 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;
load /local/class/psych221/tutorials/cMatch/monitor;
load xyz
rgb2xyz = xyz'*phosphors;

[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));

imagexyz = rgb2xyz*linrgb';

% Locate specularities by looking for the pixel with the highest
% Y value.

maxY = max(imagexyz(2,:));
index = find(imagexyz(2,:)==maxY);
index = index(1);

% Display white point

disp('Located white point...')
whitePt = linrgb(index,:)

linrgb = linrgb*diag(1./whitePt);

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);



