function stationary = textrank( graph_filename, prior_filename, lambda, stat_filename, rank_filename )
% function stationary = textrank( graph_filename, prior_filename, lambda, stat_filename, rank_filename )
% graph_filename identifies file containing graph weight matrix
% prior_filename identifies file containing values on which we should base the prior probabilities
% lambda is [0,1] trade-off parameter, with 1 being all graph-based and 0 being all prior
% stat_filename identifies file where the resulting values should be written to
% rank_filename identifies file where the rank of each item is written

debug = 1;

disp('running textrank')

% load graph weight matrix
W = load( graph_filename );

% load prior vector r
r = load( prior_filename );

n = size(W,1);

if length(r) ~= n,
  error( 'Prior prob vector is wrong length. Stop.' )
end

% create the graph-based transition matrix P
P = W ./ repmat(sum(W,2), 1, n); % row normalized

% normalize prior vector
r = r / sum(r);

% incorporate user-supplied prior probability by adding teleporting
hatP = lambda*P + (1-lambda)*repmat(r', n, 1);

if n > 1,
  % find stationary distribution of hatP:  q=hatP'*q.
  [V,D] = eigs(sparse(hatP'),1,'LR');
  stationary = abs(V); % to avoid an all-negative vector
  stationary = stationary / sum(stationary); % make it a prob dist
else,
  stationary = [1];
end

if debug,
  P
  r
  lambda
  hatP
  stationary
end

% save to file
save( stat_filename, 'stationary', '-ASCII' ) 

[val,idx] = sort( stationary, 'descend' );

ranking(idx) = [1:n];

fid = fopen( rank_filename, 'w' );
%fprintf( fid, '%d\n', ranking );
fprintf( fid, '%d\n', idx-1 );
fclose(fid);
