function bmpwrite(X,map, filename);
%BMPWRITE Write a BMP (Microsoft Windows Bitmap) file to disk.
%	BMPWRITE(X,MAP,'filename') writes a BMP file containing the
%	indexed image X and colormap MAP to a disk file called 'filename'.
%	If no file extension is given with the filename, the extension
%	'.bmp' is assumed.
%
%	See also: BMPREAD, GIFWRITE, HDFWRITE, PCXWRITE, TIFFWRITE,
%	          XWDWRITE.

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

if (nargin~=3)
	error('Requires three arguments.');
end;

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

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

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

fwrite(fid,['B';'M'],'char');

[biHeight,biWidth]=size(X);
bfSize=biHeight*(biWidth+(4-rem(biWidth,4)))/4+270;
fwrite(fid,bfSize,'long');
bfReserved1=0;
fwrite(fid,bfReserved1,'short');
bfReserved2=0;
fwrite(fid,bfReserved2,'short');
bfOffBits=1078;
fwrite(fid,bfOffBits,'long');
biSize=40;
fwrite(fid,biSize,'long');

fwrite(fid,biWidth,'long');
fwrite(fid,biHeight,'long');
biPlanes=1;
fwrite(fid,biPlanes,'short');
biBitCount=8;
fwrite(fid,biBitCount,'short');
biCompression=0;
fwrite(fid,biCompression,'long');
biSizeImage=biHeight*(biWidth+(4-rem(biWidth,4)));
fwrite(fid,biSizeImage,'long');
biXPels=0;
fwrite(fid,biXPels,'long');
biYPels=0;
fwrite(fid,biYPels,'long');
biClrUsed=256;
fwrite(fid,biClrUsed,'long');
biClrImportant=0;
fwrite(fid,biClrImportant,'long');

[m,n]=size(map);
if (m~=256)
	map=[map;zeros(256-m,3)];
elseif (m>256)
 error('Colormap exceeds 256 colors! Only 8-bit BMP file output is supported.');
end;

map=[fliplr(map*255),zeros(256,1)]';
fwrite(fid,map(:),'uchar');

X=(X-1);
if (rem(biWidth,4)~=0)
	X=[X,zeros(biHeight,4-rem(biWidth,4))];
end;
X=rot90(X,3);
fwrite(fid,X(:),'uchar');

fclose(fid);

