function Hq = dfilt2qfilt(H,Hq)
%DFILT2QFILT Convert DFILT object to QFILT object.
%   Hq = dfilt2qfilt(H,Hq_in) converts DFILT object H to QFILT object Hq
%   using Hq_in as a starting point.

%   Thomas A. Bryan
%   Copyright 1988-2000 The MathWorks, Inc.
%   $Revision: 1.8 $  $Date: 2000/06/15 20:04:53 $ 

wrn = warning('off');
if isa(H,'qfilt')
  % Already a qfilt.
  Hq = H;
  return
end

% Autocorrect for wrong length scale values
Hq = scalevaluefixup(Hq);

fstruc = class(H);
c = coefficients(H);
% Unwrap a single section.  E.g., convert {{b,a}} to {b,a}, 
%  but leave {{b1,a1},{b2,a2}} alone.
if ~isempty(c) & length(c)==1 & iscell(c{1})
  c = c{1};
end
switch fstruc
case {'df1','df1t','df2','df2t'}
    % c = {num,den}
    Hq = set(Hq,fstruc,c);
case 'sos'
    % c = {sos,g}
    Hq = set(Hq,'df2t',sos2cell(c{1}),'scale',c{2});
case 'latcallpass'
    % latcallpass: c = {k}
    Hq = set(Hq,'latcallpass',c);
case 'latcarma'
    % latticearma: c = {k,v}
    Hq = set(Hq,'latticearma',c);
case 'latcma'
    % latticema:   c = {k}
    Hq = set(Hq,'latticema',c);
case 'latcmax'
    % latcmax:     c = {k}
    Hq = set(Hq,'latcmax',c);
case 'ssd'
    % statespace:  c = {A,B,C,D}
    Hq = set(Hq,'statespace',c);
case 'dffir'
    % direct form FIR: c = {num}
    Hq = set(Hq,'fir',c);
case 'dftfir'
    % direct form transposed FIR: c = {num}
    Hq = set(Hq,'firt',c);
case 'dfsymfir',
    % symmetric direct form FIR: c = {num}
    Hq = set(Hq,'symmetricfir',c);
case 'dfasymfir'
    % antisymmetric direct form FIR: c = {num}
    Hq = set(Hq,'antisymmetricfir',c);
case 'latcca',
    % lattice coupled-allpass
    [k1,k2,beta] = getcacoefss(H);   
    Hq = set(Hq,'latticeca',{k1,k2,beta});
case 'latccapc',
    % power complementary lattice coupled-allpass
    [k1,k2,beta] = getcacoefss(H);
    Hq = set(Hq,'latticecapc',{k1,k2,beta});
case {'ca','capc','cas','par'}
    % not handled by qfilt, return a df2t
    [b,a] = tf(H);
    Hq = set(Hq,'df2t',{{b,a}});
otherwise
    error('Unrecognized filter structure.')
end
warning(wrn)

%-------------------------------------------------------------
function [k1,k2,beta] = getcacoefss(H)
% Get the coefficients of a coupled allpass DFILT

% Get the first parallel branch
H1 = section(H,1);
% Get the lattice allpass section of this branch
H12 = section(H1,2);
k1 = lattice(H12);

% Get the second parallel branch
H2 = section(H,2);
% Get the lattice allpass section of this branch
H22 = section(H2,2);
k2 = lattice(H22);
% Get the scalar section of this branch
H21 = section(H2,1);
num = tf(H21);
beta = 2*num; % Compensate for the 1/2 at construction
