function out = fshift(x1,x2)

%fshift  
%
%   out = fshift(x1,x2) returns the maximum shift between
%   two signals of the same size. out is the value of the
%   maximum shift between the two signals.
%
%   See also: maxt, gowave2, go2, twomicplot, blargh3.


%Check if the two vectors are of the same size
if size(x1) ~= size(x2),
   'Matrix dimensions must agree.'
   out = NaN,
   return,
end

%Take the middle half "chunk" of one of the vectors (x2 in this case)
%middlex2 is the middle half chunk of x2
N = max(size(x1));
startindex = N/4+1;
middlex2 = x2(startindex:startindex + N/2 - 1);


%create a vector of same length as x1, x2 with middle chunk
%of x2 called newx2
newx2a = [zeros(1,startindex), middlex2];
newx2 = [newx2a, zeros(1,N-max(size(newx2a)))];


%flip newx2 around for convolution
newx2 = fliplr(newx2);

%%nn=0:N-1;

filt = [ones(1,N/8), zeros(1,3*N/4),ones(1,N/8)];

%convolute newx2 with x1 to compare where they are very close
%(i.e. where the inner product is very, very big)


val = real(ifft( fft(x1).*fft(newx2).*filt));

val = fftshift(val);
val=val(1:(max(size(val))) -3);		%3 is centering factor. Need signals of large enough length

%EXPERIMENTAL, TRIMMING THE SHIFT VECTOR:
p=max(size(val));
q = (p-1)/4;
val=val((q+1):(p-q));



%figure
%L = (max(size(val)) - 1)/2
%L2 = 128
%t = -L2:L2;
%L+1-L2
%L+1+L2
%stem(t,val(L+1-L2:L+1+L2));


%calculate maximum shift
out=maxt(val);

clear newx2a newx2 middlex2


%---------------------------------------------------------
function T = maxt(x);

%maxt  
%
%   T = maxt(x) returns the maximum shift between two signals
%   which have been convoluted using fshift and assigned to x.
%   maxt takes the first shift (left or right) which matches
%   the signal peak. 
%
%   See also: fshift, gowave2, go2, twomicplot, blargh3.


N = max(size(x));		% Note N is odd since it is the
						% result of the convolution of
						% two even length vectors.
                              
maxval = max(x);		% Maximum value in x

mid = (N+1)/2;			% middle value for vector
						% note mid is an integer since N
						% is always odd


% compare the value at each x point to the max value, returns the index that cooresponds to the max value

for i = 0:mid-1
   
   if x(mid - i) == maxval
   	T=-i;,return 
	end
 
   if x(mid + i) == maxval
      	T=i;,return 
      	end
end
