%
% Calculate the optimal correlation coefficient
% between two time series by shifting the second
% forwards or backwards by up to 50 percent of
% its length
%
%     [ cc, k ] = shcorr( d1, d2, [m] )
%
% where    cc = optimal correlation coefficient
%          k  = optimal shift
%          s1 = first time series
%          s2 = second time series
%          m  = returns cc at shift of m (if present)
%
% Bob Newell, April 1996
%
%----------------------------------------------------
function [ cc, k ] = shcorr( s1, s2, m )
global data
%
s1 = s1(:);
s2 = s2(:);
n = length( s1 );
data = [ s1 s2 ];
if nargin == 3,
  k = m;
  disp( [ 'Specified shift is ' num2str(k) ' points' ] );
else,
  k = 0;
  last = shcorrfn( k );
  step = 10;
  while abs( step ) > 1,
    now = shcorrfn( k + step );
    while now < last,
	  k = k + step;
	  last = now;
      now = shcorrfn( k + step );
%     [ k step now last ]
	end;
	step = - step / 2;
  end;
  k = fix( k );
  disp( [ 'Optimal shift is ' num2str(k) ' points' ] );
end;
% determine the correlation coefficients
if k < 0,
  cor = corrcoef( [ data(1:n+k,1) data(-k+1:n,2) ] );
else,
  cor = corrcoef( [ data(k+1:n,1) data(1:n-k,2) ] );
end;
disp( [ 'Correlation coefficient is ' ...
                       num2str( cor(1,2) ) ] );
cc = cor(1,2);
%------------------------------------------------------
