function monitorRGB = cones2monitor(coneResponses);
% This function returns RGB values that would create the same
% color sensation as the given cone responses on a standard monitor.
% Matlab Code taken from Wandell Lab - Stanford ColorTutorial.m

%% RENDER THE SURFACES ON THE MONITOR, SO THEY LOOK RIGHT

%% Read in the spectra of a typical set of color monitor phosphors.
%% These are probably much like to the ones on your screen, but not
%% quite right because we haven't calibrated these monitors.  Each row
%% in this matrix corresponds to one phosphor, giving its relative
%% output energy as a function of wavelength.


%load phosphors %phosphors
load myDisplay; %phosphors

load cones     %cones
%load xyz
%cones = ciexyz;
%% Here we calculate the monitor phosophor intensities required to
%% generate the *same* receptor responses in your eye that the Macbeth
%% surfaces generate under daylight.  To do so, we first find the
%% linear tranform that gives the cone responses due to the different
%% monitor spectra.  To understand this calculation, try pulling out a 
%% piece of paper and convincing yourself that this is the way to get
%% cone responses from the phosphor intensities.

monitor_to_cones=cones*phosphors';

%% Now, the inverse of this matrix tells us how to set the
%% phosphors to achieve any desired cone responses:

cones_to_monitor=inv(monitor_to_cones);

%% We apply this transformation to the desired cone responses and
%% obtain the necessary monitor intensities for rendering the image.

monitor_signals=cones_to_monitor*coneResponses;


%% The digital RGB values in the framebuffer are related in a
%% nonlinear way to the actual phosphor intensities that result on the
%% screen.  This can be approximately fixed by raising the desired
%% intensity values to a fixed power, for example, 0.6. This is
%% typically called "Gamma Correction" for historical reasons (the
%% exponent is called "gamma").

%gamma=0.6;
%monitor_signals(find(monitor_signals<0))=0;
%monitorRGB=monitor_signals.^gamma;
monitorRGB=monitor_signals;


%% Note that this hack (arbitrarily chosen correction) does not
%% linearize the display perfectly.  To linearize accurately one
%% must measure the nonlinear relationship between the 8bit
%% R,G, and B values and the intensity of the resulting signal.  To do
%% so involves a simple but time-consuming calibration procedure.
