function xwdwrite(M,CM,fname)
%XWDWRITE  Write a XWD (X window dump) file to disk.
%	XWDWRITE(X,MAP,'filename') writes an XWD file containing the
%	indexed image X and colormap MAP to a disk file called 'filename'.
%	Valid range for elements of X is from 1 to the number of entries
%	in the colormap.
%
%	The extension '.xwd'' will be added to 'filename' if it doesn't
%	already have an extension.
%
%	See also: XWDREAD, BMPWRITE, GIFWRITE, HDFWRITE, PCXWRITE, 
%	          TIFFWRITE.

%	Drea Thomas, 7-20-93.
%	Copyright (c) 1993 by The MathWorks, Inc.
%	$Revision: 1.5 $  $Date: 1993/10/21 12:59:32 $

if ~any(fname==46), fname = [fname,'.xwd']; end

%open the file with big endian format
[fid,message] = fopen(fname,'w','b');
if fid == -1
  error(['Unable to open ''',fname,''' for writing.']);
end

[a,b] = size(M);
[c,d] = size(CM);
header = [ 101+length(fname)  % Length of header
	  7                   % file_version
	  2                   % Image format 2 == ZPixmap
	  8                   % Image depth
	  b                   % Image width
	  a                   % Image height
	  0                   % Image x ofset
	  1                   % MSB first (byte order)
	  8                   % Bitmap unit
	  1                   % MSB first (bit order)
	  8                   % Bitmap scanline pad
	  8                   % Bits per pixel
	  b                   % Bytes per scanline
	  3                   % Visual class (pseudocolor)
	  0                   % Z red mask (not used)
	  0                   % Z green mask (not used)
	  0                   % Z blue mask (not used)
	  8                   % Bits per logical pixel
	  c                   % Length of colormap
	  c                   % Number of colors
	  b                   % Window width
	  a                   % Window height
	  0                   % Window upper left X coordinate
	  0                   % Window upper left Y coordinate
	  0 ];                % Window border width

fwrite(fid,header,'long');
fwrite(fid,fname);
fwrite(fid,0);
fwrite(fid,[zeros(c,1) (0:(c-1))',CM*65535,zeros(c,1)]','ushort');
fwrite(fid,M'-1);

fclose(fid);
