function allCG = FindAllCG(neighbor, lc)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% FindAllCg use FindCG iteratively to find 
%%% all the connected subgraphs of neighbor with no more than lc nodes. 
%%%
%%% INPUT:
%%% neighbor: a graph with p nodes, in a form of p by p contingency matrix 
%%% lc: the maximum size of the CGs to be listed.
%%%
%%% OUTPUT:
%%% The output is a structure allCG with length lc, with one field
%%% named cg, allCG(ii).cg is a matrix with ii columns whose rows 
%%% stand for the indices of nodes in each size ii connected subgraph.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% size 1 connected subgraphs are the nodes themselves
[p,p0] = size(neighbor);
allCG(1).cg = (1:p)';

%% size 2 connected subgraphs are the pairs
if lc >= 2
[II, JJ] = find(neighbor);
IndIJ = logical(II < JJ);
allCG(2).cg = [II(IndIJ)'; JJ(IndIJ)']';

  %% only use FindCG to find the connected subgraphs with at least 3 nodes.
  if lc >= 3
    for ii = 3:lc
        %find all the CG with ii nodes in the graph
        allCG(ii).cg = FindCG(neighbor, allCG(ii-1).cg);
    end
  end
end
end
