function r = MR( X, Q, varargin )
%MR rank data using Manifold Ranking
time=cputime;
ip = inputParser;
ip.FunctionName = 'MR';
ip.addRequired('X', @ismatrix);
ip.addRequired('Q', @ismatrix);

ip.addOptional('mode', 5, @isnumeric);
ip.addOptional('W', [], @ismatrix);
ip.addOptional('k', 16, @isnumeric);
ip.addOptional('alpha', 0.99, @isnumeric);
ip.addOptional('lambda', 0, @isnumeric);
ip.parse(X, Q, varargin{:});
par = ip.Results;
mode = par.mode;
W = par.W;
k = par.k;
alpha = par.alpha;
lambda=par.lambda;

if isempty(W)
    W=constructW(X, struct('k', k, 'bSelfConnected', false));
end
D = sum(W, 2);
tmp = find(D<1e-21);
D = D.^-0.5;
D(tmp) = 0;
D = diag(D);
W = D*W*D;
%L = diag(D)-W;
y = zeros([size(X, 1), length(Q)]);
for i = 1:length(Q)
    y(Q(i), i) = 1;
end

W = eye(size(W))-W.*alpha;
%W = (1-alpha)*eye(size(W))+alpha*L;
score = W\y;   %multiply -1 to get distance function
r = [];
score=(-1)*score;
r.f = score;
if mode>0
  r = computeV(X', r.f, W, lambda);
  gdl_draw(X,Q,r.mats,r,mode);
end
r.time=cputime-time;
end


