% Get order loop: main loop in get the leaves order.
% 10may11
% B

%% Previous: orderpointers
function[y,e,r,addtolistl1,addtolistl2,addtolistn1,addtolistn2]=orderloop(z,leavesorder,nodesorder,matrix,n)
e=0;
r=0;
addtolistl1=0;
addtolistn1=0;
addtolistl2=0;
addtolistn2=0;
% get nextnode value
[y,i,j]=findnode(z,matrix);

[validation,k]=validate(z,leavesorder,nodesorder,matrix,n);
if validation==0;
[found]=findorder(z,nodesorder);
if found==0
    [foundpointer1,foundpointer2,i]=findpointer(z,matrix);
end
end

% determine minimum value
j=1;
a=matrix(i,j);
b=matrix(i,j+1);
[l,h]=whosless(a,b);
if l<=n
    found=findorder(l,leavesorder);
    if found==0
        addtolistl1=l;
        
        
    end
else
    found=findorder(l,nodesorder);
    if found==0
        [validation,k]=validate(l,leavesorder,nodesorder,matrix,n);
        if validation==0
        e=l;
        else
            addtolistn1=l;
        
        end
    
    
        
    end
    
end


if h<=n
    found=findorder(h,leavesorder);
    if found==0
        addtolistl2=h;
        
        
    end
else
    found=findorder(h,nodesorder);
    if found==0
      [validation,k]=validate(h,leavesorder,nodesorder,matrix,n);
    if validation==0
        r=h;
    else
        addtolistn2=h;
    end   
        
    end
   
end


end
