/***************************************************************/
/* Simulation des signaux générés par l'EHX Octave Multiplexer */
/***************************************************************/
// Randagodron 2018-01-06

clc;
clear;

sample_rate = 1000000;
f_max = 20000;

t = 0:(1/sample_rate):0.2;
N = size(t,'*')-1;
in = (sin(2*%pi*1000*t));


//derive = (in(2:(size(in, 1))) - in(1:N));
derive = diff(in)./diff(t) / (2*%pi*1000);

// Init zero crossing detection
zc_output = zeros(N,1);
zc_output_2 = zeros(N,1);
zc=0;
inc=0;
output = zeros(N,1);
threshold = 0.4;

//Zero crossing detection
for i = 1:N
    if (inc == 0) then
        if (derive(i) > threshold) then
            zc_output(i) = 1;
            inc = 1;
        else
            zc_output(i) = 0;
        end
    else
        if (derive(i) < -threshold) then
            zc_output(i) = 0;
            inc = 0;
        else
            zc_output(i) = 1;
        end
    end
    
    if (i>1) then
        if ((zc_output(i-1) == 0) && (zc_output(i) == 1)) then
            if (zc == 1)
                zc = 0;
            else
                zc = 1;
            end
        end
    end
    
    if (zc == 1) then
        zc_output_2(i) = 1;
        output (i) = in(i) + 1;
    else
        output (i) = -in(i) - 1;
    end
end

in_fft = (fft(in));
output_fft = fft(output);

f = sample_rate * (0 : (N/2)) / N;
n = size(f,'*');

clf()
//plot(t(1:N)',[in(1:N)', derive', zc_output])

//plot(t(1:N)',[in(1:N)', zc_output])

//plot(t(1:N)',[in(1:N)', zc_output_2])

//plot(t(1:N)',[in(1:N)', output])

//plot(f(1:f_max),20*log(abs(in_fft(1:f_max)')))
//plot(f(1:f_max),20*log(abs(output_fft(1:f_max))))
plot(f(1:f_max),[20*log(abs(in_fft(1:f_max)')), 20*log(abs(output_fft(1:f_max)))])
