function varargout = Main_Prog_Window(varargin)

% Sample rate; enter a numerical value only
SampleRate = 1000;%Hz

%KA default injection time
KA_Default = 600;%s


% Default voltage setting; kV = 1, V = 2, mV = 3, microV = 4, nV = 5.
VoltageSelNum = 3;

% Create a saving variable for the file location
mSignalFile = [];

% Loading required global variables
global reference_channel sample_rate channel_length channel_time t1 t2
global VoltageScale VoltageValue segment_length KA_injection_time
global segment_signal
   

% Generating the main figure window
MainFigure = figure('Units','characters','MenuBar','none','Name',...
    'Main Window','NumberTitle','off','Position',[10 10 290 58],'ReSize',...
    'on','Visible','off');



% Generating the required panels in the figure window for object
% construction
MainLoadFilePanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[1 53 248 4],'Title','1. Load Signal File','FontWeight','bold');
MainListboxPanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[1 20 38 33],'Title','Loaded Signals','FontWeight','bold');
MainSignalAcquiInfoPanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[1 12 38 8],'Title','LFP Acquisition Information','FontWeight','bold');
MainPlotPanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[40 1 209 51.5]);
MainSignalInfo2Panel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[250 43 38 10],'Title','LFP Signal Information','FontWeight','bold');
MainSignalSegmentationPanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[250 1 38 8.5],'Title','Epoch Selection','FontWeight','bold');
MainSegmentSignalInfoPanel = uipanel('Parent',MainFigure,'Units',...
    'characters','Position',[250 15 38 10],'Title','Epoch Segment Information','FontWeight','bold');
MainDetectionAnalysisPanel = uipanel('Parent',MainFigure,'Units',...
    'characters','Position',[1 1 38 11],'Title','Detection Analyses','FontWeight','bold');



% Setting the string for the load file text field
MainLoadFileText = 'Click Load to browse for a signal file';

% Setting the strings for the voltage scale drop-down list
VoltageName = {'kV','V','mV','microV','nV'};

% Displayed voltage scale strings (allows for Greek letters)
VoltageScale = {'kV','V','mV','\muV','nV'};



% Setting the information section string labels for Main Signal Information
MainSignalAcquInfoText = {'','Sample Rate:', 'KA injection (s):','', 'Voltage Scale'};
        %needs to be linked with edit text for start and end times and also
        %text for signal information.
        
% Setting the information section string labels for Segmentation
MainSegmentationText = {'Start Time:','', 'End Time:',''};

% Setting the information section string labels for Main Signal Information
MainSignalInfo2Text = {'Start Time:','End Time:',...
    'Min Voltage:','Max Voltage:','Samples:'};
                
% Setting the information section string labels for segmented signal
MainSegmentSignalInfoText = {'Start Time:','End Time:',...
    'Min Voltage:','Max Voltage:','Samples:'};

%Sample Rate text field
MainSampleRateTextField = uicontrol('Parent',MainSignalAcquiInfoPanel,'Units',...
    'characters', 'Callback', @MainSampleRateTextCallback,'Enable',...
    'off','BackgroundColor','w','Position',[20 4.25 11 1],'String',[],'Style','edit');

%Sample Rate units text
MainSampleRateUnitText = uicontrol('Parent',MainSignalAcquiInfoPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.85 0.59 0.1 0.2],'String','Hz','Style',...
    'text');

%KA Injection time text field
KAInjectionTextField = uicontrol('Parent',MainSignalAcquiInfoPanel,'Units',...
    'characters', 'Callback', @KAInjectionTextButtonCallback,'Enable',...
    'off','BackgroundColor','w','Position',[20 3.0 11 1],'String',[],'Style','edit');

%KA Injection units text
MainKAInjectionUnitText = uicontrol('Parent',MainSignalAcquiInfoPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.85 0.39 0.1 0.2],'String','s','Style',...
    'text');
        
