function varargout = Main_Prog_Window(varargin)

% Data Aquisition Sample rate; enter value (Plexon PBX amplifier default = 1kHz)
% 
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 sample_rate channel_length channel_time t1 t2
global VoltageScale VoltageValue segment_length KA_injection_time
global  reference_channel1 reference_channel2 reference_channel3
global reference_channel4 segment_signal1 segment_signal2 segment_signal3
global segment_signal4
   

% Generating the main figure window
MainFigure = figure('Units','characters','MenuBar','none','Name',...
    'Multi-Channel Main Window','NumberTitle','off','Position',[35 3 220 55],'ReSize',...
    'off','Visible','off');


% Generating the required panels in the figure window for object
% construction
MainLoadFilePanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[1 52.5 209 3.5],'Title','1. Load Signal File');

MainListboxPanel_1 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[1 44 33 9],'Title','Select Channel 1');
MainListboxPanel_2 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[1 35 33 9],'Title','Select Channel 2');
MainListboxPanel_3 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[1 26 33 9],'Title','Select Channel 3');
MainListboxPanel_4 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[1 17 33 9],'Title','Select Channel 4');

MainSignalAcquiInfoPanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[1 9 33 8],'Title','LFP Acquisition Information');
MainSignalSegmentationPanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[1 1 33 8],'Title','Segmentation');
MainPlotPanel = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[35 1 140 51]);

MainSignalInfoPanel_1 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[176 44 33 9],'Title','Plot 1: LFP Signal Information');
MainSignalInfoPanel_2 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[176 35 33 9],'Title','Plot 2: LFP Signal Information');
MainSignalInfoPanel_3 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[176 26 33 9],'Title','Plot 3: LFP Signal Information');
MainSignalInfoPanel_4 = uipanel('Parent',MainFigure,'Units','characters',...
    'Position',[176 17 33 9],'Title','Plot 4: LFP Signal Information');

MainDetectionAnalysisPanel = uipanel('Parent',MainFigure,'Units',...
    'characters','Position',[176 1 33 16],'Title','Detection Analyses');



% 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 (Hz):', '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 (s):','', 'End Time (s):',''};


% Setting the information section string labels
MainSignalInfoText = {'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',[17 4.25 11 1],'String',[],'Style','edit');

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

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

% Manual segmentation 'OK' button
% MainSegTextButton = uicontrol('Parent',MainSignalSegmentationPanel,'Units',...
%     'characters','Callback',@MainSegTextButtonCallback,'Enable','on',...
%     'Position',[1.85 0.75 23.3 1.5],'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 1
MainChannelPlotAxes1 = axes('Parent',MainPlotPanel,'Units','normalized',...
    'OuterPosition',[0 0.75 1 0.25]);

% Creating plot axes 2
MainChannelPlotAxes2 = axes('Parent',MainPlotPanel,'Units','normalized',...
    'OuterPosition',[0 0.5 1 0.25]);

% Creating plot axes 3
MainChannelPlotAxes3 = axes('Parent',MainPlotPanel,'Units','normalized',...
    'OuterPosition',[0 0.25 1 0.25]);

% Creating plot axes 4
MainChannelPlotAxes4 = axes('Parent',MainPlotPanel,'Units','normalized',...
    'OuterPosition',[0 0 1 0.25]);


% 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.25 0.87 0.5],'String',MainLoadFileText,'Style','edit');

% Load file button - opens file dialogue window
MainLoadFileButton = uicontrol('Parent',MainLoadFilePanel,'Units',...
    'normalized','Callback',@MainLoadFileButtonCallback,'Position',...
    [0.89 0.25 0.1 0.5],'String','Load','ToolTipString',...
    'Import Signal From Matlab file');
     
% Signal selection list box 1
MainRefSelectListBox1 = uicontrol('Parent',MainListboxPanel_1,'Units',...
    'normalized','Enable','off','HorizontalAlignment','left',...
    'Position',[0.05 0.27 0.9 0.73],'String',[],'Style','listbox',...
    'TooltipString','Select the Reference Channel Variable','Value',1);

% Signal selection list box 2
MainRefSelectListBox2 = uicontrol('Parent',MainListboxPanel_2,'Units',...
    'normalized','Enable','off','HorizontalAlignment','left',...
    'Position',[0.05 0.27 0.9 0.73],'String',[],'Style','listbox',...
    'TooltipString','Select the Reference Channel Variable','Value',1);

