%
% function [correctedColors] = inverseGammaCorrection(colors, whichCamera)
%
% Input: colors: a matrix of size 3xN whose columns are the gamma corrected 
%                colors of the camera output
%        whichCamera: must be either 'sony' or 'olympus'
%
% Return: correctedColors: the corrected colors
%

function [correctedColors] = inverseGammaCorrection(colors, whichCamera)

load 'inverseGammaCorrection';

reflectance = reflectance600*255;
reflectance = [255 reflectance 0];

if( strcmp(whichCamera, 'sony') )
 grayIntensities = sonyGrayIntensities;
elseif( strcmp(whichCamera, 'olympus') )
 grayIntensities = olympusGrayIntensities;
else
 error('unknown camera');
end

grayIntensities = [255 grayIntensities 0];

[row, col] = size(colors);

if( row != 3 )
 error('matrix must have 3 rows');
end

correctedColors = colors;

originalIntensities = (colors(1,:)+colors(2,:)+colors(3,:))/3;
iszero = (originalIntensities == 0);
originalIntensities = originalIntensities + iszero;

correctedIntensities = interp1(grayIntensities, reflectance, originalIntensities);

intensityScales = correctedIntensities./originalIntensities;

for i=1:row
 correctedColors(i,:) = colors(i,:).*intensityScales;
end

% clamp

greaterThan255 = (correctedColors > 255);
correctedColors = correctedColors .* (~greaterThan255) + greaterThan255*255;
