function EntropyDetect(varargin)
%EntropyDetect GUI which comes as part of Auto_Detect.
%User runs seizure detection algorithm based on the signal entropy

global Ent_channel reference_channel KA_injection_time sample_rate
global t1 t2 Ent_channel_time Filter_Lower_Bound Filter_Upper_Bound
global symbol_table RVE_time RVE



%initialising saving variables
Ent_channel = []; KA_injection_time = []; t1 = []; t2 = [];
sample_rate = []; Ent_channel_time =[]; symbol_table = [];


inputVar = varargin{1};

Ent_channel = inputVar{1}(:);
KA_injection_time = inputVar{2};
t1 = inputVar{3}(1);
t2 = inputVar{3}(2);
sample_rate = inputVar{4};
reference_channel = inputVar{5};


%%%%%%%%%%%%%%%%%%%%%%% Default Parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Filter_lower_limit_Default = 49;    
Filter_Upper_limit_Default = 51;   
SampleWindowSize_Default = 5;   
Lag_Default = 2;    
Decay_Rate_Default = 0.6;
Seizure_Duration_Default = 10; 
InterSeizure_duration_Default = 5;  
WindowSize_Default = 1;  
WindowOverlap_Default = 0.5;    
Standard_Deviation_Threshold_Default = 1.83;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%gets the screen size of user monitor
screensize=get(0,'ScreenSize');

% Generating the Ent Detect figure window
EntFigure = figure('Units','characters','MenuBar','none','Name',...
    'Entropy Detect','NumberTitle','off','Position',[10 0 230 70],'ReSize',...
    'on','Visible','on');

%Generating panels 
EntInputPanel = uipanel('Parent',EntFigure,'Units','normalized',...
    'Position',[0.001 0.55 0.20 0.44],'Title', 'Parameters', 'FontWeight', 'bold');
EntAllPlotsPanel =uipanel('Parent',EntFigure,'Units','normalized',...
    'Position',[0.205 0.01 0.79 0.97],'Title', 'Entropy Detect Results', 'FontWeight', 'bold');


% Loading icons for the plot manipulation buttons
undock = load('undock.mat');


%Create axis to display LFP 
EntChannelAxes = axes('Parent',EntAllPlotsPanel,'Units','normalized',...
    'OuterPosition',[0 0.75 0.93 0.25]);
%creating plot manipulation toggle buttons
EntChannelUnDock = uicontrol('Parent',EntAllPlotsPanel,'Units',...
    'normalized','Callback',{@UnDock,EntChannelAxes},'CData',...
    undock.cdata,'Position',[0.93 0.79375 0.03 0.05],'TooltipString',...
    'Click to Undock Plot into a new Figure');

%Create axis to display seizure detection graph
EntDetectAxes = axes('Parent',EntAllPlotsPanel,'Units','normalized',...
    'OuterPosition',[0 0.6 0.93 0.15]);
%creating plot manipulation toggle buttons
EntDetectUnDock = uicontrol('Parent',EntAllPlotsPanel,'Units',...
    'normalized','Callback',{@UnDock,EntDetectAxes},'CData',...
    undock.cdata,'Position',[0.93 0.60375 0.02 0.03],'TooltipString',...
    'Click to Undock Plot into a new Figure');

EntEntropyAxis = axes('Parent',EntAllPlotsPanel,'Units','normalized',...
    'OuterPosition',[0 0.35 0.93 0.25]);
%creating plot manipulation toggle buttons
EntEntropyUnDock = uicontrol('Parent',EntAllPlotsPanel,'Units',...
    'normalized','Callback',{@UnDock,EntEntropyAxis},'CData',...
    undock.cdata,'Position',[0.93 0.3575 0.03 0.05],'TooltipString',...
    'Click to Undock Plot into a new Figure');

%create axis to display spectrogram
EntSpectrogramAxes = axes('Parent',EntAllPlotsPanel,'Units','normalized',...
    'OuterPosition',[0 0 1 0.35]);
%creating plot manipulation toggle buttons
EntSpectrogramUnDock = uicontrol('Parent',EntAllPlotsPanel,'Units',...
    'normalized','Callback',{@UnDock,EntSpectrogramAxes},'CData',...
    undock.cdata,'Position',[0.95 0.0375 0.03 0.05],'TooltipString',...
    'Click to Undock Plot into a new Figure');

%another axis?

% Locating all plot manipulation buttons
allToggleBtns = findall(gcf,'Style','togglebutton');