% Signal selection list box 3
MainRefSelectListBox3 = uicontrol('Parent',MainListboxPanel_3,'Units',...
    'normalized','Enable','off','HorizontalAlignment','left',...
    'Position',[0.05 0.27 0.9 0.73],'String',[],'Style','listbox',...
    'TooltipString','Select the Reference Channel Variable','Value',1);

% Signal selection list box 4
MainRefSelectListBox4 = uicontrol('Parent',MainListboxPanel_4,'Units',...
    'normalized','Enable','off','HorizontalAlignment','left',...
    'Position',[0.05 0.27 0.9 0.73],'String',[],'Style','listbox',...
    'TooltipString','Select the Reference Channel Variable','Value',1);


% 'Select' button 1
MainRefSelectButton1 = uicontrol('Parent',MainListboxPanel_1,'Units',...
    'characters','Callback',@MainRefSelectButtonCallback1,'Enable',...
    'off','Position',[1.85 0.25 23.3 1.5],'String',...
    'Select');

% 'Select' button 2
MainRefSelectButton2 = uicontrol('Parent',MainListboxPanel_2,'Units',...
    'characters','Callback',@MainRefSelectButtonCallback2,'Enable',...
    'off','Position',[1.85 0.25 23.3 1.5],'String',...
    'Select');

% 'Select' button 3
MainRefSelectButton3 = uicontrol('Parent',MainListboxPanel_3,'Units',...
    'characters','Callback',@MainRefSelectButtonCallback3,'Enable',...
    'off','Position',[1.85 0.25 23.3 1.5],'String',...
    'Select');

% 'Select' button 4
MainRefSelectButton4 = uicontrol('Parent',MainListboxPanel_4,'Units',...
    'characters','Callback',@MainRefSelectButtonCallback4,'Enable',...
    'off','Position',[1.85 0.25 23.3 1.5],'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 for signal 1
MainSignalInfoTitleText1 = uicontrol('Parent',MainSignalInfoPanel_1,'Units',...
    'normalized','HorizontalAlignment','left','Position',...
    [0.05 0.04 0.45 0.92],'String',MainSignalInfoText,'Style','text');

% Setting the signal information section labels for signal 2
MainSignalInfoTitleText2 = uicontrol('Parent',MainSignalInfoPanel_2,'Units',...
    'normalized','HorizontalAlignment','left','Position',...
    [0.05 0.04 0.45 0.92],'String',MainSignalInfoText,'Style','text');

% Setting the signal information section labels for signal 3
MainSignalInfoTitleText3 = uicontrol('Parent',MainSignalInfoPanel_3,'Units',...
    'normalized','HorizontalAlignment','left','Position',...
    [0.04 0.04 0.45 0.92],'String',MainSignalInfoText,'Style','text');

% Setting the signal information section labels for signal 4
MainSignalInfoTitleText4 = uicontrol('Parent',MainSignalInfoPanel_4,'Units',...
    'normalized','HorizontalAlignment','left','Position',...
    [0.05 0.04 0.45 0.92],'String',MainSignalInfoText,'Style','text');

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

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


% Setting the segmentation 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',[17 1.5 11 1],'String',VoltageName,'Style',...
    'popupmenu','Value',VoltageSelNum);


% Manual segmentation 'OK' button
MainSegTextButton = uicontrol('Parent',MainSignalSegmentationPanel,'Units',...
    'characters','Position',[1.85 0.75 23.3 1.5],'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.5 0.5 32.5 11.5],'SelectionChangeFcn',...
                @DetectionSelectionChangeFn,'SelectedObject',[], 'Visible', 'off');

%Detection Algorithm buttons
FreqDetectButton = uicontrol(DetectionAlgBtnGroup,...
                'Units','characters','String','Frequency',...
                'Position',[1 11 32 2],'Style','togglebutton',...
                'TooltipString','Seizure Detection based on Segments Frequency components');
            
MeanAvDetectButton = uicontrol(DetectionAlgBtnGroup,...
                'Units','characters','String','Mean Average',...
                'Position',[1  7 32 2],'Style','togglebutton','TooltipString',...
                'Seizure Detection based on Segments Averaged Mean Amplitude');
            
CrossCorDetectButton = uicontrol(DetectionAlgBtnGroup,...
                'Units','characters','String','CrossCorrelation',...
                'Position',[1 1 32 2],'Style','togglebutton','TooltipString',...
                'Seizure Detection based on Template selected in the new window');



