function [ListBB]=WP_BB_Listree2_D_P(En)
%building the best basis tree for 2D wavelet packet transform using the tree
%of values of the cost function 'En'  for each block of the transform
%coefficients, which are presented by a cell array

[Ben ]=WPbeN_2D_bas(En);
[ve,he]=size(Ben);

 ListBB=[];
 kk=1;
 stack=[1 1 1];
 [vs hs]=size(stack);
 while vs>0
     
     s=stack(1,:,:);
     stack=stack(2:end,:,:);
   lev=s(1);
   bv=s(2);
   bh=s(3);
   b=Ben{lev}(bv,bh);
     while b==1;
         lev=lev+1;
        bv1=2*bv; bv=2*bv-1;
        bh1=2*bh; bh=2*bh-1;
   stack=[[lev bv bh1];[lev bv1 bh];[lev bv1 bh1];stack];  
  [lev bv bh]; 
  
    b=Ben{lev}(bv,bh);
     end 
  ListBB=[ ListBB;[lev-1,bv-1,bh-1]];    
 [vs hs]=size(stack); 
 end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [BEn ]=WPbeN_2D_bas(En)
[ve,he]=size(En);
BEn=cell(ve,1);
%ve=6
 BEn{ve} =zeros(size(En{ve}));

 Ec=En{ve}; 
for kk=ve-1:-1:1
 
 Ep=En{kk};   
   E =zeros(size(Ep));
    [vp,hp]=size(Ep);
    
for vv=1:vp
    for hh=1:hp
            ep=Ep(vv,hh);
            ec=[Ec(2*vv-1,2*hh-1),Ec(2*vv-1,2*hh);Ec(2*vv,2*hh-1),Ec(2*vv,2*hh)];   
            ce=(sum(ec(:)));
            if ce<=ep
 E(vv,hh)=1; 
       Ep(vv,hh)=ce;   
            end
        end
        end
    %kk
    
   BEn{kk} =E;
   Ec=Ep;
end
    % Copyright (c) 2013. Valery A. Zheludev
   