function [yout,x] = imhist(a,cm)
%IMHIST	Display image histogram
%	IMHIST(X,MAP) displays a histogram for the image X
%	above a color strip of the colormap MAP. The colormap
%	must be at least as long as the largest index in the
%	image X.
%
%	IMHIST(I,N) displays an N-bin histogram for the intensity
%	image I above a gray color strip of length N.
%
%	[N,Y] = IMHIST(...) returns the histogram counts in N
%	and the bin locations in Y so that STEM(Y,N) can be used
%	to show the histogram.

%	Clay M. Thompson 7-7-92, partially mex-ified by
%	Joseph M. Winograd, 7-93
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.21 $  $Date: 1993/09/09 22:58:38 $

error(nargchk(1,2,nargin));

NPTS = 256;

%
%  Let MEX do the scaling.
%

if nargin==1, 
  if isgray(a), 
    n = NPTS; cm = gray(n); isGray = 1;
  elseif isind(a),
    cm = colormap; isGray = 0; n = size(cm,1);
  else
    a = mat2gray(a);
    n = NPTS; cm = gray(n); isGray = 1;
  end

elseif nargin==2
  if max(size(cm))==1, % Intensity image
    n = cm; cm = gray(n); isGray = 1;
  else
    n = size(cm,1); isGray = 0;
  end
end

%
% Do range checking in MEX file to keep MEX extra robust.
%

y = imhistc( a, n, isGray ); % Call MEX file to do work.

x = [1:n]';
if nargout==0, % Plot histogram
  stem(x,y)
  hs = gca;
  h = get(hs,'children');
  delete(h(3)) % Remove 'o's from stem plot
  limits = axis;
  limits(1) = 0.5;
  limits(2) = n+0.5;
  var = sqrt(y'*y/length(y));
  limits(4) = 2.5*var;
  axis(limits);

  % Get axis position and make room for color strip.
  pos = get(hs,'pos');
  stripe = 0.075;
  set(hs,'pos',[pos(1) pos(2)+stripe*pos(4) pos(3) (1-stripe)*pos(4)])
  set(hs,'xticklabelmode','manual')
  set(hs,'xticklabels','')

  % Create axis for stripe
  ax = axes('Position', [pos(1) pos(2) pos(3) stripe*pos(4)]);

  % Create color stripe
  if isGray,
    image([-1/(2*(n-1)) 1+1/(2*(n-1))],[0 1],1:n); colormap(cm)
  else
    image([1:n+1]-0.5,[0 1],1:n); colormap(cm)
  end
  set(gca,'yticklabelmode','manual')
  set(gca,'yticklabels','')
  limits = axis;
  if isGray,
    limits(1) = -1/(2*(n-1)); limits(2) = 1+1/(2*(n-1));
  else
    limits(1) = 0.5; limits(2) = n+0.5;
  end
  axis(limits);
  j=line(limits([1 2 2 1 1]),limits([3 3 4 4 3]));set(j,'linestyle','-')
  set(j,'color',get(gca,'xcolor'))

  % Set active axis to histogram
  axes(hs)
  set(gcf,'Nextplot','replace')

  return
end
yout = y;
