%
disp(' ');
disp(' auto_correlation.m   ver 1.2  Jun 19, 2013 ');
disp(' by Tom Irvine  Email: tom@vibrationdata.com ');
%
clear a;
clear b;
clear xc;
clear sum;
%
disp(' ');
disp(' The signal must have two columns:  time(sec) & amplitude ');
disp(' ');
%
a=input(' Enter the signal name: ');
%
m=max(size(a));
n=m;
%
dur=(a(m,1)-a(1,1));
dt=dur/(m-1);
%
disp(' ');
out1=sprintf(' dt = %8.4g sec   n=%d',dt,n);
disp(out1);
%
%
disp(' ');
disp(' Select calculation method: ')
disp('  1 = Time domain ')
disp('  2 = ifft(abs(fft(x))) ');
method=input(' ');
%
if(method==1)
    xc=zeros(2*n-1,2);
    n2=2*n;
%
    progressbar;
%
    xc(:,1)=linspace(-dur,dur,(2*n-1));
%
    clear Z;
    Z=zeros(n,1);
    p=n;
    q=n;
    for i=1:n
         progressbar(i/n);
         clear X;
         clear Y;
         X=a((1:p),2);
         Y=a((i:n),2);
         Z(i)=sum(X.*Y);
         p=p-1;
    end
    Z=Z/n;
%
    pause(0.1);
    progressbar(1/1);
%
    sz=size(Z);
    if(sz(2)>sz(1))
        Z=Z';
    end
    Zr=flipud(Z);
    Zr(n)=[];
    xc(:,2)=[ Zr ; Z];    
%
else
%
    ac1 = ifft(abs(fft(a(:,2), 2*n-1)).^2);
    ac1=ac1/n;
    sz=size(ac1);
    if(sz(2)>sz(1))
        ac1=ac1';
    end
    m=floor(length(ac1)/2);
    ac2 = ac1(1:m);
    ac2r=flipud(ac2);
    ac2r(m)=[];
    ac3=[ ac2r ; ac2];
    n=length(ac3);
    t=linspace(0,(n-1)*dt,n);
    t=t-t(n)/2;
    [~,I] = min(abs(t));
    t(I)=0;
    sz=size(t);
    if(sz(2)>sz(1))
        t=t';
    end
    xc=[t,ac3];
%
end    
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
    clear C;
    clear I;
    [C,I]=max(xc);
    xmax=xc(I(2),2);
    tmax=xc(I(2),1);
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
    figure(1);
    plot(a(:,1),a(:,2));
    title('Time History');
    xlabel(' Time(sec) ')
    grid on;
%
    disp(' ');
    out1=sprintf(' Maximum occurs at %6.4g sec  Amp = %8.4g',tmax,xmax);
    disp(out1);
%
    figure(2);
    plot(xc(:,1),xc(:,2));
    xlabel(' Delay(sec) ');
    out1=sprintf(' Autocorrelation   Max at %6.4g sec  Amp=%8.4g',tmax,xmax);
    title(out1);
    grid on;
%