function [b,a,q]=ca2tf(d1,d2,beta)
%CA2TF Coupled allpass to transfer function conversion.

%   Copyright 1999-2023 The MathWorks, Inc.

narginchk(2,3);

if nargin == 2
   beta = 1; % Assume beta equal to one if not specified.
end

% Make sure D1 and D2 are rows
d1 = d1(:).';
d2 = d2(:).';

% Compute the numerators and denominator
[b,a,q] = computenumNden(d1,d2,beta);


%---------------------------------------------------------------------------
function [b,a,q] = computenumNden(d1,d2,beta)
%COMPUTENUMNDEN  Compute the numerator, denominator and power complementary
%                numerator coefficients, given allpass denominators.


% Form the coupled-allpass filter
h = cascade(dfilt.scalar(1/2),...
    parallel(dfilt.df2(conj(beta)*conj(fliplr(d1)),d1),...
    dfilt.df2(beta*conj(fliplr(d2)),d2)));

% norm(beta-1,inf) < eps^(2/3) is a better check for beta == 1
if isreal(d1) && isreal(d2) && (norm(beta-1,inf) < eps^(2/3))
    g = cascade(dfilt.scalar(1/(2)),...
        parallel(dfilt.df2(conj(fliplr(d1)),d1),...
        cascade(dfilt.scalar(-1),dfilt.df2(conj(fliplr(d2)),d2))));
else
    % Form power complementary filter
    g = cascade(dfilt.scalar(1/(2*1j)),...
        parallel(dfilt.df2(-conj(beta)*conj(fliplr(d1)),d1),...
        dfilt.df2(beta*conj(fliplr(d2)),d2)));
end

[b,a] = tf(h);

q = tf(g);    
    
% Get rid of roundoff imaginary parts
a = signalpolyutils('imagprune',a);
b = signalpolyutils('imagprune',b);
q = signalpolyutils('imagprune',q);
  
% [EOF] - ca2tf.m

