%% Quasi-Resonant Buck 
% State plane solution to Qsw buck with minimum negative current necessary
% for soft switching (J4=0) (assumed M <= 1/2)
%% Circuit definition
Vg = 48;
V = 5;

C = 10e-6; %Not used due to small ripple assumption
L = 1e-6;
Csw = 10e-9;

%% Choose/guess an I1 to define operating point
I1 = 5;


%% State Plane Analysis
% Normalization
Ro = sqrt(L/Csw);
wo = 1/sqrt(L*Csw);
Vbase = Vg;
Ibase = Vg/Ro;

M = V/Vbase;

% Interval 4
J3 = sqrt(1-2*M); %At ZVS Boundary
I3 = -J3*Ibase;
delta = pi-atan(J3/M);
r4 = (1-M);

% Interval 1
% theta1 is set to get I1 as specified
t1 = I1*L/(Vg-V);
theta1 = t1*wo;
J1 = theta1*(1-M);

% Interval 2
r2 = sqrt(J1^2+(1-M)^2);
J2 = sqrt(r2^2-(M)^2);
beta = pi-atan(J1/(1-M))-atan(J2/M);

% Interval 3
theta3 = (J2+J3)/M;

% Averaging
F = 2*pi/(theta1+theta3+delta+beta);
Jout = F/2/pi*(theta1/2*J1+theta3/2*(J2-J3));

%% Denormalize
tbeta = beta/wo;
tdelta = delta/wo;
t1 = theta1/wo;
t3 = theta3/wo;
I1 = J1*Ibase;
I2 = J2*Ibase;
I3 = J3*Ibase;
Iout = Jout*Ibase;
fs = F*wo/2/pi;
Ts = 1/fs;

%% Reconstruct current and voltage plots
t = linspace(0,1/fs,10000);
il = zeros(1,length(t));
vsw = zeros(1,length(t));

% Interval 1
il(t<=t1) = t(t<=t1)*(Vg-V)/L;
vsw(t<=t1) = Vg;

%interval 2
bind = find(t>=t1 & t<t1+tbeta); %indexes for beta subinterval
il(bind) = -r2*Ibase*sin(wo*(t(bind)-t1) + atan(J1/(1-M)) + pi);
vsw(bind) = -r2*Vbase*cos(wo*(t(bind)-t1) + atan(J1/(1-M)) + pi) + M*Vbase;

%interval 3
t3ind = find(t>t1+tbeta & t<=t1+tbeta+t3); %indexes for subinterval 3
il(t3ind) = I2-V/L*(t(t3ind)-t1-tbeta);
vsw(t3ind) = 0;

% Interval 4
dind = find(t>t1+tbeta+t3); %indexes for delta subinterval
il(dind) = -r4*Ibase*sin(wo*(t(dind)-t1-tbeta-t3) + atan(J3/M));
vsw(dind) = -r4*Vbase*cos(wo*(t(dind)-t1-tbeta-t3) + atan(J3/M)) + M*Vbase;

figure(1);
subplot(2,3,1:2);
plot(t/Ts,il,'Linewidth',3)
hold on;
plot([0 1], [0 0],'-k')
plot([0 1], [Iout Iout],':r')
Th = text(3/4,Iout,['I_{out}']);
set(Th, 'Color', [1 0 0], 'VerticalAlignment','bottom');
ylabel('i_l [A]');
set(gca,'XTickLabel', [])
hold off;

subplot(2,3,4:5);
plot(t/Ts,vsw,'Linewidth',3)
ylabel('v_{sw} [V]');
xlabel('t/T_s [p.u.]');
text(1/2,10,['f_s = ' num2str(fs/1000) ' kHz']);
text(1/2,7,['P_{out} = ' num2str(Iout*V) ' W']);

subplot(2,3,[3 6]);
plot(vsw/Vbase, il/Ibase,'Linewidth',3)
ylabel('j_L');
xlabel('m_p');









