function MeanDetect(varargin)
%MeanDetect GUI which comes as part of Auto_Detect.
%User runs seixure detection algorithm based on a sliding window mean applied. 


global mean_channel reference_channel KA_injection_time sample_rate
global t1 t2 mean_channel_time mean_channel_abs Filter_Lower_Bound 
global Filter_Upper_Bound



%initialising saving variables
mean_channel = []; KA_injection_time = []; t1 = []; t2 = [];
sample_rate = []; mean_channel_time =[];


inputVar = varargin{1};

mean_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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

WindowSize_Default = 1;
WindowOverlap_Default = 0.5;
Seizure_Duration_Default = 10;
InterSeizure_duration_Default = 5;
Standard_Deviation_Threshold_Default = 1;
Filter_lower_limit_Default = 49;
Filter_Upper_limit_Default = 51;


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

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

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

%Generating panels 
MeanInputPanel = uipanel('Parent',MeanFigure,'Units','normalized',...
    'Position',[0.001 0.61 0.20 0.38],'Title', 'Parameters', 'FontWeight', 'bold');
MeanAllPlotsPanel =uipanel('Parent',MeanFigure,'Units','normalized',...
    'Position',[0.205 0.01 0.79 0.97],'Title', 'Mean Detect Results', 'FontWeight', 'bold');


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

%Create axis to display LFP 
MeanChannelAxes = axes('Parent',MeanAllPlotsPanel,'Units','normalized',...
    'OuterPosition',[0 0.6 0.93 0.4]);
%creating plot manipulation toggle buttons
MeanChannelUnDock = uicontrol('Parent',MeanAllPlotsPanel,'Units',...
    'normalized','Callback',{@UnDock,MeanChannelAxes},'CData',...
    undock.cdata,'Position',[0.93 0.69375 0.03 0.05],'TooltipString',...
    'Click to Undock Plot into a new Figure');

%Create axis to display seizure detection graph
MeanDetectAxes = axes('Parent',MeanAllPlotsPanel,'Units','normalized',...
    'OuterPosition',[0 0.4 0.932 0.2]);
%creating plot manipulation toggle buttons
MeanDetectUnDock = uicontrol('Parent',MeanAllPlotsPanel,'Units',...
    'normalized','Callback',{@UnDock,MeanDetectAxes},'CData',...
    undock.cdata,'Position',[0.93 0.39375 0.02 0.03],'TooltipString',...
    'Click to Undock Plot into a new Figure');

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

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


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


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


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

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


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

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

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

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

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

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

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

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

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

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

