function [RHO,SIG,RANK] = rankcorr(X,tail)
%RANKCORR Spearman rank order correlation.
%	[RHO,SIG,RANK] = RANKCORR(X,TAIL) returns a matrix RHO of the
%	Spearman rank order correlation coefficients calculated from
%	an input matrix X whose rows are observations and whose
%	columns are variables.
%
%	A matrix SIG of the significance of each RHO and
%	a matrix RANK of the calculated rankings are also returned.
%
%	TAIL is an optional parameter to indicate whether the
%	significance of rho should be calculated for one-sided or
%	two-sided hypotheses, with default value 1 (one-sided).

% Jon Garibaldi: University of Plymouth: 31st Jan 1997
%

if nargin < 1
    error('Requires at least one input argument.'); 
end

if nargin < 2
	tail= 1;
end

if tail ~= 1 & tail ~= 2
	error('Arg "tail" must be 1 (one-sided) or 2 (two-sided).');
end

[m, n]= size(X);
if m < 2 | n < 2
	error('First argument must be at least a 2x2 matrix.');
end

% get the rankings and calc the correlation coefficient for the ranks
RANK= ranks(X);
RHO= corrcoef(RANK);

if nargout > 1
	if m <= 30
		T= RHO .* sqrt((m - 2) ./ (1 - RHO .^ 2 + eps));
		SIG= (0.5 - abs(tcdf(T, m - 2) - 0.5)) * tail
	else
		Z= RHO .* sqrt(m - 1);
		SIG= (0.5 - abs(normcdf(Z) - 0.5)) * tail
	end
end

