function dlmwrite(filename, m, dlm, r, c)
%DLMWRITE Write a matrix to an ASCII delimited file.
%	DLMWRITE(FILENAME, M, DLM, R, C) writes matrix M into FILENAME,
%	starting at offset row R, and column C in the file, with delimiter DLM.
%	DLMWRITE(FILENAME, M) writes matrix M into FILENAME.
%	This is equivalent to R=C=0, since the upper left cell
%	in a spreadsheet is referenced by (0,0) and with a comma delimiter.
%	NOTE: Any elements whose value is 0 will be omitted.  For example,
%	The array [1 0 2] will appear in a file like '1,,2'.
%
%	See also CSVREAD, WK1READ, WK1WRITE.


%		Brian M. Bourgault 10/22/93
%	Copyright (c) 1984-94 by The MathWorks, Inc.
%
	%
	% test for proper filename
	%
	if ~isstr(filename),
		error('FILENAME must be a string.');
	end;

	if nargin < 2
		error('Requires at least 2 input arguments.');
	end

	%
	% delimiter defaults to Comma for CSV
	%
	if nargin < 3
		dlm = ',';
	end

	%
	% open the file Lotus uses Little Endian Format ONLY
	%
	fid = fopen(filename ,'wb');
	if fid == (-1)
		error(['Could not open file ' filename]);
	end
	%
	% check for row,col offsets
	%
	if nargin < 4
		r = 0;
	end
	if nargin < 5
		c = 0;
	end
	
	%
	% dimensions size of matrix
	%
	[ br bc ] = size(m);
	
	%
	% start with offsetting row of matrix
	%
	for i = 1:r
		for j = 1:c
			fwrite(fid, dlm, 'uchar');	
		end
		for j = 1:bc
			fwrite(fid, '0', 'uchar');	
			fwrite(fid, dlm, 'uchar');	
		end
		fwrite(fid, 10, 'char'); % this may \r\n for DOS 
	end
	%
	% start dumping the array, for now number format float
	%
	for i = 1:br
		%
		% start with offsetting col of matrix
		%
		for j = 1:c
			fwrite(fid, dlm, 'uchar');	
		end

		for j = 1:bc
			if(m(i,j) ~= 0)
				str = num2str(m(i,j));
				fwrite(fid, str, 'uchar');	
			end
			if(j < bc)
				fwrite(fid, dlm, 'uchar');	
			end
		end
		fwrite(fid, 10, 'char'); % this may \r\n for DOS 
	end

	% close files
	fclose(fid);
