function x=fgpfsp(Pkp,xx)
% generate a permutation from P_t
% generation using node placements
% with ALIAS

e=10^-5;
x=[];
[n,m]=size(Pkp); % n==m

for i=1:floor(xx*n),
	ind=0;

pp=1/n;q=ones(n,1);
b=Pkp(i,:)-pp;

while sum(abs(b))>e,
  for j=1:n,
	  [c,k]=min(b);
[d,m]=max(b);
A(k)=m;
q(k)=1+c*n;
b(k)=0;
b(m)=c+d;
end
end

while(ind==0)

rr=randperm(n);
J=rr(1);

     u=rand(1);

if u<=q(J),
     xxx=J;
else
     xxx=A(J);
end

if(sum(x==xxx)==0),
     x(i)=xxx;
ind=1;
end

end

end

k=floor(xx*n)+1;
ss=0;
for j=1:n,
	if (sum(x==j)==1),
	ss=ss+Pkp(k,j);
Pkp(k,j)=0;
end
end

for j=1:n,
	if (sum(x==j)==0),
        if ss<1,
	Pkp(k,j)=Pkp(k,j)/(1-ss);
else
Pkp(k,j)=0;
end

end
end

     while k<n
     r=rand(1);
     cc=0;
     c=0;

while(r>cc),
       c=c+1;
if c<=n,
cc=cc+Pkp(k,c);
%[c,r,cc]
else
cc=cc+Pkp(k,n);
break
end
end
if(c<=n),
	  x(k)=c;
else,
  x(k)=n;
end

k=k+1;

ss=0;
for j=1:n,
	if (sum(x==j)==1),
	ss=ss+Pkp(k,j);
Pkp(k,j)=0;
end
end

for j=1:n,
	if (sum(x==j)==0),
        if ss<1,
	Pkp(k,j)=Pkp(k,j)/(1-ss);
else
Pkp(k,j)=0;
end

end
end

end

for j=1:(n),
	   if(sum(x==j)==0),
	   x(n)=j;
break;
end
end
