function [xa,ya,dd] = alignsignals(x,y,varargin)
%MATLAB Code Generation Library Function

%   Copyright 2006-2022 The MathWorks, Inc.
%#codegen

narginchk(2,12);
coder.internal.prefer_const(varargin);
validateattributes(x,{'numeric'},{'vector'},'alignsignals','X');

validateattributes(y,{'numeric'},{'vector'},'alignsignals','Y');

lx = coder.internal.indexInt(length(x));
ly = coder.internal.indexInt(length(y));

ONE = coder.internal.indexInt(1);
ISROWX = coder.internal.isConst(isrow(x)) && isrow(x);
ISROWY = coder.internal.isConst(isrow(y)) && isrow(y);

method = 'xcorr';
maxlag_default = max(lx,ly) - 1;
minPeakHeight = -inf;
minPeakProminence = 0;
peakNum =1;
stateLevels = [];

[maxlag, isLegacy, isTruncate] = ...
    signal.internal.alignsignals.legacyParser(maxlag_default,varargin{:});

if ~isLegacy
    [method,maxlag,isTruncate,peakNum,minPeakProminence,minPeakHeight,stateLevels] = signal.internal.alignsignals.parseNVPairs(maxlag_default,...
        varargin{:});
end

% Estimate delay between X and Y.
d = signal.internal.alignsignals.estimateDelay(x,y,maxlag,minPeakHeight,...
    minPeakProminence,peakNum,method,stateLevels);
di = coder.internal.indexInt(round(d));

% Determine the initial index.
if di == 0
    % Signals are already aligned. Start copying into index = 1.
    ix0 = ONE;
    iy0 = ONE;
elseif di > 0
    % X is delayed wrt Y. Shift X to the right by di.
    ix0 = di + 1;
    iy0 = ONE;
else
    % Y is delayed wrt X. Shift Y to the right by abs(di).
    ix0 = ONE;
    iy0 = 1 - di;
end
% Determine the output lengths.
if isTruncate
    lxa = lx;
    lya = ly;
    if ix0 > lx
        coder.internal.warning('signal:alignsignals:firstInputTruncated');
    end
    if iy0 > ly
        coder.internal.warning('signal:alignsignals:secondInputTruncated');
    end
else
    lxa = lx + ix0 - 1;
    lya = ly + iy0 - 1;
end
% Allocate the output arrays.
if ISROWX
    xa = zeros(1,lxa(1),'like',x);
else
    xa = zeros(lxa(1),1,'like',x);
end
if ISROWY
    ya = zeros(1,lya(1),'like',y);
else
    ya = zeros(lya(1),1,'like',y);
end
% Copy the data.
for k = ix0(1):lxa(1)
    xa(k) = x(k - ix0 + 1);
end
for k = iy0(1):lya(1)
    ya(k) = y(k - iy0 + 1);
end
% Cast di to double for third output.
dd = double(di);
end