% Segmentation Start time text field
MainSegStartTextField = uicontrol('Parent',MainSignalSegmentationPanel,'Units',...
    'characters', 'Enable','off','BackgroundColor','w',...
    'Position',[20 5.25 11 1],'String',[],'Style','edit');

%Segmentation End units text
MainSegmentationEndUnitText = uicontrol('Parent',MainSignalSegmentationPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.85 0.69 0.1 0.2],'String','s','Style',...
    'text');

% Segmentation End time text field
MainSegEndTextField = uicontrol('Parent',MainSignalSegmentationPanel,'Units',...
    'characters','Enable',...
    'off','BackgroundColor','w','Position',[20 3.25 11 1],'String',[],'Style','edit');

%Segmentation End units text
MainSegmentationEndUnitText = uicontrol('Parent',MainSignalSegmentationPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.85 0.39 0.1 0.2],'String','s','Style',...
    'text');

% Manual segmentation 'OK' button
MainSegTextButton = uicontrol('Parent',MainSignalSegmentationPanel,'Units',...
    'characters','Callback',@MainSegTextButtonCallback,'Enable','on',...
    'Position',[20 0.5 11 2],'String','OK');



% 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 reference channel signal
MainChannelPlotAxes = axes('Parent',MainPlotPanel,'Units','normalized',...
    'OuterPosition',[0 0.5 1 0.5]);

% Plot manipulation buttons for the reference channel plot axes
MainChannelZoomIn = uicontrol('Parent',MainPlotPanel,'Units',...
    'normalized','Callback',@ZoomIn,'Position',[0.93 0.84375 0.03 0.06],'Cdata', zoomplus.cdata,...
    'Style','togglebutton','TooltipString',...
    'Click, Drag, or Scroll along the Plot to Zoom In','Value',0);
MainChannelZoomOut = uicontrol('Parent',MainPlotPanel,'Units',...
    'normalized','Callback',@ZoomOut,...
    'Position',[0.93 0.76375 0.03 0.06],'Cdata', zoomminus.cdata,'Style','togglebutton',...
    'TooltipString','Click, Drag, or Scroll along the Plot to Zoom Out',...
    'Value',0);
MainChannelPan = uicontrol('Parent',MainPlotPanel, 'Units','normalized',...
    'Callback',@PanCallback,'Position',...
    [0.93 0.67375 0.03 0.06],'Cdata', panbtn.cdata,...
    'Style','togglebutton','TooltipString',...
    'Click to Pan along the Plot','Value',0);
MainChannelUnDock = uicontrol('Parent',MainPlotPanel,'Units',...
    'normalized','Callback',{@UnDock,MainChannelPlotAxes},'CData',...
    undock.cdata,'Position',[0.93 0.59375 0.03 0.06],'TooltipString',...
    'Click to Undock Plot into a new Figure');



% Creating plot axes for the segment signal
MainSegmentPlotAxes = axes('Parent',MainPlotPanel,'Units','normalized',...
    'OuterPosition',[0 0 1 0.5]);

% Plot manipulation buttons for segment plot axes
MainSegmentZoomIn = uicontrol('Parent',MainPlotPanel,'Units',...
    'normalized','Callback',@ZoomIn,'Position',...
    [0.93 0.34375 0.03 0.06],'Cdata', zoomplus.cdata,...
    'Style','togglebutton','TooltipString',...
    'Click, Drag, or Scroll along the Plot to Zoom In','Value',0);
MainSegmentZoomOut = uicontrol('Parent',MainPlotPanel,'Units',...
    'normalized','Callback',@ZoomOut,...
    'Position',[0.93 0.26375 0.03 0.06],'Cdata', zoomminus.cdata,'Style','togglebutton',...
    'TooltipString','Click, Drag, or Scroll along the Plot to Zoom Out',...
    'Value',0);
MainSegmentPan = uicontrol('Parent',MainPlotPanel,'Units','normalized',...
    'Callback',@PanCallback,'Position',...
    [0.93 0.17375 0.03 0.06],'Cdata', panbtn.cdata,'Style','togglebutton','TooltipString',...
    'Click to Pan along the Plot','Value',0);
