format longEng;

t_stop = 1e-6;

%sim('ring_osc_comp_diff_pulse_fft',t_stop)

t_start = 0.94e-6;
n_start = cast((t_start/t_stop) * t_stop/ts, 'int32');

signal = vout_last2(n_start:end);
if vout_last2(n_start) < 0
    last2_cross = cast(find(signal>0), 'int32');
    last2_edge = 1;
else
    last2_cross = cast(find(signal<0), 'int32');
    last2_edge = -1;
end
t_last2_cross = ts*double(n_start) + linzerocross(last2_cross(1), signal, ts);

signal = vout_last(n_start:end);
if last2_edge < 0
    last_cross = cast(find(signal>0), 'int32');
    last_edge = 1;
else
    last_cross = cast(find(signal<0), 'int32');
    last_edge = -1;
end
t_last_cross = ts*double(n_start) + linzerocross(last_cross(1), signal, ts);

t_del_last = t_last_cross - t_last2_cross;

signal = vout_first(n_start:end);
if last_edge > 0
    first_cross = cast(find(signal>0), 'int32');
    first_edge = 1;
else
    first_cross = cast(find(signal<0), 'int32');
    first_edge = -1;
end
t_first_cross = ts*double(n_start) + linzerocross(first_cross(1), signal, ts);

t_del_first = t_first_cross - t_last_cross;

d = t_del_first - t_del_last;

signal = iout_inj(n_start:end);
inj_cross_start = cast(find(signal==0), 'int32');
inj_pos_cross = cast(find(signal(inj_cross_start(1):end)>0), 'int32');
inj_neg_cross = cast(find(signal(inj_cross_start(1):end)<0), 'int32');
t_inj_pos_cross = ts*double(n_start) + double(inj_pos_cross(1))*ts + double(inj_cross_start(1))*ts -3*ts;
t_inj_neg_cross = ts*double(n_start) + double(inj_neg_cross(1))*ts + double(inj_cross_start(1))*ts -3*ts;

if inj_pos_cross(1) < inj_neg_cross(1)
    inj_edge = 1;
else
    inj_edge = -1;
end

delta = t_inj_pos_cross - t_last_cross;
if first_edge == -1
    delta = delta - 0.5/ f_inj;
end

if delta > 0.5/f_inj
    delta = delta - 1/f_inj;
end

if delta < -0.5/f_inj
    delta = delta + 1/f_inj;
end

inj_angle = delta * f_inj * 360;
if abs(inj_angle) > 180
    inj_angle = inj_angle-360;
end

delta
d
inj_angle