% DATAOUT=BLOCK_FILTER(BLOCK,DATA) 
%
% BLOCK_FILTER() uses the BLOCK type map of a file with
% numerical entries given by DATA and defines blocked
% data regions as well as the sizes of the blocks.
%

function [bsize,xe,ye,y,ly,x,lx]=block_filter(block,data)

y=[];ly=[];
ybs=size(block,1);
xbs=size(block,2);
pos=1;bcount=1;y(1)=1;ly(1)=1;
for il=2:ybs
	if (block(pos,:)==block(il,:))
		ly(bcount)=ly(bcount)+1;
	else
		bcount=bcount+1;
		pos=il;y(bcount)=pos;ly(bcount)=1;
	end
end

ys=nnz(y);
x=sparse(0);lx=sparse(0);
xep=[];yep=[];bsizep=[];nump=0;
for ic=1:ys
	pos=y(ic);bcount=0;flag=0;
	for il=1:xbs
		if (block(pos,il)==1)
			if (flag==0)
				flag=1;
				bcount=bcount+1;lx(ic,bcount)=1;x(ic,bcount)=il;
			else
				lx(ic,bcount)=lx(ic,bcount)+1;
			end
		else
			flag=0;
		end
	end
	for ico=1:bcount
		nump=nump+1;
		xep(nump)=x(ic,ico);
		yep(nump)=y(ic);
		bsizep(nump)=lx(ic,ico)*ly(ic);
	end
end

numz=nnz(bsizep);
bsize=abs(sort(-bsizep));
xe=sparse(0);ye=sparse(0);
for in=1:numz
	flag=0;
	for is=numz:-1:1
		if (bsizep(is)==bsize(in))
			bsizep(is)=0;
			if (in>1)
				if (bsize(in)==bsize(in-1))
					icx=icx+1;
					xe(icy,icx)=xep(is);
					ye(icy,icx)=yep(is);
				else
					icx=1;icy=icy+1;
					xe(icy,icx)=xep(is);
					ye(icy,icx)=yep(is);					
				end
			else
				icx=1;icy=1;
				xe(icy,icx)=xep(is);
				ye(icy,icx)=yep(is);
			end
			flag=1;
		end
		if (flag==1)
			break;
		end
	end
end