% 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(MainRefSelectListBox1,'BackgroundColor','w','Enable','on')
    set(MainRefSelectButton1,'Enable','on')
    set(MainRefSelectListBox2,'BackgroundColor','w','Enable','on')
    set(MainRefSelectButton2,'Enable','on')
    set(MainRefSelectListBox3,'BackgroundColor','w','Enable','on')
    set(MainRefSelectButton3,'Enable','on')
    set(MainRefSelectListBox4,'BackgroundColor','w','Enable','on')
    set(MainRefSelectButton4,'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(MainRefSelectListBox1,'BackgroundColor','w',...
                'Enable','on');
            set(MainRefSelectButton1,'Enable','on');
            set(MainRefSelectListBox2,'BackgroundColor','w',...
                'Enable','on');
            set(MainRefSelectButton2,'Enable','on')
            set(MainRefSelectListBox3,'BackgroundColor','w',...
                'Enable','on');
            set(MainRefSelectButton3,'Enable','on')
            set(MainRefSelectListBox4,'BackgroundColor','w',...
                'Enable','on');
            set(MainRefSelectButton4,'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 channel selection list boxes to display the
        % base workspace variable strings
        set(MainRefSelectListBox1,'String',variables);
        set(MainRefSelectListBox2,'String',variables);
        set(MainRefSelectListBox3,'String',variables);
        set(MainRefSelectListBox4,'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)
        
        % 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 MainRefSelectButtonCallback1(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)
        
    
    
    % Load the variable strings from the base workspace
        variables = evalin('base','who');
        
        % Select the reference channel from these variable strings
        reference_channel1 = variables{get(MainRefSelectListBox1,'Value')};
        uicontrol(hObject); 
        
       % Clear the segment plot axes and update the reference channel plot
%         cla(MainSegmentPlotAxes,'reset');

        
        
        MainChannelPlot1();         
end

function MainRefSelectButtonCallback2(hObject,eventdata)
    
        
    
    
    % Load the variable strings from the base workspace
        variables = evalin('base','who');
        
        % Select the reference channel from these variable strings
        reference_channel2 = variables{get(MainRefSelectListBox2,'Value')};
        uicontrol(hObject); 
        
       % Clear the segment plot axes and update the reference channel plot
%         cla(MainSegmentPlotAxes,'reset');

        
        
        MainChannelPlot2();         
end

function MainRefSelectButtonCallback3(hObject,eventdata)
    
         
    
    
    % Load the variable strings from the base workspace
        variables = evalin('base','who');
        
        % Select the reference channel from these variable strings
        reference_channel3 = variables{get(MainRefSelectListBox3,'Value')};
        uicontrol(hObject); 
        
       % Clear the segment plot axes and update the reference channel plot
%         cla(MainSegmentPlotAxes,'reset');

        
        
        MainChannelPlot3();         
end

function MainRefSelectButtonCallback4(hObject,eventdata)
    
          
    
    
    % Load the variable strings from the base workspace
        variables = evalin('base','who');
        
        % Select the reference channel from these variable strings
        reference_channel4 = variables{get(MainRefSelectListBox4,'Value')};
        uicontrol(hObject); 
        
       % Clear the segment plot axes and update the reference channel plot
%         cla(MainSegmentPlotAxes,'reset');

        
        
        MainChannelPlot4();         
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');
            
            % Update the signal information units
            SigInfoSet1();
            SigInfoSet2();
            SigInfoSet3();
            SigInfoSet4();
            
            SegInfoSet();
            
            % Change the y-labels of the plot axes
            ylabel(MainChannelPlotAxes1,['LFP amplitude (mV)',VoltageScale{...
                VoltageValue}]);
             ylabel(MainChannelPlotAxes2,['LFP amplitude (mV)',VoltageScale{...
                VoltageValue}]);
             ylabel(MainChannelPlotAxes3,['LFP amplitude (mV)',VoltageScale{...
                VoltageValue}]);
             ylabel(MainChannelPlotAxes4,['LFP amplitude (mV)',VoltageScale{...
                VoltageValue}]);
            
           
        end
end

 
      
function KAInjectionTextButtonCallback(hObject,evendata,handles)
    
      
    % Check there is a valid number for the KA injction 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 MainChannelPlot1
        
        % 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_channel1))/...
                sample_rate;
                     
            % Calculates the reference channel signal time scale
            channel_time = 0:1/sample_rate:channel_length-1/sample_rate;
            
            positive_limit = channel_time + 10;
            negative_limit = -10;
                      
            %  updates the signal information
            SigInfoSet1(); 
               
            % Plot the reference channel signal in the channel plot axes
            plot(MainChannelPlotAxes1,channel_time,evalin('base',...
                reference_channel1),'b');    
            grid(MainChannelPlotAxes1);
            xlabel(MainChannelPlotAxes1,'Time (s)');
            ylabel(MainChannelPlotAxes1,['LFP amplitude (',...
                VoltageScale{VoltageValue} ')']);
            title(MainChannelPlotAxes1,['Channel ',...
                reference_channel1]);
            set(gca,'YTick',[]);
            %set(MainChannelPlotAxes, 'xlim', [-100 1300]);
            
            
            
            seg_begin = channel_time(1);
            seg_end = channel_time(end);

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

