function [a,b,c,d] = ss(h,sec)
%SS  Convert dfilt object to state space.
%   [A,B,C,D] = SS(H,N) returns the state space matrices A,
%   B, C and D corresponding to the N-th section of dfilt
%   object H.
%
%   [A,B,C,D] = SS(H) returns the overall state space matrices A,
%   B, C and D corresponding to the dfilt object H.

%   Author(s): R. Losada
%   Copyright 1988-2000 The MathWorks, Inc.
%   $Revision: 1.5 $  $Date: 2000/06/13 21:21:25 $ 

error(nargchk(1,2,nargin));
error(nargoutchk(0,4,nargout));

if nargin == 2,
    h = section(h,sec);
end


% Determine overall state space model
[a,b,c,d] = determiness(h);

%--------------------------------------------------------------
function [a,b,c,d] = determiness(h)
%DETERMINESS Determine overall state-space model.

switch connection(h),
case 'cas',
    % Initialize state-space model
    a=[]; b=[]; c=[]; d=1;
    
    % Get warning state
    warnstate = warning;
    
    % Get last warning
    lastwarning = lastwarn;
    
    % Set warning off temporarily
    warning off;
        
    % Form the state-space model of the cascade recursively
    for n = 1:nsections(h),
        
        % Generate a temporary state-space model per section
        f = section(h,n);
        [at,bt,ct,dt] = sec2ss(f);
        
        % Combine section with overall state-space model
        [a,b,c,d] = cascaded_ss(a,b,c,d,at,bt,ct,dt);
    end
    
    % Return warning to previous state
    warning(warnstate);
    
    % Return lastwarning to what it was
    lastwarn(lastwarning);
    
case 'par',
    % Initialize state-space model
    a=[]; b=[]; c=[]; d=0;
    
    % Form the state-space model of the parallel filter recursively
    for n = 1:nsections(h),
        
        % Generate a temporary state-space model per section
        f = section(h,n);
        [at,bt,ct,dt] = sec2ss(f);
        
        % Combine section with overall state-space model
        [a,b,c,d] = parallel_ss(a,b,c,d,at,bt,ct,dt);
    end   
end

%-----------------------------------------------------------------------------------
function [a,b,c,d] = cascaded_ss(a1,b1,c1,d1,a2,b2,c2,d2)
%CASCADED_SS  Form a state-space representation of two cascaded state-space systems.

a = [a1, zeros(size(a1,1),size(a2,2));b2*c1, a2];

b = [b1;b2*d1];

c = [d2*c1, c2];

d = d2*d1;
%-----------------------------------------------------------------------------------
function [a,b,c,d] = parallel_ss(a1,b1,c1,d1,a2,b2,c2,d2)
%PARALLEL_SS  Form a state-space representation of two state-space systems in parallel.

a = [a1, zeros(size(a1,1),size(a2,2));zeros(size(a2,1),size(a1,2)), a2];

b = [b1;b2];

c = [c1, c2];

d = d2+d1;


