%
% PerfectReflectorFun.m
%
% Function to implement PerfectReflector color balance algorithm
%
% Hui Li
% 3/7/2000
%	

function [outR, outG, outB] = PerfectReflector(inR, inG, inB)

load /local/class/psych221/tutorials/cMatch/monitor;
load xyz
rgb2xyz = xyz'*phosphors;

% Monitor Inverse Gamma correction already done for input images

imsize = size(inR);

inR = reshape(inR, 1, imsize(1)*imsize(2))';
inG = reshape(inG, 1, imsize(1)*imsize(2))';
inB = reshape(inB, 1, imsize(1)*imsize(2))';

imRGB = [inR,inG,inB];

imXYZ = rgb2xyz*imRGB';

% Locate specularities by finding the pixel with the highest Y value.
maxY = max(imXYZ(2,:));
index = find(imXYZ(2,:)==maxY);
index = index(1);

whitePoint = imRGB(index,:);
whitePoint = replaceValue(whitePoint,0,eps);
imOut = imRGB*diag(1./whitePoint);

outR = imOut(:,1);
outG = imOut(:,2);
outB = imOut(:,3);

outR = reshape(outR, imsize(1), imsize(2));
outG = reshape(outG, imsize(1), imsize(2));
outB = reshape(outB, imsize(1), imsize(2));

% Scale output
maxRGB = [max(max(outR)) max(max(outG)) max(max(outG))];

factor = max(maxRGB);
if  factor > 1
	outR = outR./factor;
	outG = outG./factor;
	outB = outB./factor;
end


% Camera Gamma Correction