function MainChannelPlot2
        
        % 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_channel2))/...
                sample_rate;
                     
            % Calculates the reference channel signal time scale
            channel_time = 0:1/sample_rate:channel_length-1/sample_rate;
            
            positive_limit = channel_time + 10;
            negative_limit = -10;
                      
            %  updates the signal information
            SigInfoSet2(); 

            
            % Plot the reference channel signal in the channel plot axes
            plot(MainChannelPlotAxes2,channel_time,evalin('base',...
                reference_channel2),'k');    
            grid(MainChannelPlotAxes2);
            xlabel(MainChannelPlotAxes2,'Time (s)');
            ylabel(MainChannelPlotAxes2,['LFP amplitude (',...
                VoltageScale{VoltageValue} ')']);
            title(MainChannelPlotAxes2,['Channel ',...
                reference_channel2]);
            %set(MainChannelPlotAxes, 'xlim', [-100 1300]);
        
            
        end
end


function MainChannelPlot3
        
        % 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_channel3))/...
                sample_rate;
                     
            % Calculates the reference channel signal time scale
            channel_time = 0:1/sample_rate:channel_length-1/sample_rate;
            
            positive_limit = channel_time + 10;
            negative_limit = -10;
                      
            %  updates the signal information
            SigInfoSet3(); 
               
            % Plot the reference channel signal in the channel plot axes
            plot(MainChannelPlotAxes3,channel_time,evalin('base',...
                reference_channel3),'c');    
            grid(MainChannelPlotAxes3);
            xlabel(MainChannelPlotAxes3,'Time (s)');
            ylabel(MainChannelPlotAxes3,['LFP amplitude (',...
                VoltageScale{VoltageValue} ')']);
            title(MainChannelPlotAxes3,['Channel ',...
                reference_channel3]);
            %set(MainChannelPlotAxes, 'xlim', [-100 1300]);
             
        end
end

function MainChannelPlot4
        
        % 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_channel4))/...
                sample_rate;
                     
            % Calculates the reference channel signal time scale
            channel_time = 0:1/sample_rate:channel_length-1/sample_rate;
            
            positive_limit = channel_time + 10;
            negative_limit = -10;
                      
            %  updates the signal information
            SigInfoSet4(); SegPanelSet();
               
            % Plot the reference channel signal in the channel plot axes
            plot(MainChannelPlotAxes4,channel_time,evalin('base',...
                reference_channel4),'k');    
            grid(MainChannelPlotAxes4);
            xlabel(MainChannelPlotAxes4,'Time (s)');
            ylabel(MainChannelPlotAxes4,['LFP amplitude (',...
                VoltageScale{VoltageValue} ')']);
            title(MainChannelPlotAxes4,['Channel ',...
                reference_channel4]);
            %set(MainChannelPlotAxes, 'xlim', [-100 1300]);
             
        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
        
                cla(MainChannelPlotAxes1,'reset');
                cla(MainChannelPlotAxes2,'reset');
                cla(MainChannelPlotAxes3,'reset');
                cla(MainChannelPlotAxes4,'reset');
            
                % Locates the indices of the segment within the channel1
                
                segment_indices = [t1*sample_rate+1, t2*sample_rate+1];

                % Extracts the segment from the channel signal1
                segment_signal1 = evalin('base',sprintf('%s(%d:%d)',...
                reference_channel1,segment_indices(1),segment_indices(...
                2))); 
            
                % Extracts the segment from the channel signal2
                segment_signal2 = evalin('base',sprintf('%s(%d:%d)',...
                reference_channel2,segment_indices(1),segment_indices(...
                2)));
            
                % Extracts the segment from the channel signal3
                segment_signal3 = evalin('base',sprintf('%s(%d:%d)',...
                reference_channel3,segment_indices(1),segment_indices(...
                2)));
            
                % Extracts the segment from the channel signal4
                segment_signal4 = evalin('base',sprintf('%s(%d:%d)',...
                reference_channel4,segment_indices(1),segment_indices(...
                2)));
            
                % Determines the length and time scale of the segment
                % signals
                segment_length = length(segment_signal1);
                segment_time = t1:1/sample_rate:t2;

                % Plot the segment signal in  plot axes 1
                MainSegPlot1(segment_time,segment_signal1);
                
                % Plot the segment signal in  plot axes 2
                MainSegPlot2(segment_time,segment_signal2);
                
                % Plot the segment signal in  plot axes 3
                MainSegPlot3(segment_time,segment_signal3);
                
                % Plot the segment signal in  plot axes 4
                MainSegPlot4(segment_time,segment_signal4);


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


