function [img,bytes] = geread_i(data,Ndata,width,height,depth,compress,map_left,map_wide)
% [img, bytes] = geread_i(data,Ndata,width,height,depth,compress,map_left,map_wide)
%
%   Read compressed image data from the tail GE 5.x MRI image file.
%
%   data [1xndat] 	- type uint8 - a vector of input bytes containing the coded image data
%   height, width (scalars) - size of the image to be created
%   compress [1x1] 	- compression code:
%	1 - image is rectangular (not compressed or packed)
%	2 - image is packed (zeros stripped off the ends of each row)
%	3 - image is compressed (DPCM)
%	4 - image is compacked (compressed and packed)
%
%   map_left [1xheight]	-number of pixels to the left of each row in packed image (optional)
%   map_wide [1xheight]	-number of pixels in each row of a packed image (optional)


img = zeros(height, width);
bytes = 0;
last_pixel = 0;
for row=1:height,

	% packed/compacked
	if (compress == 2 | compress == 4), 
		start = map_left(row);
		lnend = start + map_wide(row);
	else,
		start = 0;
		lnend = width;
	end;

	if (compress == 3 | compress == 4), %% compressed/compacked
		while (start<lnend),
			if (bytes >= Ndata), return; end;
			bytes=bytes+1; byte = double(data(bytes));
			if bitand(byte,128),
				if (bytes >= Ndata), return; end;
				bytes=bytes+1; byte2 = double(data(bytes)); 
				if bitand(byte,64),      
					%% next word
					if (bytes >= Ndata), return; end;
					bytes=bytes+1; byte = double(data(bytes)); 
					last_pixel=bitshift(byte2,8)+byte;
				else,                  
					%% 14 bit delta
					byte = bitand(byte,63);
					if bitand(byte,32), %% negative number
						byte = byte-64;
					end;
					last_pixel = last_pixel + ...
						(bitshift(byte,8)+byte2);
				end;
			else,                          %% 7 bit delta
				if bitand(byte,64), byte = byte-128; end;
				last_pixel=last_pixel+byte;
			end;
			start = start+1;
			img(row,start) = last_pixel;
		end;
	else,
		while (start<lnend),
			if (bytes >= Ndata), return; end;
			bytes=bytes+1; byte2 = double(data(bytes));
			if (bytes >= Ndata) return; end;
			bytes=bytes+1; byte = data(bytes);
			u=bitshift(byte2,8)+byte;
			start=start+1;
			img(row,start) = u;
		end;
	end;
end;

