function [r, lag, t] = corr_cross(signal, wind, num_av, step, f_ACP)

f_ACP = f_ACP*1e6;

n = fix((1 + max(size(signal))-wind)/step); %число окон
t = zeros(n,1);

wind_fun = 0.5*(1-cos(2*pi*(1:wind)/(wind-1))); % оконная функция
Msignal = zeros(wind,n);
Msignal1 = zeros(wind,n,size(signal,2));

for k = 1:size(signal,2)

for j = 1:n
t(j) = step*j*1e3/f_ACP; % только для step = wind/2!!!!!!
Msignal(1:wind,j) = signal(1 + (j-1)*step:(j-1)*step + wind, k).*wind_fun'; %разбивает на окна
end

t = average(t, num_av); %

Msignal(1:wind,:) = Msignal(1:wind,:) - ones(wind,1)*mean(Msignal); %убирает среднее
Msignal = Msignal./repelem(std(Msignal), size(Msignal,1),1);
Msignal1(:,:,k) = Msignal;
end

r = zeros(wind*2-1, k*k, n);
for i = 1:length(t)
[r(:,:,i), lag] = xcorr(squeeze(Msignal1(:,i,:)), 'coeff');
end

% [r, lag] = xcorr(Msignal);

lag = lag./f_ACP*1e6;
end

function [ out ] = average(in, num_av )
%усредняет по num_av строк

num_av = fix(num_av);

if num_av == 1

out = in;

elseif size(in,3) == 1
out = zeros(fix(size(in,1)/num_av), size(in,2));

for k = 1: fix(size(in,1)/num_av)
out(k,:) = mean(in((k-1)*num_av + 1:k*num_av, :));
end
else
out = zeros(size(in,1), size(in,2), fix(size(in,3)/num_av));
for k = 1: fix(size(in,1)/num_av)
out(:,:,k) = mean(in(:, :, (k-1)*num_av + 1:k*num_av), 3);
end

end

end