MainSegmentUnDock = uicontrol('Parent',MainPlotPanel,'Units',...
    'normalized','Callback',{@UnDock,MainSegmentPlotAxes},'CData',...
    undock.cdata,'Position',...
    [0.93 0.09375 0.03 0.06],'TooltipString',... 
    'Click to Undock Plot into a new Figure');


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



% Load file text field
MainLoadFileTextField = uicontrol('Parent',MainLoadFilePanel,'Units',...
    'normalized','BackgroundColor','w','ButtondownFcn',...
    @LoadFileTextButtonDown,'Callback',@MainLoadFileTextCallback,...
    'Enable','inactive','HorizontalAlignment','left','Position',...
    [0.01 0.24 0.87 0.6],'String',MainLoadFileText,'Style','edit');

% Load file button - opens file dialogue window
MainLoadFileButton = uicontrol('Parent',MainLoadFilePanel,'Units',...
    'normalized','Callback',@MainLoadFileButtonCallback,'Position',...
    [0.89 0.2 0.1 0.7],'String','Load','ToolTipString',...
    'Import Signal data file From Matlab');
     
% Signal selection list box
MainRefSelectListBox = uicontrol('Parent',MainListboxPanel,'Units',...
    'normalized','Enable','off','HorizontalAlignment','left',...
    'Position',[0.05 0.21 0.9 0.74],'String',[],'Style','listbox',...
    'TooltipString','Select the Reference Channel Variable e.g. AD01','Value',1);

% 'Select' button
MainRefSelectButton = uicontrol('Parent',MainListboxPanel,'Units',...
    'normalized','Callback',@MainRefSelectButtonCallback,'Enable',...
    'off','Position',[0.1 0.059 0.8 0.09],'String',...
    'Select');


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

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

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

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

% Setting the segment information section values
MainSegInfoVarText = uicontrol('Parent',MainSegmentSignalInfoPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.5 0.04 0.45 0.92],'String',{''},'Style',...
    'text');

% Setting the segmentation information section labels
MainSignalInfoTitleText = uicontrol('Parent',MainSignalSegmentationPanel,'Units',...
    'normalized','HorizontalAlignment','left',...
    'Position',[0.05 0.04 0.45 0.92],'String',MainSegmentationText,'Style',...
    'text');

% Voltage scale drop-down list
MainVoltageScaleDrop = uicontrol('Parent',MainSignalAcquiInfoPanel,'Units',...
    'characters','Callback',@MainVoltageScaleSelect,'Enable',...
    'off','Position',[20 1.5 11 1],'String',VoltageName,'Style',...
    'popupmenu','Value',VoltageSelNum);


% % Manual segmentation 'OK' button
% MainSegTextButton = uicontrol('Parent',MainSignalSegmentationPanel,'Units',...
%     'characters','Position',[17 0.5 11 2],'Callback',@MainSegTextButtonCallback,'Enable','on',...
%     'String','OK','TooltipString','NOTE: the segment will be used for further analysis');

% %Detection algorithm button group
% DetectionAlgBtnGroup = uibuttongroup('Parent',MainDetectionAnalysisPanel,...
%             'Units','characters','Position',[0.01 0.1 32.09 14],'SelectionChangeFcn',...
%                 @DetectionSelectionChangeFn,'SelectedObject',[], 'Visible', 'off');

%Detection Algorithm buttons in button group
FreqDetectButton = uicontrol(MainDetectionAnalysisPanel,...
                'Units','normalized','String','Frequency','FontWeight','bold',...
                'Position',[0.1 0.73 0.8 0.17],...
                'Callback', @FeqDetectButtonCallback,'TooltipString',...
                'Seizure Detection based on Frequency components of Segment');
            
MeanAvDetectButton = uicontrol(MainDetectionAnalysisPanel,...
                'Units','normalized','String','Mean Average','FontWeight','bold',...
                'Position',[0.1 0.56 0.8 0.17],'Callback',...
                @MeanAvDetecttButtonCallback,'TooltipString',...
                'Seizure Detection based on Segments Averaged Mean Amplitude');
            
