function out=unrle(rledata, ymax, xmax, flag, mode);
%UNRLE	Decompress Run Length Encoded vector.
%	data=UNRLE(RLEdata,Ymax,Xmax,Flag,Mode) decompresses the vector RLEdata,
%	which is compressed using Run Length Encoding. Ymax and Xmax are the 
%	maximum X and Y ranges of the uncompressed matrix. RLE sequences in
%	RLEdata are marked by the value Flag and a repeat count. The RLE flag
%	and repeat count can be stored as either a single byt or two explicit
%	bytes, depending on the value of the Mode parameter. Valid values for 
%	the Mode parameter are:
%
%	  Mode	Description
%
%		1	RLE flag is a high order set of bit(s).
%			The remaining bits in the byte represent the repeat count.
%
%		2	RLE flag is an explicit byte.
%			The following byte represents the repeat count.
%
%	For example, UNRLE(data,480,640,128+64,1) decompresses the vector data, 
%	which was stored with setting the top two bits as an RLE flag. The
%	remaining 6-bits represent the repeat count.
%
%	Note, when using Mode 1 (single byte mode), any data values that set
%	a high order bit will be stored as a RLE sequence, which can result
%	in negative compression. Mode one is not effective for data that has
%	values that may set the RLE flag bit (as in 8-bit data). Mode 2, 
%	which stores the RLE flag and repeat count as seperate bytes, is a more
%	effective method for 8-bit data.
%
%	Also note that the compressed data is assumed to be 8-bit data.

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


if (nargin<4)
	error('UNRLE requires at least 4 input arguments.');
end
if nargin==4, mode = 1; end

xpos=1;
ypos=1;
pos=1;

if (mode==2),
	while (ypos<=ymax),
		while (xpos<=xmax),
			if (rledata(pos)==flag),
				count=rledata(pos+1)-1;
				value=rledata(pos+2);
				out(ypos,xpos:(xpos+count))=ones(1,count+1).*value;
				xpos=xpos+count+1;
				pos=pos+3;
			else
				out(ypos,xpos)=rledata(pos);
				pos=pos+1;
				xpos=xpos+1;
			end;
		end;
		xpos=1;
		ypos=ypos+1;
	end;
else
	while (ypos<=ymax),
		while (xpos<=xmax),
			if (rledata(pos)>=flag),
				count=rledata(pos)-flag-1;
				value=rledata(pos+1);
				out(ypos,xpos:(xpos+count))=ones(1,count+1).*value;
				xpos=xpos+count+1;
				pos=pos+2;
			else
				out(ypos,xpos)=rledata(pos);
				pos=pos+1;
				xpos=xpos+1;
			end;
		end;
		xpos=1;
		ypos=ypos+1;
	end;
end;
