
load /local/class/psych221/tutorials/cMatch/monitor;
load XYZ;
rgb2xyz = XYZ'*phosphors;
xyz2rgb = inv(rgb2xyz);
clear XYZ phosphors comment wavelength

if (exist('col')~=1) col = [0.5 0.5 0.5]'; end

xyzo = rgb2xyz*col;
xyzw = rgb2xyz*[1 1 1]';
LA = 20;        % white is approx 100 cd/m^2
Yb = xyzo(2);

% avg surround, samples subtending 4o
% c = 0.69;     Nc = 1.0;       FLL = 0.0;      F = 1.0;
% average surround
% c = 0.69;       Nc = 1.0;       FLL = 1.0;      F = 1.0;
% dim surround
c = 0.59;     Nc = 1.1;       FLL = 1.0;      F = 0.9;
% dark surround
% c = 0.525;    Nc = 0.8;       FLL = 1.0;      F = 0.9;
% cut sheet
% c = 0.41;     Nc = 0.8;       FLL = 1.0;      F = 0.9;

D = 1.0;	% discounting the illuminant completely (complete adaptation)

for ind = 1:3

  jch = ciecam_jc(xyzo,xyzw,LA,c,Nc,FLL,F,Yb,D);
  sav = jch(ind);
  stepsize = 1.0;

  %find lower limit
  nstep = 0;
  rgb = col;
  while ((rgb(1)>=0) & (rgb(1)<=1) ...
       & (rgb(2)>=0) & (rgb(2)<=1) ...
       & (rgb(3)>=0) & (rgb(3)<=1) & (nstep<180))
    nstep = nstep+1;
    jch(ind) = sav - (nstep*stepsize);
    xyz = inv_ciecam_jc(jch,xyzw,LA,c,Nc,FLL,F,Yb,D);
    rgb = xyz2rgb * xyz;
  end
  minval = sav - (nstep-1)*stepsize;
  if (minval<0) minval=0; end

  %find upper limit
  nstep = 0;
  rgb = col;
  while ((rgb(1)>=0) & (rgb(1)<=1) ...
       & (rgb(2)>=0) & (rgb(2)<=1) ...
       & (rgb(3)>=0) & (rgb(3)<=1) & (nstep<180))
    nstep = nstep+1;
    jch(ind) = sav + (nstep*stepsize);
    xyz = inv_ciecam_jc(jch,xyzw,LA,c,Nc,FLL,F,Yb,D);
    rgb = xyz2rgb * xyz;
  end
  maxval = sav + (nstep-1)*stepsize;
  
  %make the gradation 
  lst = minval:((maxval-minval)/255):maxval;
  for n = 1:256;
    jch(ind) = lst(n);
    xyz = inv_ciecam_jc(jch,xyzw,LA,c,Nc,FLL,F,Yb,D);
    cmap(1:3,n) = xyz2rgb * xyz;
  end
  df = abs(lst-sav);
  orig = find(df==min(df));
  cmap(1:3,orig) = [0;0;0];
  
  [a b] = meshgrid(1:256,1:64);
  imshow(a,cmap');
  title(sprintf('appearance ramp -- JCh(%d) = [%6.4f %6.4f]',ind,minval,maxval));

  if (ind<3)
    disp(['hit return to continue'])
    pause;
  end
  
end
