function newmap = testpattern(linearRGB, avg, red, green, blue, pos)

% newcolormap = testpattern(rgb, avg, spotR, spotG, spotB, pos)
%
% Given an array of rgb values that averages out to gray,
% testpattern generates an 8x6 grid of colored squares
% that also averages out to the same average. The user
% also supplies spotR spotG spotB, the color of the square
% located at pos (see below). This program automatically 
% computes a complementary color to maintain the overall average.
% 
% If an index error occurs, try spotR spotG spotB values
% that are closer to the average.
%
% pos values:
%   0  ->  center
%   1  ->  top left
%   2  ->  top right
%   3  ->  bottom left
%   4  ->  bottom right
%   5  ->  dispersed
%
% KLY 98

cd /local/class/psych221/tutorials

load cMatch/monitor;     % This contains the monitor phosphors
load cMatch/monitorGam;  % This contains monitorInvGamma
load XYZ;

cd ~

testImage = flipud(rot90(reshape(1:48,8,6)));

compred = 2*avg - red
compgreen = 2*avg - green
compblue = 2*avg - blue

if pos==0
  
  linearRGB = [linearRGB(1:19,:) ; red green blue; ...
      compred compgreen compblue; ...
      linearRGB(20:25,:) ; compred compgreen compblue; ...
      red green blue; ...
      linearRGB(26:44,:)];

elseif pos==1
  
  linearRGB = [red green blue; compred compgreen compblue; ...
      linearRGB(1:6,:) ;...
      compred compgreen compblue; red green blue;...
      linearRGB(7:44,:)];
  
elseif pos==2
  
  linearRGB = [linearRGB(1:6,:); red green blue;...
      compred compgreen compblue;...
      linearRGB(7:12,:); compred compgreen compblue;...
      red green blue; linearRGB(13:44,:)];
  
elseif pos==3
  
  linearRGB = [linearRGB(1:32,:); red green blue;...
      compred compgreen compblue;...
      linearRGB(33:38,:); compred compgreen compblue;...
      red green blue;...
      linearRGB(39:44,:)];
  
elseif pos==4
  
  linearRGB = [linearRGB(1:38,:); red green blue;...
      compred compgreen compblue;...
      linearRGB(39:44,:); compred compgreen compblue;...
      red green blue]

elseif pos==5
  
  linearRGB = [linearRGB(1:9,:); red green blue;...
      linearRGB(10:13,:); compred compgreen compblue; ...
      linearRGB(14:31,:); compred compgreen compblue; ...
      linearRGB(32:35,:); red green blue;...
      linearRGB(36:44,:)]
  
else
  error = 'Invalid position!'
end
  
% Sanity check
size(linearRGB)
newmap = linearRGB;

% Gamma correction routine

maxQ = size(monitorInvGam,1);
linearRGB = scale(linearRGB,1,maxQ,0,255);
correctedRGB =  monitorInvGam(round(linearRGB))/255;

figure('position',[0 0 800 600],...
       'units','pixels',...
       'resize','off',...
       'numbertitle','off'); 

colormap(correctedRGB);

image(testImage); axis image;
axis off;
