function CrossCorrelationDetect(varargin)
%Cross Correlation GUI which comes as part of Auto_Detect.
%User selects a template within a pre-allocated segment in Main_Prog_Window
%and this template is searched for within the segment. 


global cross_channel reference_channel KA_injection_time sample_rate
global t1 t2 cross_channel_time  template_data
global template_time template_duration  x_idx1 x_idx2 
global corr_norm2 threshold template_index


%initialising saving variables
cross_channel = []; KA_injection_time = []; t1 = []; t2 = [];
sample_rate = []; cross_channel_time =[];


inputVar = varargin{1};

cross_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 %%%%%%%%%%%%%%%%%%%%%%%%%%%
threshold = 0.6; 
Filter_lower_limit_Default = 49;
Filter_Upper_limit_Default = 51;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%




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

% Generating the cross correlation figure window
CrossCorrFigure = figure('Units','characters','MenuBar','none','Name',...
    'Cross Correlation','NumberTitle','off','Position',[10 5 237 35],'ReSize',...
    'on','Visible','off');

%Generating panels 
CrossMainPlotPanel = uipanel('Parent',CrossCorrFigure,'Units','normalized',...
    'Position',[0.001 0.15 0.7 0.81]);
CrossTemplatePlotPanel = uipanel('Parent',CrossCorrFigure,'Units','normalized',...
    'Position',[0.705 0.39 0.29 0.57]);
CrossTemplateInfoPanel = uipanel('Parent',CrossCorrFigure,'Units','normalized',...
    'Position',[0.705 0.15 0.149 0.23],'Title', ' Template Information', 'FontWeight', 'bold');
CrossThresholdSetPanel = uipanel('Parent',CrossCorrFigure,'Units','normalized',...
    'Position',[0.856 0.15 0.140 0.23],'Title', 'Correlation Threshold', 'FontWeight', 'bold');
CrossResultsPanel = uipanel('Parent',CrossCorrFigure,'Units','normalized',...
    'Position',[0.705 0.015 0.29 0.145],'Title', 'Results','FontWeight', 'bold');
CrossScrollPanel = uipanel('Parent',CrossCorrFigure,'Units','normalized',...
    'Position',[0.001 0.017 0.7 0.07]);



% Loading icons for the plot manipulation buttons
zoomplus = load([matlabroot,'/toolbox/matlab/icons/zoomplus.mat']);
zoomminus = load([matlabroot,'/toolbox/matlab/icons/zoomminus.mat']);
panbtn = load([matlabroot,'/toolbox/matlab/icons/pan.mat']);
undock = load('undock.mat');


% Creating plot axes for the chosen segment from the main window
CrossMainSegPlotAxes = axes('Parent',CrossMainPlotPanel,'Units','normalized',...
    'OuterPosition',[0 0 1 1],'ButtonDownFcn','');

% Plot manipulation buttons for the chosen segment from the main window
CrossMainSegZoomIn = uicontrol('Parent',CrossMainPlotPanel,'Units',...
    'normalized','Callback',@ZoomIn1,'Position',[0.93 0.84375 0.04 0.08],'Cdata', zoomplus.cdata,...
    'Style','togglebutton','TooltipString',...
    'Click, Drag, or Scroll along the Plot to Zoom In','Value',0);
CrossMainSeglZoomOut = uicontrol('Parent',CrossMainPlotPanel,'Units',...
    'normalized','Callback',@ZoomOut,...
    'Position',[0.93 0.76375 0.04 0.08],'Cdata', zoomminus.cdata,'Style','togglebutton',...
    'TooltipString','Click, Drag, or Scroll along the Plot to Zoom Out',...
    'Value',0);
CrossMainSegPan = uicontrol('Parent',CrossMainPlotPanel, 'Units','normalized',...
    'Callback',@PanCallback,'Position',...
    [0.93 0.67375 0.04 0.08],'Cdata', panbtn.cdata,...
    'Style','togglebutton','TooltipString',...
    'Click to Pan along the Plot','Value',0);
CrossMainFFT = uicontrol('Parent',CrossMainPlotPanel,'Units','normalized',...
    'Callback',@CrossFFTCallback,'Position',...
    [0.93 0.59375 0.04 0.08],'String', 'FT','TooltipString',...
    'Click to view frequency components of chosen segment','Value',0);
