clf; format compact; clf(figure(1))

%% options5
% filename = 'Datalog.txt';
filename = 'Night18-3-2016.txt';

%% settings
path  = 'C:/Users/S137552/Documents/Arduino/test/';
delim = ' ';
in2 = true; %audio and envelope input
sst = true; %sample speed test
hdr = true; %header above data
deb = true; %show debug messages
skip = 0; %skip the first and last x samples

if deb; disp('Fourier.m started.'); end

%% import data
if deb; disp('Loading file.'); end
x = importdata([path filename],delim, 1*hdr);
tijd = x.data(1+skip:end-skip,1);
audio = x.data(1+skip:end-skip,2);
if in2
    envelope = x.data(1+skip:end-skip,3);
end

%% us time correction
if deb; disp('Correcting time.'); end

N=max(size(tijd));
%us overflow correction
T1 = [find(diff(tijd)<0); 0];

forcep=16;
if exist('forcep','var')
    p1 = 2^forcep;
else
    p1 = 2^(nextpow2(max(tijd)-1));
end

j = 1;
for i = 1:N
    tijd(i) = tijd(i) + (j-1)*p1;
    if T1(j)<i+1 && j < length(T1)            
        j = j+1;
    end
end



if deb; disp('Starting fft & plotting.'); end
T0=tijd(end)/1e6;
f0=1/T0;

fs=length(tijd)/T0;
disp(['Sampling Frequency: ' num2str(fs) ' [Hz]'])
Ts=1/fs;
f=-fs/2:f0:fs/2-f0;

if N/fs < 600
    tc = 1e6;
    label = 'tijd [s]';
elseif N/fs < 3 * 3600
    tc = 60*1e6;
    label = 'tijd [min]';
else
    tc = 3600*1e6;
    label = 'tijd [h]';
end

%input 1
Xa=fft(audio);
X2a=Ts*[Xa(floor(N/2)+1:N); Xa(1:floor(N/2))];

subplot(2,1+in2,1)
plot(tijd/tc,audio*5/1024)
xlabel(label)
ylabel('audio [V]')

subplot(2,1+in2,2+in2)
plot(f,abs(X2a))
axis([0.01 fs/2 0 60])
xlabel('frequentie [Hz]')
ylabel('amplitude')


% input 2
if in2
    Xe=fft(envelope);
    X2e=Ts*[Xe(floor(N/2)+1:N); Xe(1:floor(N/2))];

    subplot(2,2,2)
    plot(tijd/tc,envelope*5/1024)
    xlabel('tijd [s]')
    ylabel('envelope [byte]')

    subplot(2,2,4)
    plot(f,abs(X2e))
    axis([0.01 10 0 60])
    xlabel('frequentie [Hz]')
    ylabel('amplitude')
end

if deb; disp('Sample speed test.'); end
% sample speed test
if sst
    clf(figure(2))
    plot(tijd(1:end-1)/tc,diff(tijd))
    xlabel(label)
    ylabel('sample time [{\mu}s]')
end
figure(1)
if deb; disp('Done.'); end