%  Function to do color balancing on a macbeth color checker 
%  image using specular reflection. The function mbal assumes 
%  the gamma correction has already been performed on the image.  

function [newR,newG,newB] = mbal(r,g,b)

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

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))';
linrgb = [r,g,b];

imagexyz = rgb2xyz*linrgb';

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

maxY = max(imagexyz(2,:));   % Search for the highest Y value (2nd row)
index = find(imagexyz(2,:)==maxY)  
index = index(1);

% Display white point
disp('Located white point...')
whitePt = linrgb(index,:);
whitePt = replaceValue(whitePt,0,eps)


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

newR = reshape(linrgb(:,1), imgSize(1), imgSize(2));
newG = reshape(linrgb(:,2), imgSize(1), imgSize(2));
newB = reshape(linrgb(:,3), imgSize(1), imgSize(2));









