function [X,map]=bmpread(filename);
%BMPREAD Read a BMP (Microsoft Windows Bitmap) file from disk.
%	[X,MAP]=BMPREAD('filename') reads the file 'filename' and returns
%	the indexed image X and associated colormap MAP. If no extension
%	is given for the filename, the extension '.bmp' is assumed.
%
%	See also: BMPWRITE, GIFREAD, HDFREAD, PCXREAD, TIFFREAD,
%	          XWDREAD.

%	Mounil Patel 3/10/94
%	Copyright (c) 1994 by The MathWorks, Inc.
%	$Revision: 1.11 $  $Date: 1994/03/10 21:27:12 $


if (nargin~=1)
	error('Requires a filename as an argumenty.');
end;

if (isstr(filename)~=1)
	error('Requires a string filename as an argument.');
end;

if (isempty(findstr(filename,'.'))==1)
	filename=[filename,'.bmp'];
end;

fid=fopen(filename,'rb','l');
if (fid==-1)
	error(['Error opening ',filename,' for input.']);
end;

bfType=fread(fid,2,'char');
setstr(bfType);
if (bfType~=['B';'M'])
	fclose(fid);
	error('Not a BMP file.');
end;

bfSize=fread(fid,1,'long');
bfReserved1=fread(fid,1,'short');
bfReserved2=fread(fid,1,'short');
bfOffBits=fread(fid,1,'long');

biSize=fread(fid,1,'long');
if (biSize~=40)
	fclose(fid);
	error('Not a MS Windows Device Independent Bitmap BMP file.');
end;

biWidth=fread(fid,1,'long');
biHeight=fread(fid,1,'long');
biPlanes=fread(fid,1,'short');
biBitCount=fread(fid,1,'short');
biCompression=fread(fid,1,'long');
if biCompression~=0 then
	error('Can''t load compressed format bitmaps.');
end;
biSizeImage=fread(fid,1,'long');
biXPels=fread(fid,1,'long');
biYPels=fread(fid,1,'long');
biClrUsed=fread(fid,1,'long');
biClrImportant=fread(fid,1,'long');

if (biClrUsed==0)
	nColors=2.^biBitCount;
else
	nColors=biClrUsed;
end;

% load color map now
if (biClrUsed>256)
	map=[];	% 24-bit images have no colormap
else
	map=fread(fid,4*nColors,'uchar');
	map=reshape(map,4,nColors);
	map=map';
	map=map(:,1:3);
	map=fliplr(map);
end;

map=map./255;

% read in 8-bit image data
if (biBitCount==8)
	if (rem(biWidth,4)~=0)
		XSize=biWidth+(4-rem(biWidth,4));
	else
		XSize=biWidth;
	end
	YSize=biHeight;
	Size=XSize*YSize;

	X=fread(fid,Size,'uchar');
	X=reshape(X,XSize,YSize);
	X=rot90(X);
	X=X+1;
	if (rem(biWidth,4)~=0)
		X=X(:,1:biWidth);
	end;
end;

if (biBitCount==4)
	XSize=ceil(biWidth/2);
	if (rem(XSize,4)~=0)
		XSize=XSize+rem(XSize,4);
	end;
	YSize=biHeight;
	Size=XSize*YSize;
	X=fread(fid,Size,'uchar');
	X=reshape(X,XSize,YSize);
	X=X';
	loX=X;

	index=loX>127;
	loX(index)=loX(index)-128;
	index=loX>63;
	loX(index)=loX(index)-64;
	index=loX>31;
	loX(index)=loX(index)-32;
	index=loX>15;
	loX(index)=loX(index)-16;

	X=X-loX;
	X=X./16;
	[m,n]=size(X);
	X(:,1:2:(n*2))=X;
	X(:,2:2:(n*2))=loX;
	X=flipud(X);
	X=X+1;
end;

cmax=max(max(X));
map=map(1:cmax,:);

fclose(fid);


