function [type, idxchoose,  numselected, numunselected] = tjsr_selectvertex(type);
% [type, idxchoose,  numselected, numunselected] = tjsr_selectvertex(type);
% This function belongs to tjsr!
% Selects vertices for which the norm gets computed
%
% Input: 
%   type            type-struct from tjsr
%
% Output:
%   type            type-struct for tjsr
%   idxchoose       linear index (array) of selected vertices
%   numselected     number of selected vertices
%   numunselected   number of unselected vertices
%
% Written by tommsch, 2018

idxnotnan=isnan([type.cyclictree.norm{:}]); %only select vertices which are not computed yet

if(type.opt.naturalselectiontype>0)
    minchoose=ceil(abs(type.opt.naturalselection)/type.counter.nummatrix)+1;
else
    minchoose=ceil(abs(type.opt.naturalselection));
end
maxchoose=minchoose*4;

numall=nnz(idxnotnan);

switch abs(type.opt.naturalselectiontype)
    case inf
         switch mod(type.counter.iteration,4);
             case {1,2,3}; 
                 val=[type.cyclictree.normest{:}];
             case 0; 
                val=[type.cyclictree.normparent{:}];
         end
    case 1; val=[type.cyclictree.normest{:}];
    case 2; val=[type.cyclictree.normparent{:}];
    case 3; val=[type.cyclictree.rho{:}];
        
    %values from 100 to 999 denote selection rules which are not suitable for production
    case 100; val=-[type.cyclictree.rho{:}]; %DEBUG, the algorithm does not terminate with this selection for certain matrices: B=[1 1; 0 1]; tjsr({1/2*B,1/2*B',B,B'},'ordering',{[1],[2]},'naturalselectiontype','-rho','fastnorm',0,'testspectralradius',-inf,'plot','polytope')
end
  
[idxchoose,~,barrier] = chooseval(val, [minchoose, maxchoose] , idxnotnan); 

if(type.opt.verbose>4);
    figure(1148242414); clf; 
    semilogy(sort(val),'.'); hold on;
    plot(barrier*ones(1,size(val,2)),'r-');
end

%select all children of each parent which has at least on selected child.
if(type.opt.naturalselectiontype>0 && minchoose<inf)
    LL=cellfun(@sum,type.cyclictree.L);
    valcum=[0 cumsum(LL)];
    for i=1:type.counter.numordering
        idx=idxchoose(valcum(i)+1:valcum(i+1));
        parentidx=unique(type.cyclictree.parent{i}(idx));
        idxchoose(valcum(i)+1:valcum(i+1))=ismember(type.cyclictree.parent{i},parentidx) & idxnotnan(valcum(i)+1:valcum(i+1));
    end
end

numselected=nnz(idxchoose);
numunselected=numall-numselected;
    
end





function dummy; end %#ok<DEFNU> %Generates an error, if the 'end' of a function is missing. 