% DATAOUT=BLOCK_EXTRACT(XEIN,YEIN,Y,LY,X,LX,DATA,FLAG) 
%
% BLOCK_EXTRACTOR() uses a map of data blocks (Y,LY,X,LX) with
% numerical entries given by DATA and depending upon the vaue 
% of the FLAG either extracts the block with coordinates 
% (XEIN,YEIN) into the array DATAOUT or allows an interactive extraction 
% of the desired data block. 
%
% FLAG=0 - the biggest data block is extracted from the file 
% with FILE_NAME and placed into DATA.
%
% FLAG=1 - interactve extraction of the data block.
%
function dataout=block_extract(xein,yein,y,ly,x,lx,data,gflag)

xbs=max(max(x+lx))-1;
ybs=max(max(y+ly))-1;
ys=nnz(y);xs=size(x,2);xxs=size(x,1);
if (ys>xxs)
	x(xxs+1:ys,1)=0;
	lx(xxs+1:ys,1)=0;
end
if (gflag==1)
	figure(1);clf;
	axis([1 xbs+1 1 ybs+1]); axis square;
	title('Click on a data block to retreave a corresponding data array');
	ybs=ybs+2;
	for ic=1:ys
		xs=nnz(x(ic,:));
		for ix=1:xs
			h=patch([x(ic,ix) x(ic,ix)+lx(ic,ix) x(ic,ix)+lx(ic,ix) x(ic,ix)],...
			[ybs-y(ic) ybs-y(ic) ybs-(y(ic)+ly(ic)) ybs-(y(ic)+ly(ic))],'b');
			set(h,'EdgeColor','w');
		end
	end	
	[xcoor,ycoor]=ginput(1);
	ye=fix(ybs-ycoor);
	xe=fix(xcoor);
else
xe=xein;
ye=yein;
end

iy=1;count=0;
while((y(iy)+ly(iy))<=ye)
	xs=nnz(x(iy,:));
	for ix=1:xs
		count=count+lx(iy,ix)*ly(iy);
	end
	iy=iy+1;
end

xs=nnz(x(iy,:));xlen=0;xshift=0;flag=1;
for ix=1:xs
	xlen=xlen+lx(iy,ix);
	if ((x(iy,ix)+lx(iy,ix))<=xe)		
		xshift=xshift+lx(iy,ix);
	else
		if (flag==1)
			flag=0;iix=ix;
		end
	end
end

fprintf(1,'%s%d%s%d%s\n','Data block size is (',ly(iy),'X',lx(iy,iix),')');

dataout=[];
for iiy=1:ly(iy)
	for ix=1:lx(iy,iix)
	dataout(iiy,ix)=data(count+xshift+ix+(xlen*(iiy-1)));
	end
end