CrossSegmentCrossHair = uicontrol('Parent',CrossMainPlotPanel,'Units','normalized',...
    'Callback',@CrossHairCallback,'Position',...
    [0.93 0.10375 0.04 0.07],'String', 'X','TooltipString',...
    'Click to select template','Value',0);
CrossAxesSlider = uicontrol(CrossScrollPanel,'units', 'normalized',...       
        'Position', [0 0 1 1],...
        'Callback', {@SignalScroll,CrossMainSegPlotAxes},...
        'Min', t1,'Max',t2,'Value',t1+10,'Style', 'slider');   

% Creating plot axes for the template
TemplatetPlotAxes = axes('Parent',CrossTemplatePlotPanel,'Units','normalized',...
    'OuterPosition',[0 0 1 1]);

% Plot manipulation buttons for the template plot axes 
CrossTemplateUnDock = uicontrol('Parent',CrossTemplatePlotPanel,'Units',...
    'normalized','Callback',{@UnDock,TemplatetPlotAxes},'CData',...
    undock.cdata,'Position',...
    [0.93 0.2 0.04 0.08],'TooltipString',... 
    'Click to Undock Plot into a new Figure');



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



% Template GO button
CrossTemplateGOButton = uicontrol('Parent',CrossThresholdSetPanel,'Units',...
    'normalized','Position',[0.2 0.2 0.65 0.25],'Callback',@CrossTemplateGOButtonCallback,'Enable','on',...
    'String','GO','TooltipString','Press to search data for template matches');

% Setting the threshold title
CrossTemplateInfoTitleText = uicontrol('Parent',CrossThresholdSetPanel,'Units',...
    'normalized','Position',[0 0.6 0.4 0.15],'String','Set:','Style',...
    'text','FontWeight','bold');

% Setting template threshold text field
CrossTemplateThresholdTextEdit = uicontrol('Parent',CrossThresholdSetPanel,'Units',...
    'normalized','Position',[0.45 0.6 0.35 0.15],'String',[],...
    'Style','edit','BackgroundColor','w','TooltipString',...
    'Change to adjust cross-correlation threshold for matching');

%Creating template information text
CrossTemplateInfoText = {'Start Time:','End Time:','Template width:', 'Min Voltage:', 'Max Voltage'};

% Setting the signal information section labels
CrossTemplateInfoTitleText = uicontrol('Parent',CrossTemplateInfoPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.05 0.04 0.45 0.92],'String',CrossTemplateInfoText,'Style',...
    'text');


% Setting template information section values - {''} gets filled in later func
CrossTemplateInfoVarText = uicontrol('Parent',CrossTemplateInfoPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.55 0.04 0.4 0.92],'String',{''},'Style',...
    'text');


%Creating results information text
CrossResultsInfoText = {'Total Number of Template Matches:','Number of Matches Pre-KA:',...
    'Number of Matches Post-KA:'};

% Setting the signal information section labels
CrossResultsInfoTitleText = uicontrol('Parent',CrossResultsPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.05 0.04 0.55 0.92],'String',CrossResultsInfoText,'Style',...
    'text');

% Setting the information section values - {''} gets filled in later func
CrossResultsInfoVarText = uicontrol('Parent',CrossResultsPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.6 0.04 0.40 0.92],'String',{''},'Style',...
    'text');



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


% Make the Cross Correlation window visible now that initialisation has been completed
set(CrossCorrFigure,'Visible','on')