CrossCorDetectButton = uicontrol(MainDetectionAnalysisPanel,...
                'Units','normalized','String','Cross Correlation','FontWeight','bold',...
                'Position',[0.1 0.38 0.8 0.17],'Callback',...
                @CrossCorDetectButtonCallback,'TooltipString',...
                'Analysis based on a selected Template in the next window');
            
EntropyDetectButton = uicontrol(MainDetectionAnalysisPanel,...
                'Units','normalized','String','Entropy','FontWeight','bold',...
                'Position',[0.1 0.21 0.8 0.17],'Callback',...
                @EntropyDetectButtonCallback,'TooltipString',...
                'Calculate the Shannon Entropy of the Segment');

% SpikeFreqDetectButton = uicontrol(MainDetectionAnalysisPanel,...
%                 'Units','normalized','String','Spike Frequency','FontWeight','bold',...
%                 'Position',[0.1 0.03 0.8 0.17],'Callback',...
%                 @SpikeFreqDetectButtonCallback,'TooltipString',...
%                 'Seizure Detection based on Spike Frequency of Segment');



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

% Setting the sample rate
sample_rate = SampleRate;


if ~isempty(evalin('base','who'))
    
    % Enable the reference selection list box and button if there are
    % available variables on the base workspace
    set(MainRefSelectListBox,'BackgroundColor','w','Enable','on')
    set(MainRefSelectButton,'Enable','on')
    
    % Run the load workspace variable function to add the variables to the
    % list box string
    loadWorkspaceVar();
    
end