%setting string for input titles
EntInputText = {'Sample Rate:','','KA Injection Time:','', 'Filter:',...
    '','Sample Window Size:','','Sample Lag:','',...
    'Decay rate:','','Min Inter-Seizure Period:','',...
    'Min Seizure Duration:','','Sliding Window Size:','','Window Overlap:',...
    '','Standard Deviations Above Basal Mean:'};


%setting user input title text
EntInputTitleText = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.05 0.04 0.75 0.92],'String',EntInputText,'Style',...
    'text');


% Setting the information section values - {''} gets filled in later func
EntInputVarText = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','HorizontalAlignment','right',...
    'Position',[0.65 0.78 0.3 0.18],'String',{''},'Style',...
    'text');

% Setting butterworth Filter  lower bound text field
 EntFilterLowerBoundTextEdit = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.455 0.77 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Sets upper limit of Butterworth filter');


% Setting butterworth Filter upper bound text field
 EntFilterUpperBoundTextEdit= uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.715 0.77 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Set lower limit of Butterworth filter');

% Setting Filter  text field units
 EntFilterUnitsText = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','HorizontalAlignment','Left','Position',[0.923 0.76 0.07 0.05],'String','Hz',...
    'Style','text');

% Setting Sample window size
EntSampleWindowSizeTextEdit = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.715 0.70 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Sets the size of the sample window, see Guide');

% Setting lag text field
EntSampleLagTextEdit = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.715 0.62 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Enter the lag between samples included in the sample window, see Guide');

% Setting decay rate text field
EntDecayRateTextEdit = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.715 0.545 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Enter the decay rate of the symbol count frequency');

%  Setting decay rate units
 EntDecayRateUnitsText = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','HorizontalAlignment','Left','Position',[0.923 0.53 0.07 0.05],'String','s',...
    'Style','text');

% Setting minimum InterSeizure period text field
EntMinInterSeizTextEdit = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.715 0.475 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Enter the minimum duration of time between seizure events');

%  Setting minimum Inter Seizure text field units
 EntMinInterSeizUnitsText = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','HorizontalAlignment','Left','Position',[0.923 0.465 0.07 0.05],'String','s',...
    'Style','text');

% Setting minimum SeizDuration text field
EntMinSeizDurationTextEdit = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.715 0.40 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Enter the minimum seizure duration');

%  Setting minimum SeizDuration text field units
 EntMinSeizDurationUnitsText = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','HorizontalAlignment','Left','Position',[0.923 0.385 0.07 0.05],'String','s',...
    'Style','text');

% Setting Sliding Window text field
EntSlidingWindowTextEdit = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.715 0.33 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Enter the size of the sliding window');

%  Setting Sliding Window text field units
EntSlidingWindowUnitsText = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','HorizontalAlignment','Left','Position',[0.923 0.315 0.07 0.05],'String','s',...
    'Style','text');

% Setting text field
EntWindowOverlapTextEdit = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.715 0.25 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Enter the overlap of the sliding window');

%  Setting WindowOverlap text field units
EntWindowOverlapUnitsText = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','HorizontalAlignment','Left','Position',[0.923 0.24 0.07 0.05],'String','s',...
    'Style','text');

% Setting Standard Deviation Threshold text field
EntStandardDevThreshTextEdit = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.715 0.135 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Enter the threshold below basal mean entropy. ');

% Entropy Detect Run button
EntRunDetectButton = uicontrol('Parent',EntInputPanel,'Units',...
    'normalized','Position',[0.2 0.01 0.6 0.09],'Callback',...
    @EntRunDetectButtonCallback,'Enable','on',...
    'String','Run','TooltipString','Runs algorithm with the set parameters');


% Export data to excel button
EntExportButton = uicontrol('Parent',EntFigure,'Units',...
    'normalized','Position',[0.04 0.04 0.13 0.034],'Callback',@ExcelExport,'Enable','on',...
    'String','Export Data to Excel','FontWeight','bold','TooltipString',...
    'Exports Seizure information to excel');


%Displays KA and sample rate
set(EntInputVarText,'String',{[num2str(sample_rate),' Hz'],'',...
    [num2str(KA_injection_time),'  s']});

%Plot segment chosen from previous window
EntChannelPlot();


function  ButtonDown(hObject,eventdata)
        
        % Clear the curent string in the parent text field if there is a
        % button down function
        set(hObject,'Enable','on','String',[])
        uicontrol(hObject);
        
