function alarm=Complete_script(StartTime,WakeUpTime,SizeWakeUpInterval)
alarm = false;
%% user input
StartWakeUpInterval=WakeUpTime-SizeWakeUpInterval;      %start of wakeup interval

%% options
filename = 'Night23-3-2016.txt';
tstep = 4*60*1e6;     % [us] time per frame
windowsize = 5;    % [-]  no. of frames for averaging5

%% settings
fmin   = 13/60;     % [Hz] minimal expected breathing frequency
fmax   = 27/60;     % [Hz] maximal expected breathing frequency
ndrop = 2;          % number of frames in a row for waking up

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

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

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

%% fix samples
if deb; disp('Removing bad samples.'); end
ts = 2e3;
index = true(size(tijd));
for i = 2:length(tijd)
    if tijd(i)-tijd(i-1) > 4*ts || tijd(i)-tijd(i-1) < -2^16 || (tijd(i)-tijd(i-1) < 0.5*ts && tijd(i)-tijd(i-1) > -6e4)
        index(i) = false;
        j = 1;
        while tijd(i+j)-tijd(i-1) > 4*ts || (tijd(i+j)-tijd(i-1) < 0.5*ts && tijd(i+j)-tijd(i-1) > -6e4)
            index(i+j) = false;
            j = j + 1;
        end 
    end
end
tijd = tijd(index, :);
%audio = audio(index, :);
envelope = envelope(index, :);

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

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

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

%if deb; disp('TO DO:    Removing bad samples.'); end

%% %% ademhaling.m
if deb; disp('Calculating sleepphase.'); end

%% preparations

% calculate frames (count & time)
nframes = floor(tijd(end)/tstep);
tb = (0:nframes) * tstep;

% storage vars
fr  = zeros(1,nframes);
avg = zeros(1,nframes);

%% loop
for i=1:nframes
    clear x t

    % cut previous frame from data
    
    envelope = envelope(tijd>tb(i));
    tijd = tijd(tijd>tb(i));
    
    % create frame
    x = envelope(tijd<tb(i+1));
    t = tijd(tijd<tb(i+1));
    
    % this is where the magic happens
    X = fft(x);

    % calculate frequency variables
    T0=(t(end)-t(1))/1e6;
    f0=1/T0;
    N=max(size(t));
    
    fs=N/T0;
    Ts=1/fs;
    f=-fs/2:f0:fs/2-f0;

    X2=Ts*[X(floor(N/2)+1:N); X(1:floor(N/2))];

    % filter frequencies
    X3 = X2(f < fmax);
    f2 = f(f < fmax);
    X3 = X3(f2 > fmin);
    f3 = f2(f2 > fmin);
    
    % assume the highest peak is actual breathing frequency
    fr(i) = f3(X3==max(X3));
    
    % calculate shifting average
    if i < windowsize
        avg(i) = mean(fr(1:i));
    else
        avg(i) = mean(fr(i+1-windowsize:i));
    end
    
end

%{
T0 = (tijd(end)-tijd(1))/1e6;
if T0 < 600
    tc = 1e6;
    label = 'tijd [s]';
elseif T0 < 3 * 3600
    tc = 60*1e6;
    label = 'tijd [min]';
else
    tc = 3600*1e6;
    label = 'tijd [h]';
end

tframe = (1:tijd(end)/tstep)*tstep/tc;
clf();
plot(tframe, fr*60, 'LineWidth',0.5);hold on
plot(tframe, avg*60,'LineWidth',2);hold off
xlabel(label)
ylabel('ademhalingsfrequentie [/min]')
%}

%% calculation of wake-up time
if deb; disp('Determining wake-up moment.'); end

%% initialisation
A=ones(nframes);    %will be used if function is out of working
B=ones(nframes);    %will be used if function is out of working


%% determining moment of waking up with the aid of the slope of the line
slope=[0 diff(avg)];                                        %A=1 if the slope is negative
A=slope<0;                                                  %A=0 if the slope is positive                                                

%% determining the moment of waking up with the aid of the position relative to the mean
factorDeviation=0.1;    
variation=max(avg)-min(avg);                                %factor of the total variation above the mean
value=avg-(mean(avg)+factorDeviation*variation);            %B=1 if the line is under the mean+variationfactor
B=value<0;                                            %B=0 if the line isn't under the mean+variationfactor

                                                        

for i=ndrop:nframes
    ii = 1+i-ndrop;
    
    %check whether the number of frames in a row complies with the requirement(s)
    C(i)=prod(A(ii:i))*prod(B(ii:i));                                  %if B(i)=1, the ndrop frames before i all complies with the requirements 
    
    %determining the relative wake up time
    AbsoluteWakeUpTime=StartTime + i*(tstep/1e6)*C(i);

    
    %check if there is a perfect moment to wake someone up within the wake-up interval
    if AbsoluteWakeUpTime>StartWakeUpInterval
        alarm=true;
        return
    end
end

if deb; disp('Done.'); end
