function [ A ] = gen_er( n , p  , quiet)
%GEN_ER  Generates a random graph of the Erdös-Renyi type
%
%  A = GEN_ER( n , p ) returns the adjacency matrix A of the
%      undirected graph with n nodes, every pair of nodes 
%      being connecte by an edges with the probability p.
%
%  Last change:  10/2/2005 - Florian Knorn

if nargin < 2
	error('Please provide n and p');
else
	if n < 2
		error('n must be greater or equal 2');
	end
	if p < 0 | p > 1
		error('p must be a probability, so 0 <= p <= 1 !');
	end
end

if nargin ~= 3
	quiet = 0;
end

p_ = 1-p;
n = floor(n); % make sure n is an integer
rand('state',sum(100*clock)); % reset random number generator

if mod(n,2) % n is odd
	n1 = floor(n/2); n2 = n1 + 1;
else % n is even
	n1 = n/2; n2 = n1;
end

% top left block
R = rand(n1,n1);
T = sparse(triu(R,1)); clear R;  % only keep upper triang part
[ii1,jj1] = find(T>p_); clear T; % determine "winning" edges

% top right block
R = rand(n1,n2);
[ii2,jj2] = find(R>p_); clear R; % determine "winning" edges

% bottom right block
R = rand(n2,n2);
T = sparse(triu(R,1)); clear R;  % only keep upper triang part
[ii3,jj3] = find(T>p_); clear T; % determine "winning" edges

% combine indices
ii = [ii1 ; ii2; ii3+n1]; jj = [jj1 ; jj2+n1 ; jj3+n1];

onez = true(1,length(ii));	% create vector of with what to fill A

A = sparse(ii,jj,onez,n,n); % create A

A = A | A';

if ~quiet
	disp(sprintf('Erdös-Renyi graph with %i nodes and %i edges successfully created',n,nnz(A)/2));
end