close all; clear all;
%% Final Static Fire Sequence

% Time vector
dt = 0.0001;              % or 0.01, etc.
t  = -8:dt:14;           % colon, not linspace


%% Define sequence for each valve
% [ start_time, target_value, ramp_duration ]

N2_events = [
    -3   100   0
];


Fuel_events = [
    1   33.33   0.5
    2   100   0.5
    3.5       0   0.5
];

LOX_events = [
    1.3    33.33   0.2
    2   100  0.5
    3.5       0   0.3
];

Pyro_events = [
     0   100   0.01
     1.8     0   0.01
];

%% Generate profiles (initial value = 0)
N2   = valve_profile(t, N2_events,   0);
Fuel = valve_profile(t, Fuel_events, 0);
LOX  = valve_profile(t, LOX_events,  0);
Pyro = valve_profile(t, Pyro_events, 0);

%% Plot
% Existing
figure; hold on; grid on; box on;
plot(t, N2,   '--', 'LineWidth', 1,  'Color', [0 0 1 0.5]);
plot(t, Fuel, '-',  'LineWidth', 1.5);
plot(t, LOX,  '-',  'LineWidth', 1.5);
%plot(t, Pyro, '--', 'LineWidth', 1);
plot([0,0],[0,100],'-', 'LineWidth', 2,'Color', [1 0 0 0.5]); %Ignition


ax = gca;
ax.XTick = -4:1:10;
ax.XMinorTick = 'on';
ax.XAxis.MinorTickValues = -4:0.1:10;
ax.XMinorGrid = 'on';
ax.MinorGridAlpha = 0.15;                % transparency
ax.MinorGridLineStyle = '-';            % solid but faint
ax.MinorGridColor = [0.8 0.8 0.8];

xlabel('Time [s]');
ylabel('Opening[%]');
legend('Nitrogen','Ethanol','LOX','Ignition','Location','best');
ylim([-5 105]);
xlim([-4 10]);
title('First Ignition Sequence (1 second)');





%% Helper function
function u = valve_profile(t, events, initial_value)
    % events: [t_start, target_value, ramp_duration]
    % assumes events are sorted by t_start

    u = initial_value * ones(size(t));
    prev_value = initial_value;

    for k = 1:size(events,1)
        t0     = events(k,1);
        target = events(k,2);
        dur    = events(k,3);

        if dur <= 0
            % Instant step
            u(t >= t0) = target;
        else
            % Linear ramp from prev_value to target
            t1        = t0 + dur;
            idx_ramp  = (t >= t0) & (t <= t1);
            u(idx_ramp) = prev_value + ...
                (target - prev_value) .* (t(idx_ramp) - t0) / dur;

            % Hold new value after ramp
            u(t > t1) = target;
        end

        prev_value = target;
    end
end
