function pcxwrite(X,map, filename);
%PCXWRITE Write a PCX (ZSoft Paint Format) file to disk.
%	PCXWRITE(X,MAP,'filename') writes a PCX 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 '.pcx' is assumed.
%
%	See also: PCXREAD, BMPWRITE, GIFWRITE, HDFWRITE, TIFFWRITE,
%             XWDWRITE.

%	Mounil Patel 7/20/93
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.7 $  $Date: 1993/10/21 12:59:32 $

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

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

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

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

fwrite(fid,10,'uchar'); % PCX ID
fwrite(fid,5,'uchar');  % PCX Version #

nEncoding=1;
fwrite(fid,nEncoding,'uchar');
nBits=8;
fwrite(fid,nBits,'uchar');
nXmin=0;
fwrite(fid,nXmin,'short');
nYmin=0;
fwrite(fid,nYmin,'short');
[nVres,nHres]=size(X);
nXmax=nHres-1;
fwrite(fid,nXmax,'short');
nYmax=nVres-1;
fwrite(fid,nYmax,'short');
fwrite(fid,nHres,'short');
fwrite(fid,nVres,'short');
nHPalette=zeros(1,48);
fwrite(fid,nHPalette,'uchar');
nReserved=0;
fwrite(fid,nReserved,'uchar');
nPlanes=1;
fwrite(fid,nPlanes,'uchar');
nBytesPerLine=nHres;
fwrite(fid,nBytesPerLine,'short');
nHPaletteInf=0;
fwrite(fid,nHPaletteInf,'short');
nVidX=0;
fwrite(fid,nVidX,'short');
nVidY=0;
fwrite(fid,nVidY,'short');
nBlanks=zeros(1,54);
fwrite(fid,nBlanks,'uchar');

X=X'-1;
rledata=rle(X,192,1);
fwrite(fid,rledata,'uchar');

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

map=(map').*255;
map=map(:);
fwrite(fid,map,'uchar');
fclose(fid);
