function listCliques = SGrowCliques(A,maxsize,minsize)
% GrowCliques consmes an adjacency matrix A, and returns a
%   list of cliques (without replications) (in cell) such that
%   the size is between [minsize,maxsize]

    n = size(A,1);
    II = zeros(n*maxsize,1);
    JJ = zeros(n*maxsize,1);
    k = 0; % count # of edges
    
    for jc = 1:n

        k = k+1; II(k) = jc; JJ(k) = jc;
        NodesToAdd = maxsize-1;
        q = logical(A(:,jc));
        
        while NodesToAdd && nnz(~q)
            NodesToAdd = NodesToAdd - 1;
           % ic = find(q==0); 
           
            k = k + 1;  JJ(k) = jc;
            
            % alternating the index that to be added,
            % so that the vertices will gather at
            % all <=m or all > m
            if mod(NodesToAdd,2) == 0
                ic = find(~q,1,'first'); 
                %II(k) = ic(1);
                %q = q | A(:,ic(1));
                II(k) = ic;
                p = logical(A(:,ic));
                q = q | p;
            else
                ic = find(~q,1,'last'); 
               % II(k) = ic(end);
               % q = q | A(:,ic(end));
                II(k) = ic;
                 p = logical(A(:,ic));
                q = q | p;
            end
        end
    end
    
    Cliques = sparse(II(1:k),JJ(1:k),1,n,n);   
    Cliques = (unique(Cliques','rows'))';
    
    inds = find(sum(Cliques,1) >= minsize);    
    numCliques = length(inds);    
    listCliques = cell(numCliques,1);
    
    for ii = 1:numCliques
        listCliques{ii} = find(Cliques(:,inds(ii)));
    end

end
