% Code to plot simulation results from sdl_engine_braking
%% Plot Description:
%
% This plot shows the torque supplied by the engine varies with the applied
% throttle and with the number of cylinders that are used for engine
% braking.

% Copyright 2016 The MathWorks, Inc.

% Generate simulation results if they don't exist
if ~exist('simlog_sdl_engine_braking', 'var')
    sim('sdl_engine_braking')
end

% Reuse figure if it exists, else create new figure
if ~exist('h2_sdl_engine_braking', 'var') || ...
        ~isgraphics(h2_sdl_engine_braking, 'figure')
    h2_sdl_engine_braking = figure('Name', 'sdl_engine_braking');
end
figure(h2_sdl_engine_braking)
clf(h2_sdl_engine_braking)

% Get simulation results
simlog_t = simlog_sdl_engine_braking.Inertia.I.w.series.time;
simlog_engineThr = simlog_sdl_engine_braking.Engine_with_Brake.Engine.T.series.values;
simlog_engineNBrCyl = simlog_sdl_engine_braking.Engine_with_Brake.Braking_Torque.Num_Cyl_Round.O.series.values;
simlog_combustionTrq = simlog_sdl_engine_braking.Engine_with_Brake.Engine.trq.series.values('N*m');
simlog_brakingTrq = simlog_sdl_engine_braking.Engine_with_Brake.Braking_Torque.Total_Braking_Torque.O.series.values('N*m');
simlog_outputTrq = simlog_sdl_engine_braking.Inertia.t.series.values('N*m');

% Plot results
simlog_handles(1) = subplot(2, 1, 1);
plot(simlog_t, simlog_outputTrq, 'LineWidth', 2)
hold on
plot(simlog_t, simlog_combustionTrq, 'LineWidth', 1)
plot(simlog_t, simlog_brakingTrq, 'LineWidth', 1)
grid on
title('Torque')
ylabel('Torque (N*m)')
legend({'Output','Combustion','Braking'},'Location','Best');

simlog_handles(2) = subplot(2, 1, 2);
yyaxis left
plot(simlog_t, simlog_engineThr, 'LineWidth', 1)
ylabel('Throttle (0-1)')
set(gca,'YLim',[-0.2 1.2]);
yyaxis right
plot(simlog_t, simlog_engineNBrCyl, 'LineWidth', 1)
ylabel('# Braking Cyl (0-8)')
set(gca,'YLim',[-0.2 8.2]);
%plot(simlog_t, simlog_shaftt, 'LineWidth', 1)
grid on
title('Throttle and Brake')
xlabel('Time (s)')

linkaxes(simlog_handles, 'x')

% Remove temporary variables
clear simlog_t simlog_handles
clear simlog_brakingTrq simlog_combustionTrq  simlog_outputTrq           
clear simlog_engineNBrCyl simlog_engineThr