% Make the Main Window visible now that initialisation has been completed
set(MainFigure,'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 ZoomIn(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 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 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 LoadFileTextButtonDown(hObject,eventdata)
        
        % Clear the load file text button when it is selected but remove
        % the clearing function so that the user can edit the written path
        set(hObject,'String','','Enable','on','ButtonDownFcn',[]);
        uicontrol(hObject);
        
    end



 function loadSigFile
                              
        %Check that a valid string has been entered into the text
        % field
        if strcmp(mSignalFile,MainLoadFileText)==0
            
            % Set the file location variable as the text field string
            set(MainLoadFileTextField,'String',mSignalFile)
            
            % Enable the reference selection list box
            set(MainRefSelectListBox,'BackgroundColor','w',...
                'Enable','on');
            set(MainRefSelectButton,'Enable','on');
            
            % Load the file
            evalin('base',['load ''',mSignalFile,'''']);
            
            % Extract the base workspace variables
            loadWorkspaceVar();
    
        end
 end

 function loadWorkspaceVar(hObject,eventdata,handles)
          % Obtaining the variable string from the base workspace
        variables = evalin('base','who');
        
        % Setting the reference channel selection list box to display the
        % base workspace variable strings
        set(MainRefSelectListBox,'String',variables);
        
        % Run through every variable
        for jj = 1:length(variables)
            
            % Evaluate each variable
            var = evalin('base',variables{jj});
            
            % Check that the variable is in the correct orientation
            if size(var,2)>size(var,1)
                
                % Re-assign the variable in the correct orientation if it
                % is not
                assignin('base',variables{jj},var') ;
                
            end
        end
        
 end



function MainLoadFileButtonCallback(hObject,eventdata)
    
    
        %clear the axes
        AxesReset();
        
        
        % Set the open file dialogue window to only accept Matlab .mat
        % files
        filespec = {'*.mat', 'MATLAB .MAT files (*.mat)'};
        
        % Load the open file dialogue window
        [filename,pathname] = uigetfile(filespec,'Pick a data file',pwd);
        
        % Check that the filename isn't empty
        if ~isequal(filename,0)
            
            % Set the file location variable
            mSignalFile = fullfile(pathname,filename);
            
            % Load the signal file
            loadSigFile();
            
        end
        
        
    end

function MainRefSelectButtonCallback(hObject,eventdata)
    
    % Enable the sample rate, KA injection voltage scale section
        set(MainSampleRateTextField,'BackgroundColor','w',...
            'ButtondownFcn',@ButtonDown,'Enable','inactive', 'String',SampleRate);
        set(KAInjectionTextField,'BackgroundColor','w',...
            'ButtondownFcn',@ButtonDown,'Enable','inactive', 'String',KA_Default)
        set(MainVoltageScaleDrop,'BackgroundColor','w',...
             'Enable','on','Value',VoltageSelNum,'String',VoltageName)
         
     %Reset segment plot
     cla(MainSegmentPlotAxes,'reset');
     
     %Clear segment information
     set(MainSegInfoVarText, 'String', {''});
         
        
    
    
    % Load the variable strings from the base workspace
        variables = evalin('base','who');
        
        % Select the reference channel from these variable strings
        reference_channel = variables{get(MainRefSelectListBox,'Value')};
        uicontrol(hObject); 
        
       % Clear the segment plot axes and update the reference channel plot
%         cla(MainSegmentPlotAxes,'reset');

        
        
        MainChannelPlot();         
end

function MainSampleRateTextCallback(hObject,eventdata,handles)
        
        % Convert the sample rate string to a numerical value
        sample_rate = str2double(get(hObject,'String'));
        
        % Perform checks
        if isnan(sample_rate)
            
            % Display this message if it is not a numerical value
            set(MainSampleRateTextField,'String',['Number only'])
            
            % Stops the program
            return
            
        elseif sample_rate<=0
            
            % Displays this message if the sample rate is less than 1Hz
            set(MainSampleRateTextField,'String',['Must be greater ',...
                'than 0Hz'])
            
            % Stops the program
            return
            
        end

        
        % Clear the segment plot axes and update the reference channel plot
%         cla(MainSegmentPlotAxes,'reset');

        MainChannelPlot();        
        
end

function MainVoltageScaleSelect(hObject,evendata,handles)
        
        % Check there is a valid number for the sample rate
        if ~isnan(str2double(get(MainSampleRateTextField,'String')))
            
            % Obtain the selected voltage value
            VoltageValue = get(MainVoltageScaleDrop,'Value');
            
            %assuming microV as default
            
            % Update the signal information units
            SigInfoSet();
            
            % Change the y-labels of the plot axes
            ylabel(MainChannelPlotAxes,['LFP amplitude (',VoltageScale{...
                VoltageValue},')']);
            ylabel(MainSegmentPlotAxes,['LFP amplitude (',VoltageScale{...
                VoltageValue},')']);
           
        end
end

 
      
function KAInjectionTextButtonCallback(hObject,evendata,handles)
    
      
    % Check there is a valid number for the KA injection time
        if ~isnan(str2double(get(hObject,'String')))
            
           %Convert KA injection time text field into numerical value
           KA_injection_time = str2double(get(KAInjectionTextField,'String'));
           uicontrol(hObject);
                     
        
        end
    
end



function MainChannelPlot
        
        % Checks that a valid number has been entered for the sample rate
        if ~isnan(str2double(get(MainSampleRateTextField,'String')))
            
            % Obtains the voltage scale selection value
            VoltageValue = get(MainVoltageScaleDrop,'Value');
            
            % Determines the length of the reference channel signal
            channel_length = length(evalin('base',reference_channel))/...
                sample_rate;
                     
            % Calculates the reference channel signal time scale
            channel_time = 0:1/sample_rate:channel_length-1/sample_rate;
            
            Ka_main_time = 0:1/sample_rate:KA_injection_time;
                      
            %  updates the signal information
            SigInfoSet(); SegPanelSet();
               
            % Plot the reference channel signal in the channel plot axes
            plot(MainChannelPlotAxes,channel_time,evalin('base',...
                reference_channel));    
            grid(MainChannelPlotAxes);
            xlabel(MainChannelPlotAxes,'Time (s)');
            xlim([0 channel_time(end)]);
            ylabel(MainChannelPlotAxes,['LFP amplitude (',...
                VoltageScale{VoltageValue},')']);
            title(MainChannelPlotAxes,['LFP Channel ',...
                reference_channel]);
            xlim(MainChannelPlotAxes,[min(channel_time) max(channel_time)]);
            
            
        
            
            seg_begin = channel_time(1);
            seg_end = channel_time(end);

            set(MainSegStartTextField, 'String', seg_begin);
            set(MainSegEndTextField, 'String', seg_end);
            
            
           
            
        end
end

 function SegPanelSet
        
        %Enables all relevant objects in the segmentation panel
        set(MainSegTextButton,'ButtondownFcn',@MainSegTextButtonCallback,'Enable', 'on')
        set(MainSegStartTextField,'BackgroundColor','w',...
            'ButtondownFcn',@ButtonDown,'Enable','inactive')
        set(MainSegEndTextField, 'BackgroundColor','w',...
            'ButtondownFcn',@ButtonDown,'Enable','inactive')
        
        
    end

function MainSegTextButtonCallback(hObject,evendata,handles)
    
            
            % Convert the start and end time text fields into numerical
            % values
            t1 = str2double(get(MainSegStartTextField,'String'));
            t2 = str2double(get(MainSegEndTextField,'String'));
        
            % Determine if both are valid numbers
            numerical_error_check = isnan([t1 t2]);
        
            % Determine if they both fall within the reference channel time
            % scale
             time_error_check = [t1<channel_time(1),t2>(round(...
            channel_time(end)*sample_rate)/sample_rate)];
       
            if t1>=t2
            
                % Displayed if the end time is less than or equal to the
                % start time
                set(MainSegEndTextField,'String','>Start Time')
            
                % Stops the program
                return
            
            else
        
            
                % Locates the indices of the segment within the channel
                % signal
                segment_indices = [t1*sample_rate+1, t2*sample_rate+1];

                % Extracts the segment from the channel signal
                segment_signal = evalin('base',sprintf('%s(%d:%d)',...
                reference_channel,segment_indices(1),segment_indices(...
                2)));

                % Determines the length and time scale of the segment
                % signal
                segment_length = length(segment_signal);
                segment_time = t1:1/sample_rate:t2;

                % Plot the segment signal in the segment plot axes
                MainSegPlot(segment_time,segment_signal);


                % Update the information panel
                SigInfoSet();
                
            end
            
%             set(DetectionAlgBtnGroup,'Visible','on');
end


function SigInfoSet
        
           
    
        % Check if a segment has been selected yet
        if isempty(t1)||isempty(t2);
            
            % If not, display all channel signal information but no segment
            % signal information
                set(MainChannelInfoVarText,'String',{[num2str(channel_time(...
                1)),' s'],[num2str(channel_time(end)),' s'],...
                [num2str(min(min(evalin('base',reference_channel)))),' ',...
                VoltageScale{VoltageValue}],[num2str(max(max(evalin('base',...
                reference_channel)))),' ',VoltageScale{VoltageValue}],num2str(channel_length*...
                sample_rate)});
            
        else
            
                % Obtains the indices of the segment signal in the channel
                % signal
                 segment_indices = [t1*sample_rate+1, t2*sample_rate+1];

                 % Extracts the segment signal from the channel signal
                 segment_signal = evalin('base',sprintf('%s(%d:%d)',...
                 reference_channel,segment_indices(1),segment_indices(...
                 2)));

                 %Segment length to be displayed
                 segment_duration = segment_length*(1/sample_rate);

                 %Segment min voltage display
                 segment_min_voltage = min(segment_signal);

                 %Segment max voltage display
                 segment_max_voltage = max(segment_signal);
            

                %Otherwise display all both reference channel and seg info
                set(MainChannelInfoVarText,'String',{[num2str(channel_time(...
                1)),' s'],[num2str(channel_time(end)),' s'],...
                [num2str(min(min(evalin('base',reference_channel)))),' ',...
                VoltageScale{VoltageValue}],[num2str(max(max(evalin('base',...
                reference_channel)))),' ',VoltageScale{VoltageValue}],num2str(...
                channel_length*sample_rate)});
                 
                set(MainSegInfoVarText,'String',{[num2str(t1),' s'],...
                [num2str(t2),' s'],[num2str(segment_min_voltage),' ',...
                VoltageScale{VoltageValue}],[num2str(segment_max_voltage),' ',...
                VoltageScale{VoltageValue}],...
                num2str(segment_length)});
            
        end
    end



    function MainSegPlot(segment_time,segment_signal)
        
             
        % Obtains the selected voltage scale
        VoltageValue = get(MainVoltageScaleDrop,'Value');
        
        % Plots the segment signal to the segment plot axes
        plot(MainSegmentPlotAxes,segment_time,segment_signal);
        grid(MainSegmentPlotAxes);
        xlabel(MainSegmentPlotAxes,'Time (s)');
        xlim(MainSegmentPlotAxes,[min(segment_time) max(segment_time)]);

        ylabel(MainSegmentPlotAxes,['LFP amplitude (',...
            VoltageScale{VoltageValue},')']);
        title(MainSegmentPlotAxes,['Selected Epoch for ',reference_channel,' (',num2str(t1,...
            '%.0f'),'s - ',num2str(t2,'%.0f'),'s)']);
        
    end


    function AxesReset
        
        %Resets both axes in Main Window
        cla(MainChannelPlotAxes, 'reset');
        
        cla(MainSegmentPlotAxes, 'reset');
        
    end

    function FeqDetectButtonCallback(hObject,evendata,handles)
     
%         Obtains the indices of the segment signal in the channel
%          signal
        segment_indices = [t1*sample_rate+1, t2*sample_rate+1];
        

%         Extracts the segment signal from the channel signal
        segment_signal = evalin('base',sprintf('%s(%d:%d)',...
        reference_channel,segment_indices(1),segment_indices(...
        2)));
    
        
%         KA injection time
        KA_time = str2double(get(KAInjectionTextField,'String'));
        
    
%     Creating cell to pass data to CrossCorrelationDetect GUI
        %user segmented data
        OutputForAnalysis{1} = segment_signal;
        
        %user inputted KAinjection time
        OutputForAnalysis{2} = KA_time;
        
        %segment start and end time. 1 cell, 2 elements
        OutputForAnalysis{3}(1) = t1;
        OutputForAnalysis{3}(2) = t2;
        
        %user inputted sample rate
        OutputForAnalysis{4} = sample_rate;
        %
        OutputForAnalysis {5} = reference_channel;
        
        % Disables the figure window
            set(allObjects(isprop(allObjects,'Enable')),'Enable','off')
        
        %Calls and opens Cross correlation GUI
        FrequencyDetect(OutputForAnalysis);
        
        % Enables the figure window
            set(allObjects(isprop(allObjects,'Enable')),'Enable','on')
            
        % Refreshes the reference channel list box
        loadWorkspaceVar();
    end

    function MeanAvDetecttButtonCallback(hObject,evendata,handles)
%       Obtains the indices of the segment signal in the channel
%          signal
        segment_indices = [t1*sample_rate+1, t2*sample_rate+1];
        

%         Extracts the segment signal from the channel signal
        segment_signal = evalin('base',sprintf('%s(%d:%d)',...
        reference_channel,segment_indices(1),segment_indices(...
        2)));
    
        
%         KA injection time
        KA_time = str2double(get(KAInjectionTextField,'String'));
        
    
%     Creating cell to pass data to CrossCorrelationDetect GUI
        %user segmented data
        OutputForAnalysis{1} = segment_signal;
        
        %user inputted KAinjection time
        OutputForAnalysis{2} = KA_time;
        
        %segment start and end time. 1 cell, 2 elements
        OutputForAnalysis{3}(1) = t1;
        OutputForAnalysis{3}(2) = t2;
        
        %user inputted sample rate
        OutputForAnalysis{4} = sample_rate;
        %
        OutputForAnalysis {5} = reference_channel;
        
        % Disables the figure window
            set(allObjects(isprop(allObjects,'Enable')),'Enable','off')
        
        %Calls and opens Cross correlation GUI
        MeanDetect(OutputForAnalysis);
        
        % Enables the figure window
            set(allObjects(isprop(allObjects,'Enable')),'Enable','on')
            
        % Refreshes the reference channel list box
        loadWorkspaceVar();
    end

    function CrossCorDetectButtonCallback(hObject,evendata,handles)
        
%         Obtains the indices of the segment signal in the channel
%          signal
        segment_indices = [t1*sample_rate+1, t2*sample_rate+1];
        

%         Extracts the segment signal from the channel signal
        segment_signal = evalin('base',sprintf('%s(%d:%d)',...
        reference_channel,segment_indices(1),segment_indices(...
        2)));
    
        
%         KA injection time
        KA_time = str2double(get(KAInjectionTextField,'String'));
        
    
%     Creating cell to pass data to CrossCorrelationDetect GUI
        %user segmented data
        OutputForAnalysis{1} = segment_signal;
        
        %user inputted KAinjection time
        OutputForAnalysis{2} = KA_time;
        
        %segment start and end time. 1 cell, 2 elements
        OutputForAnalysis{3}(1) = t1;
        OutputForAnalysis{3}(2) = t2;
        
        %user inputted sample rate
        OutputForAnalysis{4} = sample_rate;
        %
        OutputForAnalysis {5} = reference_channel;
        
        % Disables the figure window
            set(allObjects(isprop(allObjects,'Enable')),'Enable','off')
        
        %Calls and opens Cross correlation GUI
        CrossCorrelationDetect(OutputForAnalysis);
        
        % Enables the figure window
            set(allObjects(isprop(allObjects,'Enable')),'Enable','on')
            
        % Refreshes the reference channel list box
        loadWorkspaceVar();
        
    end

    function EntropyDetectButtonCallback(hObject,evendata,handles)
%         Obtains the indices of the segment signal in the channel
%          signal
        segment_indices = [t1*sample_rate+1, t2*sample_rate+1];
        

%         Extracts the segment signal from the channel signal
        segment_signal = evalin('base',sprintf('%s(%d:%d)',...
        reference_channel,segment_indices(1),segment_indices(...
        2)));
    
        
%         KA injection time
        KA_time = str2double(get(KAInjectionTextField,'String'));
        
    
%     Creating cell to pass data to CrossCorrelationDetect GUI
        %user segmented data
        OutputForAnalysis{1} = segment_signal;
        
        %user inputted KAinjection time
        OutputForAnalysis{2} = KA_time;
        
        %segment start and end time. 1 cell, 2 elements
        OutputForAnalysis{3}(1) = t1;
        OutputForAnalysis{3}(2) = t2;
        
        %user inputted sample rate
        OutputForAnalysis{4} = sample_rate;
        %
        OutputForAnalysis {5} = reference_channel;
        
        % Disables the figure window
            set(allObjects(isprop(allObjects,'Enable')),'Enable','off')
        
        %Calls and opens Cross correlation GUI
        EntropyDetect(OutputForAnalysis);
        
        % Enables the figure window
            set(allObjects(isprop(allObjects,'Enable')),'Enable','on')
            
        % Refreshes the reference channel list box
        loadWorkspaceVar();
    end

    function SpikeFreqDetectButtonCallback(hObject,evendata,handles)
        
%         %         Obtains the indices of the segment signal in the channel
% %          signal
%         segment_indices = [t1*sample_rate+1, t2*sample_rate+1];
% 
% %         Extracts the segment signal from the channel signal
%         segment_signal = evalin('base',sprintf('%s(%d:%d)',...
%         reference_channel,segment_indices(1),segment_indices(...
%         2)));
%         
% %         KA injection time
%         KA_time = str2double(get(KAInjectionTextField,'String'));
%     
% %     Creates cell to pass data to detection GUI platforms
%         InputForAnalysis{1} = segment_signal;
%         InputForAnalysis{2} = KA_time;
    end


end
 