CrossChannelPlot();


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 ZoomIn1(hObject,eventdata,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
        
        % Check if the butotn is toggled
        if get(hObject,'Value')==1
            
            % If the button is toggled, activate the zooming function
            zoom_handle = zoom;
            
            % Set the zooming function to zoom in, and to zoom only in the
            % horizontal direction
            set(zoom_handle,'Direction','in','Enable','on','Motion',...
                'horizontal')
            
            
            
                       
        else
            
            % Turn the zooming function off if the button is toggled off
            zoom off
            
        end
 end


    function ZoomOut(hObject,eventdata,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
        
        % Check to see if the button has been toggled on
        if get(hObject,'Value')==1
            
            % Activate the zoom function if the button has been toggled on
            zoom_handle = zoom;
            
            % Set the zoom function to zoom out, and to only zoom in the
            % horizontal direction
            set(zoom_handle,'Direction','out','Enable','on','Motion',...
                'horizontal')
            
        else
            
            % Turn the zooming function off if the button is toggled off
            zoom off
            
        end
    end

   
    function PanCallback(hObject,eventdata,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
        
        % Checking if the button has been toggled on
        if get(hObject,'Value')==1
            
            % Activating the pan function if the button has been toggled on
            pan_handles = pan;
            
            % Restricting the pan motion to the horizontal axis only
            set(pan_handles,'Enable','on','Motion','horizontal')
            
        else
            
            % Turning off the pan function if the button has been toggled
            % off
            pan off
            
        end
    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 SignalScroll(hObj,event,CrossMainSegPlotAxes)
        
    % Called to scroll through signal to find desired template and/or to
    % look for template matched
    
    
    
    val =get(hObj,'Value');
    
    xlim(CrossMainSegPlotAxes,[t1 val]);
    end

function CrossChannelPlot
    
       
        %finds length of segment chosen in Main Window
        L=length(cross_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;
        
        %creating bounds for filter - filter between 48 and 52Hz
        %mains frequency noise = 50Hz
        w1=Filter_lower_limit_Default/nyquist;
        w2=Filter_Upper_limit_Default/nyquist;

        %Butterworth filter - stops frequencies between bounds w1 and w2
        [b,a]=butter(5,[w1,w2],'stop');
        
        %applying Buttorworth filter to chosen segment
        cross_channel=filter(b,a,cross_channel);

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

        % Plots the segment signal to the segment plot axes
        plot(CrossMainSegPlotAxes,cross_channel_time,cross_channel);
        grid(CrossMainSegPlotAxes);
        xlabel(CrossMainSegPlotAxes,'Time (s)');
        ylabel(CrossMainSegPlotAxes,'LFP amplitude(mV)');
        title(CrossMainSegPlotAxes,['Selected Epoch for ',reference_channel,' (',num2str(t1,...
            '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
        xlim(CrossMainSegPlotAxes,[min(cross_channel_time) max(cross_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 = cross_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(CrossMainSegPlotAxes,cross_channel_time,...
                cross_channel,KA_plot_time,KA_plot_sig);
            grid(CrossMainSegPlotAxes);
            xlabel(CrossMainSegPlotAxes,'Time (s)');
            ylabel(CrossMainSegPlotAxes,'LFP amplitude (mV)');
            title(CrossMainSegPlotAxes,[' ',...
                reference_channel,' Epoch (',num2str(t1,...
                '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
%             legend(CrossMainSegPlotAxes,'Post-KA administration',...
%                 'Pre-KA administration', 'Location', 'North');
            legend(CrossMainSegPlotAxes,'Post-KA administration',...
                'Pre-KA administration', 'Location', 'North');
            xlim(CrossMainSegPlotAxes,...
                [min(cross_channel_time) max(cross_channel_time)]);
            
        elseif  t2 <= KA_injection_time == 1 ;
            
            
            %plots the basal segment in green
            plot(CrossMainSegPlotAxes,cross_channel_time,...
                cross_channel,'color',[0 0.5 0]);
            grid(CrossMainSegPlotAxes);
            xlabel(CrossMainSegPlotAxes,'Time (s)');
            ylabel(CrossMainSegPlotAxes,'LFP amplitude (mV)');
            title(CrossMainSegPlotAxes,['Segment of ',...
                reference_channel,' (',num2str(t1,...
                '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
%             legend(CrossMainSegPlotAxes,'Pre-KA administration',...
%                 'Location', 'North');
            legend(CrossMainSegPlotAxes,'Pre-KA administration',...
                'Location', 'North','Left');
%             xlim(CrossMainSegPlotAxes,...
            xlim(CrossMainSegPlotAxes,...
                [min(cross_channel_time) max(cross_channel_time)]);
            
            
            
        end
        
%         set(CrossAxesSlider, 'Min',t1, 'Max',t2);
      
        
%         cross_seg_begin = cross_channel_time(1)+1;
%         cross_seg_end = cross_channel_time(end)-1;
        
       
%         EnableCrossSegmentation();
        
%         set(CrossSegStartTextField,'String',cross_seg_begin)
%         set(CrossSegEndTextField,'String',cross_seg_end)
        
                    
        
end



function CrossHairCallback(hObject,eventdata,handles)
    
        %Disables the axes button down function that is used later to view
        %matches returned from algorithm
        set(CrossMainSegPlotAxes,'ButtonDownFcn','');
    
        %activates cross hairs for template selection
        [x, y] = ginput(2);
        
        if x(2,1)<=x(1,1)
            
            set(CrossTemplateInfoVarText,'String',{'Click again'});
            
            %stops program
            return
        end

%         %finds corresponding time sample to mouse click
%         temp_index1 = find(x(1,1) == cross_channel_time);
%         disp(temp_index1)
%         temp_index2 = find(x(2,1) == cross_channel_time);
%         disp(temp_index2)
% 
%         x_idx1 = temp_index1;
%         disp(x_idx1)
% 
%         x_idx2 =temp_index2;
%         disp(x_idx2)
        
        
        %finds the x coordinates of the mouse clicks and relates these to
        %the segment chosen in Main Window. ginput returns decimals and
        %this cannot be used for indexing the data later. Hence the use of
        %floor.
        x_idx1 = ( floor((x(1,1)) - t1)*sample_rate); 
        x_idx2 = ( floor((x(2,1) -t1 )*sample_rate));
%         x_idx3 =(x_idx2-x_idx1)+1;

        %extracting template data from segment chosen in Main Window
        template_data = cross_channel(x_idx1:x_idx2);
        
        %extracting time from segment chosen in Main Window
        template_time = cross_channel_time(x_idx1:x_idx2);
        
         TemplatePlot(template_time, template_data);
      
end

    function TemplatePlot(template_time, template_data)
        
        %setting the threshold box to default. 
        set(CrossTemplateThresholdTextEdit,'String',threshold);

        %changes colour of template depending on selection time
        col = [];
        if template_time(end)<= KA_injection_time;
            col = [0 0.5 0];
        else
            col = [0 0 1];
        end
        
        plot(TemplatetPlotAxes,...
        template_time,template_data,'color',col);
        grid(TemplatetPlotAxes);
        xlabel(TemplatetPlotAxes,'Time (s)');
        ylabel(TemplatetPlotAxes,'LFP amplitude (mV)');
        title(TemplatetPlotAxes,'Template');
        xlim(TemplatetPlotAxes,[min(template_time) max(template_time)])

        
        %Updates Template Information
        TemplateInfo();
   
    end

    function TemplateInfo
        
                %Template length to be displayed
                 template_duration = length(template_data)*(1/sample_rate);
                 
                 %Template Start Time
                 template_start = cross_channel_time(x_idx1);
                 
                 %Template End Time
                 template_end = cross_channel_time(x_idx2-t1);
                 
                 %Segment min voltage display
                 template_min_voltage = min(min(template_data));

                 %Segment max voltage display
                 template_max_voltage = max(max(template_data));
            

                %Set to display template information
                set(CrossTemplateInfoVarText,'String',{[num2str(template_start),' s'],...
                    [num2str(template_end),' s'],[num2str(template_duration),' s'],...
                [num2str(template_min_voltage),' mV'],...
                [num2str(template_max_voltage),' mV']});
            
    end
                 
               


function CrossFFTCallback(hObject,eventdata,handles)
    
         %finds length of segment chosen in Main Window
        L=length(cross_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;
        
    
        %creating windows for fourier transform plot
        windows_fft=fft(cross_channel,NFFT)/L;

% 
%         FT_cross_channel = fft(cross_channel); %put in freq space
%         freq_range = linspace(0,sample_rate,length(cross_channel)); %making frequency range same length as VE for filter

       
%         Plots discrete absolute fourier transform of segment data
%         in new window
%         Create a new figure window on which to export the parent plot
%         FourierPlot = figure('ReSize','on','Name', 'Frequency Information','NumberTitle','off');
%         plot(freq_range,abs(FT_cross_channel))
%         title(gca,['Absolute Fourier Transform of ',...
%             reference_channel,' (',num2str(t1,...
%             '%.0f'),'s and ',num2str(t2,'%.0f'),'s)']);
%         ylabel(gca,'mVs^-1');
%         xlabel(gca, 'Frequency (Hz) ');
%         axis tight
       

        % Plots discrete absolute fourier transform of segment data
        % in new window
        % Create a new figure window on which to export the parent plot
        FourierPlot = figure('ReSize','on','Name', 'Frequency Information','NumberTitle','off');
        plot(freq,2*abs(windows_fft(1:NFFT/2+1)));
        title(gca,['Absolute Fourier Transform of ',...
            reference_channel,' (',num2str(t1,...
            '%.0f'),'s and ',num2str(t2,'%.0f'),'s)']);
        ylabel(gca,'Intensity (mV)');
        xlabel(gca, 'Frequency (Hz) ');
        xlim(gca,[1 300]);
        

end


    function CrossTemplateGOButtonCallback(hObject,eventdata,handles)
        
%         %resets axis
%         cla(CrossMainSegPlotAxes,'reset');
        
        %Refereshes plot
        CrossChannelPlot();
        
        %Checks if user entered a numerical value
        if isnan(str2double(get(CrossTemplateThresholdTextEdit,'String')));
            
            %Displays instruction to user in edit box
            set(CrossTemplateThresholdTextEdit, 'String', 'Number less than 1');
            
            %stops program
            return
            
        end
               
        
        %checks to see if template data and time variabls have been assigned
        if ~isempty(template_data) && ~isempty(template_time)
        
        %Runs Correlation algorithm with user defined threshold    
        Correlation(template_data);
      
        end            
    end



    function Correlation(template_data)
        
      x_idx3=(x_idx2-x_idx1)+1;

      %makes template and user selected segment from the Main Window the
      %same length as the
      xcorr_template=zeros(1,length(cross_channel));
      
      %assigns the template to the beginning of the zeros array
      xcorr_template(1:x_idx3) = template_data;
      
      %Calculating the correlation between the the user selected segment from the
      %Main Window and the user selected template.
      %Correlation is normalized between 1,1
      [corr,lags] = xcorr(cross_channel,xcorr_template,'coeff'); 
      max_val=max(corr);
      scaling_factor=1/max_val;
      corr_norm=corr.*scaling_factor;

      index=(length(cross_channel))-x_idx3;
      index2=(index+length(cross_channel))-1;
      corr_norm2=corr_norm(index:index2);

      CorrelationThresholdPlot(corr_norm2);



     %Displays template matches
        TemplateMatchPlot();
 
    end

    function CorrelationThresholdPlot(corr_norm2)
        
         figure('NumberTitle','off','Name', 'Cross-Correlation Threshold plot')
        
       
         
        %plots all of the calculated correlation coefficents for the
        %template and the ssignal carried forward from 
        plot(gca,cross_channel_time,corr_norm2);
        title(gca,['Correlation Coefficient plot for ', num2str(template_duration) 's Template']);
        xlabel(gca,'Time (s)');
        ylabel(gca,'Normalised Correlation Coefficient');
        xlim([min(cross_channel_time) max(cross_channel_time)]);
       
         %to highligh basal period
         if t1 < KA_injection_time == 1 ;

             ka_corr_length = KA_injection_time - t1;
             KA_corr_sig = corr_norm2(1:ka_corr_length*sample_rate+1);
             KA_corr_time = t1:1/sample_rate:KA_injection_time;

            %plots all of the calculated correlation coefficents for the
            %template and the segment carried forward from Main Window
             plot(gca,cross_channel_time,corr_norm2,...
                 KA_corr_time,KA_corr_sig);
             title(gca,['Plot of Correlation Coefficient vs Time of ',...
                 num2str(template_duration) 's Template']);
             xlabel(gca,'Time (s)');
             ylabel(gca,...
                 'Normalised Correlation Coefficient');
             xlim([min(cross_channel_time) max(cross_channel_time)]);
             
           
         end
           

        hold on

        %uses threshold defined by user in algorithm
        threshold = str2double(get(CrossTemplateThresholdTextEdit,'String'));
        
        %initialising variable
        threshold_lines=zeros(length(corr_norm2),1);
        
            %creates threshold line
            for a = 1:length(corr_norm2)
                threshold_lines(a)=threshold;
            end
        
        %plots threshold line on same axis
        plot(gca,cross_channel_time,threshold_lines,'r');
        
        
        if t1<=KA_injection_time == 1 && t2>= KA_injection_time == 1;
            
            legend(gca,'Post-KA administration','Pre-KA administration',['Threshold ',num2str(threshold)],...
                'Location', 'North');
        elseif t1<=KA_injection_time == 1 && t2<= KA_injection_time == 1;
            
            legend(gca,'Pre-KA administration',['Threshold ',num2str(threshold)],...
                'Location', 'North');
            
        elseif t1>=KA_injection_time == 1 && t2>= KA_injection_time == 1;
            
            
            legend(gca,'Post-KA administration',['Threshold ',num2str(threshold)],...
                'Location', 'South');
        end

       
             
        hold off
  
    end



    function TemplateMatchPlot
    
    %makes the top axes the current axes in the program
    axes(CrossMainSegPlotAxes);
    
 
    
    hold on
    
    %locates correlation coefficients that exceed threshold
    locs=find(corr_norm2 >= threshold);
          
    j=1;
    for d=1:length(locs)-1        
    n=locs(d);            
     if locs(d+1)- locs(d) ==1 ;
     if (corr_norm2(n+1)- corr_norm2(n))<= 0 && (corr_norm2(n-1)- corr_norm2(n))<=0; 
     location(j)=n;
     j=j+1;
     end
     end
    end
    
k=1;

%Template match information prints to the command window
disp ([' Template and any matching locations are of length '  num2str(template_duration, 2) ' seconds']);

post_kA_count = 0;
pre_KA_count = 0;



for d=1:length(location)
    b=location(d);
    a=location(d) - (template_duration*sample_rate);
    a=round(a);
    template_index(k)=a;
    b=round(b);
    template_index(k+1)=b;
    match_loc = cross_channel_time(a);
         
        %determines pre-KA and post KA number of seizures
        if match_loc >= KA_injection_time;
            post_kA_count = post_kA_count + 1;
        else
            pre_KA_count = pre_KA_count + 1;
        end
        
    disp(['The start time of the ' num2str(d) 'th template match is ' num2str(match_loc) ' seconds']);
    plot(cross_channel_time(a:b),cross_channel(a:b),'r');
%     title(['Segment of ',reference_channel,' between ',num2str(t1,...
%             '%.0f'),'s and ',num2str(t2,'%.0f'),'s displaying all ', num2str(locs), ' template matches']);



            if t1<=KA_injection_time == 1 && t2>= KA_injection_time == 1;

                legend(CrossMainSegPlotAxes,'Post-KA administration','Pre-KA administration','Template Match(es)',...
                    'Location', 'NorthEast');
            elseif t1<=KA_injection_time == 1 && t2<= KA_injection_time == 1;

                legend(CrossMainSegPlotAxes,'Pre-KA administration','Template Match(es)',...
                    'Location', 'NorthEast');

            elseif t1>=KA_injection_time == 1 && t2>= KA_injection_time == 1;


                legend(CrossMainSegPlotAxes,'Post-KA administration','Template Match(es)',...
                    'Location', 'NorthEast');
            end


            k=k+2;

end

           
        Number_Pre_KA_Events = pre_KA_count;
        Number_Post_KA_Events = post_kA_count;


    
        hold off
    
  

      %updates seizure results panel      
        set(CrossResultsInfoVarText, 'String',{num2str(length(location)),...
            num2str(Number_Pre_KA_Events),num2str(Number_Post_KA_Events)});
        
        %allows user to select template matches in the top axis to view in
        %the template axes as well as the vew all button
        set(CrossMainSegPlotAxes,'ButtonDownFcn',@TemplateSelect);
        
        
        
    end



% function CrossResultsAllViewButtonCallback(hObject,eventdata,handles)
%     
%     
%         %Make the top axis the current axes
%         axes(CrossMainSegPlotAxes);
%     
%         % Create a new figure window on which to export the parent plot
%         SeparatePlot = figure('ReSize','on', 'Name', 'Viewing All Template Matches','NumberTitle','off');
%         
%         % Copy all the objects from the parent plot axes to this new figure
%         % window
%         copyobj(CrossMainSegPlotAxes,SeparatePlot);
%         
%                
%         % Resize the plot axes to fill the new figure window
%         set(gca,'OuterPosition',[0 0 1 1])
%         
%         %changing zoom property of undocked figure
%         zoom xon
%         %so that the zoom is not toggled when the window opens
%         zoom off
%         
%         
%         set(gca,'ButtonDownFcn',@TemplateSelect);
%         
%          
%          pause
%          
%          %gets x coordinates of mouse click inside undocked axis
%          [point, y] = getpts(gca);
%         
%         
%          %finds template clicked on in figure and displays it in the
%          %template axis in red
%         x=point*sample_rate;
%         for h=(1:2:length(template_index));
%             if x >= template_index(h);
%                 c=template_index(h);
%                 x2=(find(template_index(1:end) == c))+1;
%                 if x<=template_index(x2);
%                     d=template_index(x2);
%                     
%                     plot(TemplatetPlotAxes,cross_channel_time(c:d),...
%                         cross_channel(c:d),'r'); 
%                     grid(TemplatetPlotAxes);
%                     title(TemplatetPlotAxes,'Selected Template Match');
%                     xlabel(TemplatetPlotAxes,'Time /s');
%                     ylabel(TemplatetPlotAxes,'Voltage muV');
%                 else
%                     
%                 end
%             else
%             end
%         end
%         
%         
%      
%         
% end


% 
% function CrossResultsViewButtonCallback(hObject,eventdata,handles)
%     
% 
%     %Obtain the data cursor mode object,specify data tip option to select
%     %nearest sample point to mouse
%     dcm_obj = datacursormode(CrossMainSegPlotAxes);
%     set(dcm_obj,'DisplayStyle','datatip',...
%     'SnapToDataVertex','on','Enable','on')
% 
%     %waits for user to click
%     pause
%     
%     
%     %gets the index of the selected data point
%     dataIndex = get(event_obj,'DataIndex');
%     
% %        template_index_counter = [];
%  
%     
%     set(CrossTemplateInfoVarText,'String',dataIndex);
% 
%     
% end


% function GetTemplateIndex( ~,event_obj)
%     
% 
%         % Create a new figure window on which to export the parent plot
%         SeparatePlot = figure('ReSize','on', 'Name', 'Viewing All Template Matches','NumberTitle','off');
%         
%         % Copy all the objects from the parent plot axes to this new figure
%         % window
%         copyobj(CrossMainSegPlotAxes,SeparatePlot);
%         
%                
%         % Resize the plot axes to fill the new figure window
%         set(gca,'OuterPosition',[0 0 1 1])
%         
%         %changing zoom property of undocked figure
%         zoom xon
%         %so that the zoom is not toggled when the window opens
%         zoom off
%         
%         
%         set(gca,'ButtonDownFcn',@TemplateSelect);
%         
%          
%          
%          
%          %gets x coordinates of mouse click inside undocked axis
%          [point, y] = getpts(gca);
%         
%         
%          %finds template clicked on in figure and displays it in the
%          %template axis in red
%         x=point*sample_rate;
%         for h=(1:2:length(template_index));
%             if x >= template_index(h);
%                 c=template_index(h);
%                 x2=(find(template_index(1:end) == c))+1;
%                 if x<=template_index(x2);
%                     d=template_index(x2);
%                     
%                     plot(TemplatetPlotAxes,cross_channel_time(c:d),...
%                         cross_channel(c:d),'r'); 
%                     grid(TemplatetPlotAxes);
%                     title(TemplatetPlotAxes,'Selected Template Match');
%                     xlabel(TemplatetPlotAxes,'Time (s)');
%                     ylabel(TemplatetPlotAxes,'Voltage (mV)');
%                 else
%                     
%                 end
%             else
%             end
%         end
%         
%         
%      
%         
% end

    function TemplateSelect(hObject,eventdata,handles)
        
         pause
         
         %gets x coordinates of mouse click inside undocked axis
         [point, y] = getpts(gca);
        
        
         %finds template clicked on in figure and displays it in the
         %template axis in red
        x=point*sample_rate;
        for h=(1:2:length(template_index));
            if x >= template_index(h);
                c=template_index(h);
                x2=(find(template_index(1:end) == c))+1;
                if x<=template_index(x2);
                    d=template_index(x2);
                    
                    plot(TemplatetPlotAxes,cross_channel_time(c:d),...
                        cross_channel(c:d),'r'); 
                    grid(TemplatetPlotAxes);
                    title(TemplatetPlotAxes,'Selected Template Match');
                    xlabel(TemplatetPlotAxes,'Time (s)');
                    ylabel(TemplatetPlotAxes,'LFP amplitude (mV)');
                    xlim(TemplatetPlotAxes, [cross_channel_time(c) cross_channel_time(d)]);
                else
                    
                end
            else
            end
        end
    end
    

end