% InitializeClutsCT
%
% Read the calibration file and initialize the linear
% color lookup table.
%
% 3/8/97  dhb  Modified from dgp original to use current calibration
%              scheme.

% Read calibration file if not already in memory.
% Also load a description of a linear color space.
% Here we use CIE 1931 with units in cd/m^2.  (The
% factor of 683 converts the standard V_lambda function
% to units of cd/m^2.)
if (~exist('calCT'))
	disp('	Loading calibration file.');
% 	disp('	This may take some time.');
	calCT = LoadCalFile(screenNumber);
	if isempty(calCT)
		error('No calibration file available.');
	end
	calCT = SetGammaMethod(calCT,1);
	load T_xyz1931;
	T_linear = 683*T_xyz1931;
	S_linear = S_xyz1931;
	calCT = SetColorSpace(calCT,T_linear,S_linear);
else
	disp('	Using calibration data in memory.');
end

% Use calibration routines to find out the tristimulus
% coordiates corresonding to device white and black.
% From this we determine the chromaticity that we will
% modulate, which is that of the device white point.
disp('	Initializing cluts.');
whiteXYZ = SettingsToLinear(calCT,[255 255 255]');
blackXYZ = SettingsToLinear(calCT,[0 0 0]');
whitexyY = XYZToxyY(whiteXYZ);
nominalLMax = whiteXYZ(2);
nominalLMin = blackXYZ(2);

% Find 256 (corresponds to 8-bits) linearly spaced luminances
% between min and max available luminances.  Then convert
% these to tristimulus coordinates at the desired chromaticity.
linearLums = linspace(nominalLMin,nominalLMax,256);
linearXYZ = xyYToXYZ([whitexyY(1:2)*ones(1,256) ; linearLums]);

% Compute the color lookup table that gives the closest possible
% approximation to the desired tristimulus coordinates.  This
% is the clut that will linearize the display.
linearClut = LinearToSettings(calCT,linearXYZ)';

% Run the converstion back from the linear clut to find out
% what we can actually achieve with the device.
actualXYZ = SettingsToLinear(calCT,linearClut');
actualLums = actualXYZ(2,:);
LMax = actualLums(256);
LMin = actualLums(1);
LBackground = actualLums(backgroundEntry);

% Compute a clut that will blank the display at the
% background level.  Installing this hides artifacts
% during frame buffer writes.
offClut = ones(256,1)*linearClut(backgroundEntry,:);
