function tval = spear(data,stimvector);
%function tval = spear(data,stimvector);
%
% assumes data is in second dimension of the matrix, 
%  ie correlates data(n,:) with stimvector(n,:)

%  Ref:  Numerical Recipes in C, 2d ed. Page 640

% ---------------------------------
% Copyright (c) 2003 Serge Dumoulin and Rick Hoge
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License version 2
% as published by the Free Software Foundation.
% ---------------------------------


if nargin < 2,
   help(mfilename);
   return;
end;

if (size(stimvector,1)~=size(data,1) | size(stimvector,2)~=size(data,2)),
  disp(sprintf('Error: different sizes data [%d %d] and stimvector [%d %d]',...
                size(data,1),size(data,2),size(stimvector,1),size(stimvector,2)));
  return;
end;

tval=zeros(size(data,1),1);
for n=1:size(data,1), % must vectorize at some point
   % generate rank vector for s:
   s = tierank( stimvector(n,:)' );
   s = s-ones(size(s)).*mean(s);

   % generate rank vector for data:
   v = tierank(data(n,:));
   v = v-ones(size(v)).*mean(v);

   %% now calculate linear correlation coeff between the ranked data sets
   div=(sqrt(sum(v.^2)).*sqrt(sum(s.^2)));
   if div~=0,
      cc = v*s./div;
      if cc == 1,
         tval(n)=Inf;
      else,
         tval(n)=cc.*sqrt( (length(v)-2) / (1-cc^2) ); 
      end;
   else,
      tval(n)=0;
   end;
end;