% Setting Standard Deviation Threshold text field
MeanStandardDevThreshTextEdit = uicontrol('Parent',MeanInputPanel,'Units',...
    'normalized','Position',[0.715 0.24 0.21 0.05],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Sets the threshold above the basal mean LFP amplitude');

% Manual segmentation 'Run' button
MeanRunDetectButton = uicontrol('Parent',MeanInputPanel,'Units',...
    'normalized','Position',[0.2 0.01 0.6 0.09],'Callback',@MeanRunDetectButtonCallback,'Enable','on',...
    'String','Run','TooltipString','Runs algorithm with the set parameters');

% Export data to excel button
ExcelExportButton = uicontrol('Parent',MeanFigure,'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');
% 
% % Export figure to powerpoint button
% PowerpointExportButton = uicontrol('Parent',MeanFigure,'Units',...
%     'normalized','Position',[0.04 0.08 0.13 0.034],'Callback',@PowerpointExport,'Enable','on',...
%     'String','Export to Powerpoint','FontWeight','bold','TooltipString','Exports Seizure information to excel');


% Locating all objects on the Main Window
allObjects = findall(MeanFigure);



%Plot segment chosen from previous window
MeanChannelPlot();

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


% Make the Mean Detect window visible now that initialisation has been completed
set(MeanFigure,'Visible','on');





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(mean_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
        mean_channel=filter(b,a,mean_channel);
        
        end


    function MeanChannelPlot
        
       

        %Sets and dispays default parameters in Paramter panel
        set(MeanFilterLowerBoundTextEdit,'String',...
            Filter_lower_limit_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(MeanFilterUpperBoundTextEdit,'String',...
            Filter_Upper_limit_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(MeanSlidingWindowTextEdit,'String',WindowSize_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(MeanWindowOverlapTextEdit,'String',WindowOverlap_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(MeanMinSeizDurationTextEdit,'String',Seizure_Duration_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(MeanMinInterSeizTextEdit,'String',InterSeizure_duration_Default,...
            'ButtondownFcn',@ButtonDown,'Enable','on');
        set(MeanStandardDevThreshTextEdit,'String',...
            Standard_Deviation_Threshold_Default,'ButtondownFcn',...
            @ButtonDown,...
            'Enable','on');

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

        % Plots the raw LFP signal chosen from the main window
        plot(MeanChannelAxes,mean_channel_time,mean_channel);
        grid(MeanChannelAxes);
        xlabel(MeanChannelAxes,'Time (s)');
        ylabel(MeanChannelAxes,'LFP amplitude(mV)');
        title(MeanChannelAxes,['Selected Epoch for ',reference_channel,' (',num2str(t1,...
            '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
        xlim(MeanChannelAxes,[min(mean_channel_time) max(mean_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 = mean_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(MeanChannelAxes,mean_channel_time,...
                mean_channel,KA_plot_time,KA_plot_sig);
            grid(MeanChannelAxes);
            xlabel(MeanChannelAxes,'Time (s)');
            ylabel(MeanChannelAxes,'LFP amplitude (mV)');
            title(MeanChannelAxes,[' ',...
                reference_channel,' Epoch (',num2str(t1,...
                '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
            legend(MeanChannelAxes,'Post-KA administration',...
                'Pre-KA administration', 'Location', 'North');
            xlim(MeanChannelAxes,...
                [min(mean_channel_time) max(mean_channel_time)]);
            
        elseif  t2 <= KA_injection_time == 1 ;
            
            
            %plots the basal portion in green
            plot(MeanChannelAxes,mean_channel,...
                mean_channel_time,'color',[0 0.5 0]);
            grid(MeanChannelAxes);
            xlabel(MeanChannelAxes,'Time (s)');
            ylabel(MeanChannelAxes,'LFP amplitude (mV)');
            title(MeanChannelAxes,['Segment of ',...
                reference_channel,' (',num2str(t1,...
                '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
            legend(MeanChannelAxes,'Pre-KA administration',...
                'Location', 'North','Left');
            xlim(MeanChannelAxes,...
                [min(mean_channel_time) max(mean_channel_time)]);
            
            
            
        end
        
        
    end

    


    function MeanRunDetectButtonCallback(hObject,eventdata,handles)
        
       
        
        % Handles corresponding to all text fields in the parameters panel
        TextEditFieldsHandles = {MeanStandardDevThreshTextEdit...
            ,MeanMinSeizDurationTextEdit,MeanMinInterSeizTextEdit,...
            MeanWindowOverlapTextEdit,MeanSlidingWindowTextEdit,...
            MeanFilterUpperBoundTextEdit,MeanFilterLowerBoundTextEdit};

        %Gets values of the text fields of parameters panel and assigns
        %values to variables
        Filter_Lower_Bound = str2double(get(MeanFilterLowerBoundTextEdit,...
            'String'));
        Filter_Upper_Bound = str2double(get(MeanFilterUpperBoundTextEdit,...
            'String'));
        Sliding_Window_Size = str2double(get(MeanSlidingWindowTextEdit,...
            'String'));
        Window_Overlap = str2double(get(MeanWindowOverlapTextEdit,...
            'String'));
        MinInter_Seiz = str2double(get(MeanMinInterSeizTextEdit,...
            'String'));
        MinSeiz_Duration = str2double(get(MeanMinSeizDurationTextEdit,...
            'String'));
        Standard_Dev_Thresh = str2double(get(MeanStandardDevThreshTextEdit,...
            'String'));


        

        ParamterValues = {Filter_Lower_Bound,Filter_Upper_Bound,...
            Sliding_Window_Size,Window_Overlap,MinInter_Seiz,...
            MinSeiz_Duration,Standard_Dev_Thresh};
        
        
        %applies notch filter to channel and changes the mean_channel global variable
        %value which is the signal
        ChannelNotchFilter(Filter_Lower_Bound,Filter_Upper_Bound);
        
       
      %run algorithm
        
     
     %Now calculate number of pre KA injection datapoints are in mean_channel

      [min_dist,pre_KA_datapoints] =min(abs(mean_channel_time-KA_injection_time));
     
  
  
        mean_channel_abs=abs(mean_channel);


        %% new algorithm

        % this one is very slow with 'rand' data, and crashes with actual lfp data.
        % The only solution is to either vectorise, or use parpool function with
        % multiple processors.
        window_size=Sliding_Window_Size*sample_rate;
        lag = Window_Overlap*sample_rate;
        num_segs=length(mean_channel_abs)/lag;

        a=1;
        for n = 1:lag:((lag*num_segs)-window_size);
        window_average(a)=(sum(mean_channel_abs(n:(n+window_size))))/window_size;
        time1(a)=mean_channel_time(n);
        a=a+1;
        end
        
        window_average=window_average';

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


        threshold = mean + (Standard_Dev_Thresh*deviation);

        %plots red threshold line
        %  threshold_lines = zeros(length(window_average),1);
        % 
        % for a= 1:length(window_average)
        %     threshold_lines(a) = threshold;
        % end

        % figure 
        % plot(time1,window_average);
        % title('Plot of Mean Values of Windowed Data');
        % ylabel('Mean Value of Each Window');
        % xlabel ('Time(s)');
        % hold on
        % plot(time1,threshold_lines,'r');

%% This is the method of extracting seizures given by SeizureDetectv8_c.m

%
        data.seiz=zeros(length(mean_channel),1);

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

        %corresponding indices of data.seiz(mean_channel) where window starts
        x =(trigger*lag)-(lag-1);
        for k=1:length(x)
            % sets the condition so that the length of data.seiz isnt altered by this condition
            if (x(k) + window_size) < length(data.seiz)
         % sets the data points in data.seiz to 1, corresponding to those contained between each window above threshold from 'trigger'.       
         data.seiz(x(k):(x(k)+ window_size)) = 1;
            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

disp(length(data.seiz))

disp(length(mean_channel_time))

 
 %% false interictals removed
  
      %finds starts and end points of seizure
      on_off = find(abs(diff(data.seiz)) > 0);

      %gives length in samples of seizure then interictal
      data_dist = diff(on_off);
      
      data.seiz(1:3)=0;%  this ensures that the ordering of the algorithms selection of seizure start and end points holds true for data starting with a seizure.

      %this ensures that even if seizure continues beyond dataset, the algorithm can detect and measure its duration within data selected. 
      data.seiz(end)=0;
   
      % if isempty(find(data_dist(2:2:end)<MinInter_Seiz*sample_rate,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_rate*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(mean_channel_time,Data_Seizure);
    


% %% Output of final seizure data to user
% 
%  data.seiz_real(:,i) = data.seiz(1:length(mean_channel_time));% this one works better with multiple channel analysis to store each final output.
%  
%     data.seiz_n(i) = length(find((diff(data.seiz))>0));% stores the final number of detected seizures present in 'data.seiz' 
%     %(note that 'abs' isnt used as a prequel, therefore this will only select start points of seizures.
%     
%     data.seiz_total_dur(i) = sum(data.seiz)/sample_rate; % this works as elements of data.seiz are either 1 or 0, so dividing total sum of array by sample_rate gives total seizure time
%     
% 
%  if data.seiz_n > 1
%         seiz_start = find(abs(diff(data.seiz))>0); %outputs indices of each seizure start and end point
%         for seiz = 1:data.seiz_n(i)% cycles through each seizure
%             data.seiz_dur(seiz) = (seiz_start(seiz*2)-seiz_start(seiz*2-1))/sample_rate;
%         end
%     else
%         seiz_start = find(abs(diff(data.seiz))>0);
%     end
%     
%     
%     disp(' ')
%     disp(['Variable ' nth_trace(i,:) ', overall Seizure Duration = ' num2str(data.seiz_total_dur(i),'%.4f') 's'])
%     disp(['Variable ' nth_trace(i,:) ', number of Seizure Events = ' num2str(data.seiz_n(i))])
%     if isempty(seiz_start) == 1
%         disp(' '); disp('*** NO SEIZURES DETECTED WITH CURRENT THRESHOLD SETTING ***')
%     else
%         
%         k=1;
%         for l=1:2:length(seiz_start)
%             
%         disp(['Variable ' nth_trace(i,:) ', start time of seizure number ' num2str(k) ' = ' num2str((mean_channel_time(seiz_start(l))),'%.4f') 's'])
%         disp(['Variable ' nth_trace(i,:) ', duration of seizure number ' num2str(k) ' = ' num2str(data.seiz_dur(k),'%.4f') 's'])
% %         format short g;
% %         if data.seiz_n == 1
% %             data.seiz_total_dur
% %             
% %         else
% %             data.seiz_dur
% %       
% %         end
% start_time(k)=(mean_channel_time(seiz_start(l)));
% start_time=start_time';
% duration(k)=data.seiz_dur(k);
% duration=duration';
%         k=k+1;
%         end
%         disp(['NB Calculations utilise only seizures > ' num2str(MinSeiz_Duration) 's in duration; seizures occurring less than ' num2str(MinInter_Seiz) 's apart are considered as one seizure'])
%         format short g
%     end
   

        %plots spectrogram 
        SpectroPlot();


        
        
    end

    function SpectroPlot
 
       
        F=linspace(1,sample_rate/4,sample_rate/2);

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

    function SeizureEventDisplay(mean_channel_time,Data_Seizure)
        

        %seizure detect Display
        plot(MeanDetectAxes,mean_channel_time,Data_Seizure,'r','LineWidth',1.6);
        title(MeanDetectAxes,'Seizure Events & Durations', 'FontWeight','bold');
        xlabel(MeanDetectAxes,'Time (s)');
        grid(MeanDetectAxes);
        ylabel(MeanDetectAxes,'1 = Seizure Event');
        ylim (MeanDetectAxes,[ -0.2 1.2]);
        xlim(MeanDetectAxes,[min(mean_channel_time) max(mean_channel_time)]);
    
    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
% 
%     function PowerpointExport(hObject,eventdata)
%         exports figure to powerpoint. 
%         file courtesy of Dmitriy Aronov, MATLAB Central.
%         Locating all objects on the Main Window
%        allObjects = findall(MeanFigure);
%        
%         pptfigure(MeanFigure);
%  
%     end

end


