clc; clear; close all;

% read simplis simulation results from csv file
data = csvread("simplis_d50.csv", 1, 0);
time_simplis = data(:,1);
ind_simplis = data(:,2);
vout_simplis = data(:,3);


Vin = 5;
D = 0.5;
L = 1e-6;
C = 1e-6;
R = 1;
Tsw = 1e-6;
Dp = 1 - D;

N = 100;
dt =Tsw/N;

V = D*Vin;
Iave = V/R;
Sr = (Vin-V)/L;
Sf = -V/L;

Imin = Iave - Sr*0.5*D*Tsw;
Imax = Iave + Sr*0.5*D*Tsw;

% V0 = 2.423;
V0 = V*(1-(Dp^2-D*Dp)*Tsw^2/24/L/C);
V2 = V0;
Vo_min = V0 - V*D*Dp*Tsw^2/8/L/C;
Vo_max = V0 + V*Dp^2*Tsw^2/8/L/C;

k=1;
for i=0:dt:D*Tsw
    t(k) = i*1e6;
    I(k) = Imin + Sr*i;
    Vo(k) = V0 - V*Dp*Tsw/2/L/C*i + Sr*i^2/2/C;
    k = k+1;
end

for i=D*Tsw:dt:Tsw
    t(k) = i*1e6;
    I(k) = Imax + Sf*(i-D*Tsw);
    Vo(k) = V2 + V*Dp*Tsw/2/L/C*(i-D*Tsw)+Sf/2/C*(i-D*Tsw)^2;
    k = k+1;
end

for i=Tsw:dt:Tsw+D*Tsw
    t(k) = i*1e6;
    I(k) = Imin + Sr*(i-Tsw);
    Vo(k) = V0 - V*Dp*Tsw/2/L/C*(i-Tsw) + Sr*(i-Tsw)^2/2/C;
    k = k+1;
end

for i=Tsw+D*Tsw:dt:2*Tsw
    t(k) = i*1e6;
    I(k) = Imax + Sf*(i-Tsw-D*Tsw);
    Vo(k) = V2 + V*Dp*Tsw/2/L/C*(i-Tsw-D*Tsw)+Sf/2/C*(i-Tsw-D*Tsw)^2;
    k = k+1;
end

yyaxis('left');
plot(t,I, "LineWidth",2,'Color', '#0284C7');
hold on;
% plot([0,2*Tsw*1e6],[Iave,Iave], '--', "LineWidth",1);
% text(0.05e-6, Iave+0.06, '$I_{ave}$ ', 'Interpreter','latex', 'Color', '#0284C7', 'FontSize',16);
% plot([D*Tsw*1e6,D*Tsw*1e6],[Imin-0.05,Imax+0.05], '-.', "LineWidth",1);
% plot([Tsw*1e6+D*Tsw*1e6,Tsw*1e6+D*Tsw*1e6],[Imin-0.05,Imax+0.05], '-.', "LineWidth",1);
% text(0.52e-6, 2.1, '$DT_{S}$ ', 'Interpreter','latex', 'Color', '#0284C7', 'FontSize',16);
% plot([0.5*D*Tsw*1e6,0.5*D*Tsw*1e6],[Imin-0.05,Imax+0.05], ':', "LineWidth",1);
% plot([Tsw*1e6+0.5*D*Tsw*1e6,Tsw*1e6+0.5*D*Tsw*1e6],[Imin-0.05,Imax+0.05], ':', "LineWidth",1);
% text(0.26e-6, 2.1, '$\frac{DT_S}{2}$ ', 'Interpreter','latex', 'Color', '#0284C7', 'FontSize',20);
% plot([D*Tsw*1e6+0.5*Dp*Tsw*1e6,D*Tsw*1e6+0.5*Dp*Tsw*1e6],[Imin-0.05,Imax+0.05], ':', "LineWidth",1);
% plot([Tsw*1e6+D*Tsw*1e6+0.5*Dp*Tsw*1e6,Tsw*1e6+D*Tsw*1e6+0.5*Dp*Tsw*1e6],[Imin-0.05,Imax+0.05], ':', "LineWidth",1);
plot(time_simplis.*1e6, ind_simplis, "LineWidth",2, 'Color', "#EA580C");
grid on;
ylim([Imin-0.05, Imax+0.05]);
ylabel("Inductor current [A]");

yyaxis('right');
plot(t,Vo, "LineWidth",2);
hold on;
plot(time_simplis.*1e6, vout_simplis, "LineWidth",2, 'Color', "#9333EA");
grid on;
ylim([Vo_min-0.03, Vo_max+0.01]);
ylabel("Output voltage [V]");

xlabel('Time [µs]')
legend("inductor current - math", 'inductor current - simplis', 'Vout - math', 'Vout - simplis', "Location","southeast");




