%=========================================================================
% E. Boutillon, 25/05/2019
%
% This function find the girth of a QC matrix. 
%=========================================================================
% Input: P, the prototype matrix,
%        N, the expension factor size.
%=========================================================================
function [min_girth] = girth_evaluation(P, N)

%%
%P = mod(P, N); % To avoid to it outside.
[dv, dc] = size(P);
P = P + 1;
M = [];
I = eye(N,N);
I = sparse(I);
 for i = 1:dv
      L = [];
      for j = 1:dc
            if P(i,j) > 0
                I_ij  = [I(:,P(i,j):end) I(:,1:P(i,j)-1)];
            else
                I_ij  = zeros(N,N);
            end;
            L     = [L I_ij];
      end
      M = sparse( [M;L]);
 end
min_girth = 1000;


 for i = 1:dc
     ind = 1 + (i-1)*N; % index of first element of the ith column.
     cn  = find( M(:,ind) == 1); % index of check connected to the variable.
     for j = 1:length(cn)-1
        X = zeros(N*dc, 1);
        Ma = M;
        Ma(cn(j), ind) = 0;
        S = zeros(dv*N,1);
        S(cn(j)) = 1;
        girth = 0;
        cpt = 1;
        while (X(ind) == 0) && (cpt < 20)
            cpt = cpt + 1;
            X = Ma'*S > 0;
            S = Ma*X;
            girth = girth + 2;
        end;
        if girth < min_girth
            min_girth = girth;
        end;

     end;
 end
 min_girth;
 
 
        