%% Header
% Purpose:  Function calculating the integrated absolute error 
%           as a function of controller tuning.
% Author:   Axel Lodemel Holene
% E-mail:   axel.holene@gmail.com
% Date:     February 2013
% About:    

function iae0 = iae(ctrl, parm)
    G = parm.G ;
    C = controller(ctrl, parm);
    try
        S = 1/(1+G.tf*C.tf) ;   % Output feedback loop tf(do->e)
        Sd = -G.tf/(1+G.tf*C.tf);% Input feedback loop tf(di->e)
    catch
        fprintf('This is iae. Error in loop TFs.\n')
    end
    %% Output response
    if parm.simCost == 0 % Don't use Simulink
        try
            [e t] = step([S; Sd], parm.simTime) ;
            iae0 = trapz(t, abs(e))' ;
        catch
            iae0 = [100; 100] ;% Penalize bad tuning from solver
            if parm.dispErrors
                fprintf('This is costFun catch. ')
                fprintf('Error in step function: %s\n', ...
                        lasterr) ;
            end
        end
    else % Use simulink
        try
            simOut = sim('simulink/iaeBlock', ...
                 'SrcWorkspace', 'current') ;
            iae_y = get(simOut,'iae_y') ;
            iae_d = get(simOut,'iae_d') ;
        catch
            iae_y = 100 ;      % Penalize bad tuning from solver
            iae_d = 100 ;
            if parm.dispErrors
                fprintf('This is costFun catch. ')
                fprintf('Error in simulink simulation: %s\n',...
                        lasterr) ;
            end
        end
        iae0 = [iae_y(end); iae_d(end)] ;
    end
end