function[J,grad] = objfun_Comb(x,pr)

% Cost function of the combined flowsheet
% Written by Julian Straus, Trondheim 09.12.2018

% This function defines the cost function for the optimization (J) and the
% gradient of the cost function grad. It uses the scaled values. Hence, one
% has to be careful with respect to the values in pr.

% The needed input is defined as
%       x:  	Solution vector
%       pr:     Price for the cost function


% Cost Function
J = pr.feed*x(1) + pr.prod*x(540) + pr.purg*x(445) + pr.comp*(x(10)+x(43)+x(68))+...
    pr.stea*x(362) + pr.cool*(x(479)+x(505)+x(539));

if nargout > 1
    grad = sparse(numel(x),1);
    
    % Feed Stream
    grad(1) = pr.feed;
    
    % Product Stream
    grad(540) = pr.prod;
    
    % Purge Stream
    grad(445) = pr.purg;
        
    % Compressor duty
    grad(10) = pr.comp;
    grad(43) = pr.comp;
    grad(68) = pr.comp;
    
    % Steam Production
    grad(362) = pr.stea;
    
    % Compressor Cooling
    grad(479) = pr.cool;
    grad(505) = pr.cool;
    grad(539) = pr.cool;
end

%% Indices off the variables
% Makeup Section
% Cold Flow HEx1:       27
% Compressor 1 Duty:    10
% Compressor 2 Duty:    43
% Compressor 3 Duty:    68

% Reactor Section
% HEx5 Duty:            362

% Separation Section
% Cold Flow HEx6:       379
% Product stream:       540
% HEx8 Duty:            479
% HEx9 Duty:            505
% HEx10 Duty:           539
% Split flow:           445