%We want to test whether the different configurations can always return a
%number or not.

clear all


global h
h=actxserver('UnisimDesign.Application');

clc
load x0
load ua
load disturbances


% %Temperatures specified in Unisim model:
% lb = [4240 ; 500 ; 101/3600 ; -100; -100 ; -100 ; -158.15 ; -158.15 ; 40/3600 ; 0/3600 ;  6/3600] ;
% ub = [4440 ; 537 ; 103/3600 ;  -85;  -85 ;  -85 ; -156.15 ; -156.15 ; 45/3600 ; 4/3600 ; 10/3600] ;
% scale_x = diag(2.^(fix(log2(ub - lb)))) ;
% 
% lb = scale_x\lb ;
% ub = scale_x\ub ;
% parameters.scale_x = scale_x ;
% 
% failures_temp = 0 ;
% 
% ind = [1:3 9:11] ;
% 
% for j = ind
%     disp(['Perturbing ' num2str(j) 'th element of x0'])
%     x0 = x0_temp ; x0 = scale_x\x0 ;
%     xpert = linspace(lb(j),ub(j),50) ;
%     for i = 1:length(xpert)
%         disp(['i = ' num2str(i)])
%         x0(j) = xpert(i) ;
%         J = MCHE_obj_temp(x0,d,parameters) ;
% %         work(i) = J ;
%         if J == 1e5
%             failures_temp = failures_temp + 1 ;
%         end
%     end
% end
% disp([num2str(failures_temp) ' calculations failed.'])
% Reset_MCHE_temp(x0_temp,d,h) ;


%UA is specified within Unisim, and recycles solved by
%Unisim as well.

x0 = x0_area ;
lb = [4240 ; 500 ; 101/3600 ; 40/3600 ; 0/3600 ;  6/3600 ; -158.15 ; -100 ] ;
ub = [4440 ; 537 ; 103/3600 ; 45/3600 ; 4/3600 ; 10/3600 ; -156.15 ;  -80 ] ;

scale_x = diag(2.^(fix(log2(ub - lb)))) ;

x0 = scale_x\x0 ;
lb = scale_x\lb ;
ub = scale_x\ub ;

parameters.scale_x = scale_x ;

%Now define whether recycles should be handled by Unisim or by matlab:

parameters.recycles = 'unisim' ;

parameters.scale_ceq = 1 ;
x0 = x0(1:6);
scale_x = scale_x(1:6,1:6) ;
parameters.scale_x = scale_x ;
lb = lb(1:6);
ub = ub(1:6);

failures_area1 = 0 ;

for j=1:6
    disp(['Perturbing ' num2str(j) 'th element of x0'])
    x0_new = x0 ;
    xpert = linspace(lb(j),ub(j),25) ;
    for i = 1:length(xpert)
        disp(['i = ' num2str(i)])
        x0_new(j) = xpert(i) ;
        [J message] = MCHE_obj_area(x0_new,d,parameters) ;
%         work(i) = J ;
        if J == 1e5
            failures_area1 = failures_area1 + 1 ;
            disp(message)
        end
    end
end
% Reset_MCHE_area(x0_area,d,h) ;

% parameters.recycles = 'matlab' ;
% failures_area2 = 0 ;
% 
% for j=1:6
%     disp(['Perturbing ' num2str(j) 'th element of x0'])
%     x0_new = x0 ;
%     xpert = linspace(lb(j),ub(j),50) ;
%     for i = 1:length(xpert)
%         disp(['i = ' num2str(i)])
%         x0_new(j) = xpert(i) ;
%         J = MCHE_obj_area(x0_new,d,parameters) ;
% %         work(i) = J ;
%         if J == 1e5
%             failures_area2 = failures_area2 + 1 ;
%             disp('Convergence failure')
%         end
%     end
% end
Reset_MCHE_area(x0_area,d,h) ;