function convertxyzimage (fnamein, fnameout);

% Usage convertxyzimage (XYZ .mat file name, CMYK .mat file name)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convertxyzimage.m                 %
% written 3/5/00 by Ben Olding      %
% Takes in an image with xyz data   %
% & creates a cmyk image            %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Requires: MasterDataList.mat, xyz2cmy.m,
%           findtetra.m, tetravolume.m,
%           coplanar.m

% fnamein is a .mat file with xyz data in xyzimage

load MasterDataList;

load (fnamein);
row = size(xyzimage,1);
col = size(xyzimage,2);

x = xyzimage(:,:,1);
y = xyzimage(:,:,2);
z = xyzimage(:,:,3);

% converts each pixel to cmy
for i = 1:row,
  for j = 1:col,
    [C M Y] = xyz2cmy([x(i,j) y(i,j) z(i,j)], MasterDataList);     
    c(i,j) = C;
    m(i,j) = M;
    y(i,j) = Y;
  end;
end;

cmykimage(:,:,1)=c;
cmykimage(:,:,2)=m;
cmykimage(:,:,3)=y;

%%% Calculates black from cmy data
warning off;
k = min(cmykimage,[],3);
c=(c-k)./(1-k);
m=(m-k)./(1-k);
y=(y-k)./(1-k);

I = find (k==1);
c(I) = 0;
m(I) = 0;
y(I) = 0;
warning on;

cmykimage(:,:,1)=c;
cmykimage(:,:,2)=m;
cmykimage(:,:,3)=y;
cmykimage(:,:,4)=k;

save(fnameout,'cmykimage');

