function [rawindex,mean,variance,upvalue,sortvalues] = linassign(prox,nstarts)

% LINASSIGN evaluates the salience of the sum of main diagonal entries (the
% trace) in an  $n \times n$ square (but not necessarily
% symmetric) input matrix PROX  using a (linear assignment) permutation
% strategy.  The columns of PROX are randomly permutated NSTARTS times with the
% matrix trace repeatedly computed.  The original trace of PROX is RAWINDEX; the
% NSTARTS index values are given (sorted in increasing order)
% in the vector SORTVALUES; MEAN and VARIANCE are the exact mean and 
% variance of the permutation distribution assuming that all $n!$ permutations
% are equally-likely; UPVALUE is the proportion of the NSTARTS indices that
% are as large or larger than RAWINDEX (i.e., UPVALUE is the upper-tail p-value for
% the observed index RAWINDEX).

n= size(prox,1);

aone = (sum(sum(prox)))^2;

atwo = sum((sum(prox')).^2);

athree = sum((sum(prox)).^2);

afour = sum(sum(prox.^2));

mean = (sum(sum(prox)))/n;

variance = ((aone/n) - (atwo + athree) + (n*afour))/(n*(n-1));

rawindex = sum(diag(prox));

indexvals = zeros(nstarts,1);

upval = 0;

for i = 1:nstarts
    iden = 1:n;
    perm = randperm(n);
    
    indexvals(i) = sum(diag(prox(iden,perm)));
    
    if (indexvals(i) >= rawindex)
        upval = upval + 1;
    end
end

sortvalues = sort(indexvals)';
upvalue = upval/nstarts;