function SigInfoSet1
        
           
    
%         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(MainChannelInfoVarText1,'String',{[num2str(channel_time(...
                1)),'s'],[num2str(channel_time(end)),'s'],...
                [num2str(min(min(evalin('base',reference_channel1)))),...
                VoltageScale{VoltageValue}],[num2str(max(max(evalin('base',...
                reference_channel1)))),VoltageScale{VoltageValue}],[num2str(channel_length*...
                sample_rate),' points']});
end

function SigInfoSet2
            
            set(MainChannelInfoVarText2,'String',{[num2str(channel_time(...
                1)),'s'],[num2str(channel_time(end)),'s'],...
                [num2str(min(min(evalin('base',reference_channel2)))),...
                VoltageScale{VoltageValue}],[num2str(max(max(evalin('base',...
                reference_channel2)))),VoltageScale{VoltageValue}],[num2str(channel_length*...
                sample_rate),' points']});
end

    function SigInfoSet3
            
            set(MainChannelInfoVarText3,'String',{[num2str(channel_time(...
                1)),'s'],[num2str(channel_time(end)),'s'],...
                [num2str(min(min(evalin('base',reference_channel3)))),...
                VoltageScale{VoltageValue}],[num2str(max(max(evalin('base',...
                reference_channel3)))),VoltageScale{VoltageValue}],[num2str(channel_length*...
                sample_rate),' points']});
    end

    function SigInfoSet4
            
            set(MainChannelInfoVarText4,'String',{[num2str(channel_time(...
                1)),'s'],[num2str(channel_time(end)),'s'],...
                [num2str(min(min(evalin('base',reference_channel4)))),...
                VoltageScale{VoltageValue}],[num2str(max(max(evalin('base',...
                reference_channel4)))),VoltageScale{VoltageValue}],[num2str(channel_length*...
                sample_rate),' points']});
    end

    function SegInfoSet

        
            
                % 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 1
                 segment_signal1 = evalin('base',sprintf('%s(%d:%d)',...
                 reference_channel1,segment_indices(1),segment_indices(...
                 2)));

                 % Extracts the segment signal from the channel signal 2
                 segment_signal2 = evalin('base',sprintf('%s(%d:%d)',...
                 reference_channel2,segment_indices(1),segment_indices(...
                 2)));
             
                 % Extracts the segment signal from the channel signal 3
                 segment_signal3 = evalin('base',sprintf('%s(%d:%d)',...
                 reference_channel3,segment_indices(1),segment_indices(...
                 2)));
             
                 % Extracts the segment signal from the channel signal 4
                 segment_signal4 = evalin('base',sprintf('%s(%d:%d)',...
                 reference_channel4,segment_indices(1),segment_indices(...
                 2)));
             
                 %Segment length to be displayed
                 segment_duration = segment_length*(1/sample_rate);

                 %Segments min voltage display 
                 segment1_min_voltage = min(segment_signal1);
                 segment2_min_voltage = min(segment_signal2);
                 segment3_min_voltage = min(segment_signal3);
                 segment4_min_voltage = min(segment_signal4);

                 %Segment max voltage display 
                 segment1_max_voltage = max(segment_signal1);
                 segment2_max_voltage = max(segment_signal2);
                 segment3_max_voltage = max(segment_signal3);
                 segment4_max_voltage = max(segment_signal4);
                 
            

                %Display all segmented channels info                                
            set(MainChannelInfoVarText1,'String',{[num2str(t1),'s'],...
                [num2str(t2),'s'],[num2str(segment1_min_voltage),...
                VoltageScale{VoltageValue}],[num2str(segment1_max_voltage),...
                VoltageScale{VoltageValue}],'',...
                [num2str(segment_length),'points']});
            
            set(MainChannelInfoVarText2,'String',{[num2str(t1),'s'],...
                [num2str(t2),'s'],[num2str(segment2_min_voltage),...
                VoltageScale{VoltageValue}],[num2str(segment2_max_voltage),...
                VoltageScale{VoltageValue}],...
                [num2str(segment_length),'points']});
            
            set(MainChannelInfoVarText3,'String',{[num2str(t1),'s'],...
                [num2str(t2),'s'],[num2str(segment3_min_voltage),...
                VoltageScale{VoltageValue}],[num2str(segment3_max_voltage),...
                VoltageScale{VoltageValue}],...
                [num2str(segment_length),'points']});
            
            set(MainChannelInfoVarText4,'String',{[num2str(t1),'s'],...
                [num2str(t2),'s'],[num2str(segment4_min_voltage),...
                VoltageScale{VoltageValue}],[num2str(segment4_max_voltage),...
                VoltageScale{VoltageValue}],...
                [num2str(segment_length),'points']});
            
        
    end



    function MainSegPlot1(segment_time,segment_signal1)
        
             
        % Obtains the selected voltage scale
        VoltageValue = get(MainVoltageScaleDrop,'Value');
        
        % Plots the segment signal to the segment plot axes
        plot(MainChannelPlotAxes1,segment_time,segment_signal1,'b');
        grid(MainChannelPlotAxes1)
        xlabel(MainChannelPlotAxes1,'Time (s)')
        ylabel(MainChannelPlotAxes1,['LFP amplitude (',...
            VoltageScale{VoltageValue} ')'])
        title(MainChannelPlotAxes1,['Plot 1: ',' Selected Epoch (',num2str(t1,...
            '%.0f'),'s - ',num2str(t2,'%.0f'),'s) ',reference_channel1])
        
    end