end

 function UnDock(hObject,eventdata,axes_handles)
        
        % Locating all plot manipulation buttons except for the currently
        % selected one
        otherToggleBtns = allToggleBtns;
        otherToggleBtns(allToggleBtns==hObject) = [];

        % Set the properties for all other toggle buttons
        for jj = 1:length(otherToggleBtns)
            
            % Toggle off all other plot manipulation buttons
            set(otherToggleBtns(jj),'Value',0)
            
        end
        
        % Create a new figure window on which to export the parent plot
        SeparatePlot = figure('ReSize','on');
        
        % Copy all the objects from the parent plot axes to this new figure
        % window
        copyobj(axes_handles,SeparatePlot);
        
        % Resize the plot axes to fill the new figure window
        set(gca,'OuterPosition',[0 0 1 1])
        
    end


function ChannelNotchFilter(Filter_Lower_Bound,Filter_Upper_Bound)
            %finds length of segment chosen in Main Window
        L=length(Ent_channel); 
        
               
        % Next power of 2 from length of y
        NFFT = 2^nextpow2(L); 
        freq = sample_rate/2*linspace(0,1,NFFT/2+1);
        nyquist=(sample_rate/2)+1;
             
        w1=Filter_Lower_Bound/nyquist;
        w2=Filter_Upper_Bound/nyquist;

        %Butterworth filter - stops frequencies between bounds w1 and w2
        %defined by the user.Filters mains frequency noise by default between 48 and 52Hz
        %mains frequency noise = 50Hz
        [b,a]=butter(5,[w1,w2],'stop');
        
        %applying Buttorworth filter and redefining global variable
        Ent_channel=filter(b,a,Ent_channel);
        
        end


