function [ D ] = adj2dist( A , penalize , quiet )
%ADJ2DIST  converts adjacency matrix to distance matrix
%
%   ADJ2DIST(A , penalize ) returns the distance matrix for 
%       the adjacency matrix A:  the element d_ij corresponds
%       to the length of the shortes path between nodes i 
%       and j.
%
%       If two nodes are not are not reachable the corresp.
%       entry is either set to zero (if penalize = 0, def.)
%       or  n  (if penalize = 1).

if nargin < 1
	error('Please input adjacency matrix !');
else
	n = size(A,1);
 	if n ~= size(A,2)
 		error('Please input SQUARE matrix !');
 	end
	if nargin < 3
		quiet = false;
	end
	if nargin < 2
		penalize = false;
	end
end

% some initialisation
nn = n^2; m = 0; count = []; deltannz = 42; warning off; d = [];
D = zeros(n,n);

A = logical(A); Asum2 = logical(speye(n)); Am = Asum2;
while (nnz(Asum2) ~= nn) && (deltannz ~= 0) && (m <= n)
	m = m + 1; Am = logical(double(Am)*A);
	Asum1 = Asum2; Asum2 = Asum1 | Am;
	D = D + m*xor(Asum1,Asum2);
	deltannz = nnz(Asum2)-nnz(Asum1); % increase of new shortest paths
	count(m) = deltannz; % store increase
end

if penalize
	D(find(D==0)) = n;
	D = D - n*eye(n);
end

if ((deltannz == 0) || (m == n)) && ~quiet
	disp('NOT CONNECTED !');
end

warning on;