function MainSegPlot2(segment_time,segment_signal2)
        
             
        % Obtains the selected voltage scale
        VoltageValue = get(MainVoltageScaleDrop,'Value');
        
        % Plots the segment signal to the segment plot axes
        plot(MainChannelPlotAxes2,segment_time,segment_signal2,'k');
        grid(MainChannelPlotAxes2)
        xlabel(MainChannelPlotAxes2,'Time (s)')
        ylabel(MainChannelPlotAxes2,['LFP amplitude (',...
            VoltageScale{VoltageValue} ')'])
        title(MainChannelPlotAxes2,['Plot  2: ',' Selected Epoch (',num2str(t1,...
            '%.0f'),'s - ',num2str(t2,'%.0f'),'s) ',reference_channel2])
        
end

function MainSegPlot3(segment_time,segment_signal3)
        
             
        % Obtains the selected voltage scale
        VoltageValue = get(MainVoltageScaleDrop,'Value');
        
        % Plots the segment signal to the segment plot axes
        plot(MainChannelPlotAxes3,segment_time,segment_signal3,'c');
        grid(MainChannelPlotAxes3)
        xlabel(MainChannelPlotAxes3,'Time (s)')
        ylabel(MainChannelPlotAxes3,['LFP amplitude (',...
            VoltageScale{VoltageValue} ')'])
        title(MainChannelPlotAxes3,['Plot 3: ',' Selected Epoch (',num2str(t1,...
            '%.0f'),'s - ',num2str(t2,'%.0f'),'s) ',reference_channel3])
        
end

function MainSegPlot4(segment_time,segment_signal4)
        
             
        % Obtains the selected voltage scale
        VoltageValue = get(MainVoltageScaleDrop,'Value');
        
        % Plots the segment signal to the segment plot axes
        plot(MainChannelPlotAxes4,segment_time,segment_signal4,'k');
        grid(MainChannelPlotAxes4)
        xlabel(MainChannelPlotAxes4,'Time (s)')
        ylabel(MainChannelPlotAxes4,['LFP amplitude (',...
            VoltageScale{VoltageValue} ')'])
        title(MainChannelPlotAxes4,['Plot 4: ',' Selected Epoch (',num2str(t1,...
            '%.0f'),'s - ',num2str(t2,'%.0f'),'s) ',reference_channel4])
        
    end

%Callback routine executed when the selected detection toggle button
%changes.
%  function DetectionSelectionChangeFn(DetectionAlgBtnGroup,eventdata)
%     end 
  end
 