function EntChannelPlot
        
       

        %Set and dispay default parameters in Paramter panel
        set(EntFilterLowerBoundTextEdit,'String',Filter_lower_limit_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(EntFilterUpperBoundTextEdit,'String',Filter_Upper_limit_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(EntSampleWindowSizeTextEdit,'String',SampleWindowSize_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(EntSampleLagTextEdit,'String',Lag_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(EntDecayRateTextEdit,'String',Decay_Rate_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
         set(EntMinSeizDurationTextEdit,'String',Seizure_Duration_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(EntMinInterSeizTextEdit,'String',InterSeizure_duration_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
         set(EntSlidingWindowTextEdit,'String',WindowSize_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(EntWindowOverlapTextEdit,'String',WindowOverlap_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
         set(EntStandardDevThreshTextEdit,'String',...
            Standard_Deviation_Threshold_Default,'ButtondownFcn',...
            @ButtonDown,...
            'Enable','on');




        
        % Determines the time scale of segment chosen in main window
        Ent_channel_time = t1:1/sample_rate:t2;

        % Plots the segment signal to the top plot axes
        plot(EntChannelAxes,Ent_channel_time,Ent_channel);
        grid(EntChannelAxes);
        xlabel(EntChannelAxes,'Time (s)');
        ylabel(EntChannelAxes,'LFP amplitude(mV)');
        title(EntChannelAxes,['Selected Epoch for ',reference_channel,' (',num2str(t1,...
            '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
        xlim(EntChannelAxes,[min(Ent_channel_time) max(Ent_channel_time)]);


         %highlights basal period in green if segment chosen in Main_Prog_Window
         %includes it
        if t1 < KA_injection_time == 1 && t2 > KA_injection_time == 1 ;
           
            
            ka_sig_length = KA_injection_time - t1;
            KA_plot_sig = Ent_channel(1:ka_sig_length*sample_rate+1);
            KA_plot_time = t1:1/sample_rate:KA_injection_time;
            
            %plots the chosen segment with the basal period displayed in a
            %different colour
            plot(EntChannelAxes,Ent_channel_time,...
                Ent_channel,KA_plot_time,KA_plot_sig);
            grid(EntChannelAxes);
            xlabel(EntChannelAxes,'Time (s)');
            ylabel(EntChannelAxes,'LFP amplitude (mV)');
            title(EntChannelAxes,[' ',...
                reference_channel,' Epoch (',num2str(t1,...
                '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
            legend(EntChannelAxes,'Post-KA administration',...
                'Pre-KA administration', 'Location', 'NorthEast');
            xlim(EntChannelAxes,...
                [min(Ent_channel_time) max(Ent_channel_time)]);
            
        elseif  t2 <= KA_injection_time == 1 ;
            
            
            %plots the basal segment in green
            plot(EntChannelAxes,Ent_channel,...
                Ent_channel_time,'color',[0 0.5 0]);
            grid(EntChannelAxes);
            xlabel(EntChannelAxes,'Time (s)');
            ylabel(EntChannelAxes,'LFP amplitude (mV)');
            title(EntChannelAxes,['Segment of ',...
                reference_channel,' (',num2str(t1,...
                '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
            legend(EntChannelAxes,'Pre-KA administration',...
                'Location', 'NorthEast');
            xlim(EntChannelAxes,...
                [min(Ent_channel_time) max(Ent_channel_time)]);
            
            
            
        end
        
        
    end

    function EntRunDetectButtonCallback(hObject,eventdata,handles)
        
        %Gets values of the text fields of parameters panel and assigns
        %values to variables
        Filter_Lower_Bound = str2double(get(EntFilterLowerBoundTextEdit,...
            'String'));
        Filter_Upper_Bound = str2double(get(EntFilterUpperBoundTextEdit,...
            'String'));
        W = str2double(get(EntSampleWindowSizeTextEdit,...
            'String'));
        lag = str2double(get(EntSampleLagTextEdit,...
            'String'));
        Decay = str2double(get(EntDecayRateTextEdit,...
            'String'));
        Sliding_Window_Size = str2double(get(EntSlidingWindowTextEdit,...
            'String'));
        Window_Overlap = str2double(get(EntWindowOverlapTextEdit,...
            'String'));
        MinInter_Seiz = str2double(get(EntMinInterSeizTextEdit,...
            'String'));
        MinSeiz_Duration = str2double(get(EntMinSeizDurationTextEdit,...
            'String'));
        Standard_Dev_Thresh =str2double(get(EntStandardDevThreshTextEdit,...
            'String'));
        
        %makes the threshold negative
        if Standard_Dev_Thresh >= 0;
            
            Standard_Dev_Thresh = - Standard_Dev_Thresh;
        end
        
    
        %applies notch filter to channel and changes the mean_channel global variable
        %value which is the signal
        ChannelNotchFilter(Filter_Lower_Bound,Filter_Upper_Bound);
        
        %sample spacing between the end of one window and the beginning of the
        %nexg
        spacing = 5;
        
        %Table of symbols is related to the size of the window i.e. value of W. 
        symbol_table = perms(1:W);
        
       %leaky integrater constant alpha 
       alpha = exp(-1./(Decay.*sample_rate));
        
       %setting all Fcount values = 1 
       Fcount(1:length(symbol_table)) = 1;
        
       
       window_size= (lag*W)-1;
       
       %takes into account the spacing value along the data set
       num_segs= round(length(Ent_channel)/spacing);
       
%        disp(num_segs)
%        disp('This number times 1/sample_rate tells us how much time is lost')
       
       %pre-defining the Rank Vector Entropy vector. Increasing the spacing
       %between windows reduces the number of entropy estimates returned in
       %the algorithm - the entorpy becomes less synched in time
       RVE = zeros((num_segs-window_size),1);
       
       %creates new time vector for RVE estimates
       RVE_time = zeros((num_segs-window_size),1);

       a=1;
       
         h = waitbar2a(0,'COMPUTING - Please wait...', 'BarColor', 'g');

         pause(0.3)

         waitbar2a(0.1,h)

         pause(0.1)
         waitbar2a(0.3,h)
         pause(0.1)
         waitbar2a(0.4,h)
 

        tic% sliding window through the data (but stops before the end)
        for n = 1:spacing:((spacing*num_segs)-window_size);
            w = Ent_channel(n:lag:(n+window_size))'; %misses off windows at the end 
            %windows(n,:) = w;    
            %[sortedValues(n,:), sortedIndexes(n,:)] = sort(windows(n,:), 'descend');
            [sorted_window_elements, sorted_element_indexes] = sort(w, 'descend');
            [~, symbol] = ismember(sorted_element_indexes, symbol_table, 'rows');

            Fcount = alpha.*Fcount; % Equation3, where Fk = alpha*(F(k-1))
            Fcount(symbol)= Fcount(symbol) + 1; 
            Probability = Fcount./(sum(Fcount));

            RVE(a) = (1/log(factorial(W)))*sum(-Probability.*log(Probability));
            RVE_time(a)=Ent_channel_time(n);
            a=a+1;
            
            
        end
         toc
         
        waitbar2a(0.7,h)
         
          
          
% loop_var = (length(Ent_channel)-((lag*W)-1)); %so the sliding window doesn't exceed the signal
% Fcount(1:length(symbol_table)) = 1; %setting all Fcount values = 1
% Decay = 0.6;
% 
% RVE = zeros(length(Ent_channel),1);
% 
% tic
% % sliding window through the data (but stops before the end)
% for n = 1:loop_var;
%     w = Ent_channel(n:lag:(n+(lag*W)-1))'; %misses off windows at the end 
%     %windows(n,:) = w;    
%     %[sortedValues(n,:), sortedIndexes(n,:)] = sort(windows(n,:), 'descend');
%     [sorted_window_elements, sorted_element_indexes] = sort(w, 'descend');
%     sorted_element_indexes = sorted_element_indexes;
%     [~, symbol] = ismember(sorted_element_indexes, symbol_table, 'rows');
%     
%     Fcount = alpha.*Fcount; % Equation3, where Fk = alpha*(F(k-1))
%     Fcount(symbol)= Fcount(symbol) + 1; 
%     Probability = Fcount./(sum(Fcount));
%     
% %     calculates entropy
%     RVE(n) = (1/log(factorial(W)))*sum(-Probability.*log(Probability));
%     
% end
% 
% toc
% 
% RVE = RVE(1:end-12);
% 
% 
% RVE_time = linspace(0,size(RVE,1)/sample_rate,size(RVE,1)); 


%         assignin('base',['RVE_',reference_channel],RVE);
%         assignin('base', 'rveTime',RVE_time);

            %plots entropy
            EntropyPlot(RVE_time,RVE);
            
            
        [min_dist, pre_KA_datapoints]=min(abs(RVE_time-KA_injection_time));%the value of I saved from this line is the nth datapoint of the 'time' vector 


        mean = sum(RVE(1:pre_KA_datapoints)/pre_KA_datapoints);
        %deviation=std(RVE(1:pre_KA_datapoints));

        threshold = mean;
        threshold_lines = zeros(length(RVE),1);




        % for a= 1:length(RVE)
        %     threshold_lines(a)=threshold;
        % end
        % 
        % plot(RVE_time,threshold_lines,'r');





        % This is the method of extracting seizures given by SeizureDetectv8_c.m
         data.seiz = zeros(length(Ent_channel),1);

          %finds indices of when window_average is above the set threshold
        trigger = find((RVE(1:end)) < threshold);

        tic
        x = (trigger*spacing)-(spacing-1);

        %corresponding indices of data.seiz(data.lfp) where window starts
        for k=1:length(x)
            if (x(k)+window_size)<length(data.seiz)% sets the condition so that the length of data.seiz isnt altered by this condition
         data.seiz(x(k):(x(k)+ window_size))=1;% sets the data points in data.seiz to 1, corresponding to those contained between each window above threshold from 'trigger'.
            else
                end_diff=(x(k)+window_size)-length(data.seiz);%obtains number of data points from 'triggered' above threshold window start point in data.seiz to end of data.seiz
                data.seiz(x(k):(x(k)+ end_diff))=1;%sets these values to 1 also without altering the length of data.seiz.
            end
        end
         toc


        % false interictals removed

      on_off=find(abs(diff(data.seiz))>0);
      data_dist=diff(on_off);

       % set entire post KA injection data points to 1 for subsequent
       % insertion of seizure details.
       %n start = find(data.lfp(pre_KA_datapoints+1:end),1) +   pre_KA_datapoints; % extracts the first non-zero index of the array data.seiz from which KA was administered.  
       %n finish = find(data.lfp( pre_KA_datapoints+1:end), 1, 'last') +   pre_KA_datapoints;

       %n data.seiz(start:finish) = 1;

       data.seiz(end)=0;%this ensures that even if seizue continues beyond dataset, the algorithm can detect and measure its duration within data selected.
   
       
       
        % if isempty(find(data_dist(2:2:end)<MinInter_Seiz*sample_freq,1)) == 0 % i.e. do this if it's not empty (if inequality is met)
           
        % extracts indices of array data_dist of interictal events above user defined min duration.
         interictal=find(data_dist(2:2:end)<MinInter_Seiz*sample_rate);
        
     
                %This next lines extract the start point of each interictal
                %interval that exceeds the time threshold individually using the
                %command 'interictal(int_num)' acting upon 'on_off'' which
                %contains the start/end locations of each event. The
                %algebra '*2' ensures selection of the start of the 'off'
                %location of seizures in the 'on_off' array, which is the
                %start of the interictal period. All of these array indices
                %are subseqently selected from the data.seiz array and set
                %back to 0 from 1, giving an array of 1's and zero's for
                %selected seizure events. 
        for int_num = 1:length(interictal) 
             data.seiz(on_off(interictal(int_num)*2):(on_off(interictal(int_num)*2+1))) = 1; 
        end
       %else
    %        disp('Equality in line 122 not met; interictal period below selected threshold duration not found within data set');
       %end

       
        % NOW REMOVE ALL FALSE SEIZURES FROM DATA.SEIZ ARRAY

        %This extracts indices of where in the data the threshold is crossed,indicating either the start or end of a seizure.
          on_off_1=find(abs(diff(data.seiz))>0);
          data_dist_1=diff(on_off_1);

      
     
       %if isempty(find(data_dist_1(1:2:end)>sample_freq*MinSeiz_Duration,1)) == 0 % i.e. do this if it's not empty (if inequality is met)    
      
        seizure=find(data_dist_1(1:2:end)<sample_rate*MinSeiz_Duration);% extracts indices of array data_dist of seizure events BELOW user defined min duration.
        
        %The next two lines extract the start point of each seizure event
        %that is less than the user defined minimum MinSeiz_Duration
        %individually using the command 'seizure(sez_num)' acting upon 'on_off_1' which
        %contains the start/end locations of each event. The
        %algebra '*2-1' ensures selection of the start of the 'on'
        %location of seizures in the 'on_off_1' array, which is the
        %start of each seizure period. All of these array indices
        %are subseqently selected from the data.seiz array and set
        %back to 0 from 1, giving an array of 1's and zero's for
        %remaining thresholded seizure events.
        for sez_num = 1:length(seizure) 
          data.seiz(on_off_1(seizure(sez_num)*2-1):(on_off_1(seizure(sez_num)*2))) = 0; 
        end
      % else
%            disp('Equality in line 154 not met, no seizures above selected duration found within data set');
     % end

        Data_Seizure = data.seiz;

        SeizureEventDisplay(Ent_channel_time,Data_Seizure);

        waitbar2a(0.9,h);

        %plots spectrogram 
        SpectroPlot();

        close(h);
    end

    function SeizureEventDisplay(Ent_channel_time,Data_Seizure)
        
    plot(EntDetectAxes,Ent_channel_time,Data_Seizure,'r','LineWidth',1.6);
    title(EntDetectAxes,'Seizure Events & Durations');
    xlabel(EntDetectAxes,'Time (s)');
    grid(EntDetectAxes);
    ylabel(EntDetectAxes,'1 = seizure event');
    ylim (EntDetectAxes,[ -0.2 1.2]);
    xlim(EntDetectAxes, [min(Ent_channel_time) max(Ent_channel_time)]);
        
    end

    function EntropyPlot(RVE_time,RVE)
        
        %plots Entropy values on separate plot
        plot(EntEntropyAxis,RVE_time,RVE);
        xlabel(EntEntropyAxis,'Time (s)');
        ylabel(EntEntropyAxis,'Entropy')
        title(EntEntropyAxis,['Entropy Change of ',...
                reference_channel,' Epoch (',num2str(t1,...
                '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
        xlim(EntEntropyAxis,[min(RVE_time) max(RVE_time)]);
        
        
    end

    function SpectroPlot
        

        F=linspace(1,sample_rate/4,100);               
        

        [~,F,T,P] = spectrogram(Ent_channel,sample_rate,0,F,sample_rate);
        surf(EntSpectrogramAxes,T,F,10*log10(P),'edgecolor','none'); axis tight;
        view(EntSpectrogramAxes,0,90);
        xlabel(EntSpectrogramAxes,'Time (s)'); ylabel('Frequency (Hz)');
        shading interp
        axes(EntSpectrogramAxes);
        chandle= colorbar('YTickLabel', [0:10]);
        ylabel(chandle, 'Relative Frequency Intensity');
        title(EntSpectrogramAxes,['Spectrogram of Epoch ',...
                        reference_channel,' (',num2str(t1,...
                        '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
        
    end


 function ExcelExport(hObject,eventdata)

        start={'Seizure Start Time'};
        xlswrite('seizure_events.xls',start,'seizure_events','B1')
        xlswrite('seizure_events.xls',start_time,'seizure_events','B2')

        dur={'Seizure Duration'};
        xlswrite('seizure_events.xls',dur,'seizure_events','C1')
        xlswrite('seizure_events.xls',duration,'seizure_events','C2')

 end

end