function dummy = closedloop(LoopData)
%CLOSEDLOOP  Gets the closed-loop model.

%   Author(s): P. Gahinet
%   Copyright 1986-2000 The MathWorks
%   $Revision: 1.4 $  $Date: 2000/06/14 20:18:25 $

% Closed-loop model from [r,dy,du,n] to [y,u]

% REVISIT
dummy = [];

% Get components
G = LoopData.Plant.Model;
F = LoopData.PreFilter.Model;
H = LoopData.Sensor.Model;
C = zpk(LoopData.Compensator);

% Take feedback sign into account
e = LoopData.FeedbackSign;

try
    if isproper(G) & isproper(H) & isproper(F) & isproper(C)
        % All models are proper: use state-space approach
        M = append(ss(G),ss(C),ss(H),ss(F));
        % Build interconnection matrix
        switch LoopData.Configuration
        case 1
            % C is in forward path
            ICmat = [0 1 0 0 0 0 1 0;0 0 e 1 0 0 0 e;1 0 0 0 0 1 0 0;0 0 0 0 1 0 0 0];
        case 2
            % C is in feedback path
            ICmat = [0 e 0 1 0 0 1 0;0 0 1 0 0 0 0 1;1 0 0 0 0 1 0 0;0 0 0 0 1 0 0 0];
        end
        ICmat = [ICmat ; ICmat([3 1],:)];
        % Derive closed-loop model
        LoopData.ClosedLoop = lft(M,ICmat);
        
    else
        % Some models are improper: use ZPK format
        G = zpk(G);   H = zpk(H);   F = zpk(F);
        % Build closed-loop map
        switch LoopData.Configuration
        case 1
            % C is in forward path
            H = (-e)*H;
            [S,GS,CS,CGS,CHS] = LocalGetTransfers(G,C,H,F);
            LoopData.ClosedLoop = [F*CGS S GS e*CGS;F*CS -CHS S e*CS];
        case 2
            % C is in feedback path
            C = (-e)*C;
            [S,GS,CS,CGS,CHS] = LocalGetTransfers(G,C,H,F);
            LoopData.ClosedLoop = [F*GS S GS -CGS;F*S -CHS S -CS];
        end
    end
catch
    % Current gain value causes an algebraic loop
    LoopData.ClosedLoop = repmat(NaN,[2 4]);
end


%-------------------------Internal Functions-------------------------

%%%%%%%%%%%%%%%%%%%%%%%%%
%%% LocalGetTransfers %%%
%%%%%%%%%%%%%%%%%%%%%%%%%
function [S,GS,CS,CGS,CHS] = LocalGetTransfers(G,C,H,F)

S = feedback(1,C*G*H);
CGS = feedback(G*C,H);
CHS = feedback(H*C,G);
GS = feedback(G,C*H);
CS = feedback(C,G*H);
