function [X,MAP]=classres(x,class,glevels)
%CLASSRES  Visualize classification results using colorkey
%
%	classres(x,class) displays the image x with each class having a
%	different color, determined by class, and each class having 64
%	graylevels.
%
%	classres(x,class,glevels) uses glevels gray levels.
%
%	[x,map]=classres(...) returns the index image and the colormap.

if nargin<3,
  glevels=64;
end

clf;
class=class-min2(class)+1;
if max2(class)>21,
  error('Maximum 21 classes may be visualized');
end
x=round(scale(x,1,glevels));
map=[];
colorcomp=[0 0 1;0 1 0;1 0 0;0 1 1;1 0 1;1 1 0;1 1 1];
colorcomp=[colorcomp;0.6*colorcomp;0.3*colorcomp];
basemap=(1:glevels)'/(glevels);
for i=1:max2(class),
  x=x+glevels*(i-1).*(i==class);
  map=[map
    [ colorcomp(i,1)*basemap' 
      colorcomp(i,2)*basemap' 
      colorcomp(i,3)*basemap' ]'];
end
image(x);
colormap(map);
h=colorbar;
set(h,'YTick',glevels*[1:max2(class)]-glevels/2);
set(h,'YTickLabels',[1:max2(class)]);
set(h,'YDir','reverse');

if nargout>0,
  X=x;
  if nargout>1,
    MAP=map;
  end
end
