function bwout = im2bw(p1,p2,p3,level)
%IM2BW	Convert image to black and white by thresholding.
%	BW = IM2BW(X,MAP,LEVEL) converts the indexed image X with
%	colormap MAP to a black and white intensity image BW.  
%	BW is 0 (black) for all pixels with luminance less 
%	than LEVEL and 1 (white) for all other values. 
%
%	BW = IM2BW(I,LEVEL) converts the gray level intensity image
%	I to black and white.  BW is 0 (black) for all pixels with
%	value less than LEVEL and 1 (white) for all other values.
%
%	BW = IM2BW(R,G,B,LEVEL) converts the RGB image to black 
%	and white.  BW is 0 (black) for all pixels with luminance
%	less than LEVEL and 1 (white) for all other values.
%
%	See also IND2GRAY, RGB2GRAY.

%	Clay M. Thompson 10-5-92
%	Copyright (c) 1992 by The MathWorks, Inc.
%	$Revision: 1.10 $  $Date: 1993/09/09 22:18:16 $

if nargin==1, % im2bw(I)
  a = p1;
  level = [];

elseif nargin==2, % im2bw(I,level) or im2bw(a,cm)
  if size(p2,2)==3, % It is a colormap
    a = ind2gray(p1,p2);
    level = [];
  else
    a = p1;
    level = p2;
  end

elseif nargin==3, % im2bw(r,g,b) or im2bw(a,cm,level)
  if all(size(p1)==size(p3)),
    a = rgb2gray(p1,p2,p3);
    level = [];
  else
    a = ind2gray(p1,p2);
    level = p3;
  end

elseif nargin==4, % im2bw(r,g,b,level)
  a = rgb2gray(p1,p2,p3);
end

if isempty(level), % Get level from user
  level = 0.5; % Use default for now
end

bw = (a >= level);

if nargout==0, % Show results
  imshow(bw,2)
  return
end
bwout = bw;
