
function [Bmd,Amd,FIRd]=parf2delparf(Bm,Am,FIR);

%PARF2DELPARF converts a normal parallel filter to a delayed one.
%   [Bmd,Amd,FIRd]=PARF2DELPARF(Bm,Am,FIR) converts the normal (non-delayed)
%   parallel filter to the delayed parallel filter where the IIR part is delayed
%   so there is no overlap between the FIR and IIR responses, which leads to improved
%   numerical properties.
%
%   Te conversion is accurate up to numerical precision, so
%   PARFILT(Bm,Am,FIR,input) gives the same result as
%   DELPARFILT(Bmd,Amd,FIRd,input).
%
%   Note that if there is a long FIR part, then it is numerically better to
%   design the delayed parallel filter directly by the DELPARFILTDES command.
%   
%   For the details, see:
%
%   Balazs Bank and Julius O. Smith, III, "A delayed parallel filter structure
%   with an FIR part having improved numerical properties", 136th AES
%   Convention, Preprint No. 9084, Berlin, April 2014.
%
%   http://www.mit.bme.hu/~bank/delparf
%
%   C. Balazs Bank, 2014.

NFIR=length(FIR); % FIR length, not order!
if NFIR==1, % if the FIR coeff is zero then there is no FIR part
    if FIR==0,
        NFIR=0;
    end;
end;

if NFIR>0, %there is a FIR part
    imp=zeros(1,NFIR);
    imp(1)=1;
    FIRd=parfilt(Bm,Am,FIR,imp); % the new FIR part is the first FIRN samples
    Bmd=zeros(size(Bm));
    Amd=zeros(size(Am));
    SECNUM=size(Am,2);
    
    for s=1:SECNUM,
        if Am(3,s)==0, % so this is a first order filter
            [r,p,c]=residuez(Bm(1,s),Am(1:2,s));
            r=r.*p.^NFIR;
            [Btmp,Atmp]=residuez(r,p,[]);
            Bmd(1,s)=Btmp.';
            Amd(1:2,s)=Atmp.';
        else % a second-order filter
            [r,p,c]=residuez(Bm(:,s),Am(:,s));
            r=r.*p.^NFIR;            
            [Btmp,Atmp]=residuez(r,p,[]);
            Bmd(:,s)=Btmp.';
            Amd(:,s)=Atmp.';
        end;
    end;
    
else % no FIR part
    Bmd=Bm;
    Amd=Am;
    FIRd=FIR;
end;


    

