function A = rme( A , pn )
%RME  randomly remove egdes from graph
%
%   RME(A,pn)  removes edges from the network (given by its
%      adjacency matrix A). The no. of deleted edges depends on
%    - *probability* pn if 0 < pn < 1
%    - *number* of edges pn if pn >= 1
%
%  Last change:  10/2/2005 - Florian Knorn

if nargin < 2
	error('Please provide adjacency matrix A and probability p !');
else
	n = size(A,1);
	if n ~= size(A,2)
		error('Please input SQUARE matrix !');
	end
	if pn < 0 || (pn >= 1 && round(pn) ~= pn)
		error('pn must be a probab. (0 <= pn < 1) or an int >= 1 !');
	end
end

if pn < 1 % we're dealing with probabilities
	pn = binornd(n,pn);
end

A = logical(sparse(triu(A,1))); % only keep upper triang part

ind = find(A);      % get 1D-indexes of edges
lind = length(ind); % count those edges;
if pn > lind
	error('Cannot remove more egdes then actually exist !');
end
ind = ind(randperm(lind));  % randomly "reorder" the entries of ind

A(ind(1:pn)) = false; % set the first pn entries to zero

A = A | A';