function varargout = Front_Panel(varargin)                                
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
%     G U I   H E L P   I N F O R M A T I O N                                   % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
%  Front_Panel M-file  for Front_Panel.fig                                  % 
%       This GUI is part of the LFP analysis suite 2006                         % 
%       The GUI is designed as a Preview of more advanced analysis techniques   % 
%       select your data from the workspace then click Update                   % 
%                                                                               % 
%       Once your data has been read in you can select one of the analysis      % 
%       options from the drop down menu                                         % 
%                                                                               % 
%       Often, certain frequency bands can be analysed individually. These can  % 
%        be selected using the radio buttons above the dropdown menu.           % 
%                                                                               % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %                                         % 
%  See also: GUIDE, GUIDATA, GUIHANDLES                                         % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
%                                                                               % 
%  This Software is distributed under the GNU General Public Liscence           % 
%  a copy of this liscence sould be accompany this software.                    % 
%                                                                               % 
% Copyright (C) 2006  Greg Aldam and Richard Peter                              %
%                                                                               %  
% This program is free software; you can redistribute it and/or modify          %
% it under the terms of the GNU General Public License as published by          %
% the Free Software Foundation; either version 2 of the License, or             %
% (at your option) any later version.                                           %
%                                                                               % 
% This program is distributed in the hope that it will be useful,               %
% but WITHOUT ANY WARRANTY; without even the implied warranty of                %
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                 %
% GNU General Public License for more details.                                  %
%                                                                               %  
% You should have received a copy of the GNU General Public License             %
% along with this program; if not, write to the Free Software                   %
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA %
%                                                                               % 
%                                                                               % 
%  For further information contact Richard Peter at                             % 
%  infinitybeckon@hotmail.com                                                   %
%  or Greg Aldam at                                                             %
%  greg_aldam@hotmail.com                                                       %
%                                                                               %   
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 


% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Front_Panel_OpeningFcn, ...
                   'gui_OutputFcn',  @Front_Panel_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...    
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
                              

% --- Executes just before Front_Panel is made visible.
    function Front_Panel_OpeningFcn(hObject, eventdata, handles, varargin)
        % This function has no output args, see OutputFcn.
        % hObject    handle to figure
        % eventdata  reserved - to be defined in a future version of MATLAB
        % handles    structure with handles and user data (see GUIDATA)
        % varargin   command line arguments to Front_Panel (see VARARGIN)

        % Choose default command line output for Front_Panel
        handles.output = hObject;

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
%   Here we initialise the GUI before the USER has any Input                    % 
%                                                                               % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %     
        %Clear the plots
        cla(handles.Userdata_plot);
        cla(handles.Userselection_plot);
        cla(handles.Userselection_PowSpec);
        
        %Populate the listbox with workspace data
        update_dropdown(handles);
        handles.numfigs=0;      % a variable to allow many new window handles
        handles.tstep = 1000;   %defines number of samples per real time second
        

        % Set text boxes to default values
        set(handles.user_start, 'String', num2str(0));
        set(handles.user_end, 'String', num2str(0));
        %Define an empty array for userdata
        handles.userdata = [];
        %Set the power spectrum frquency limits
        set(handles.PowMax, 'String','170');
        set(handles.PowMin, 'String','0');

       
        %Relinquish the user's ability to zoom out or scroll around
        set(handles.ZoomSlider, 'Enable', 'off');
        set(handles.Zoom_out, 'Enable', 'off');
        
        %Update the handles structure
        guidata(hObject,handles);


% End of initialisation code

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
%   End of Front_Panel_OpeningFcn initialisation                                % 
%                                                                               %  
%   We now present an overview of the callback functions within the             % 
%   GUI in the order they appear:                                               % 
%                                                                               % 
%   Front_Panel_OutputFcn               This is a starndard function of all     % 
%                                       GUIs it has no purpose in this GUI.     %
%   fb_Analysis_Callback                This does nothing: (it is the listbox)  % 
%                                                                               %  
%   fba_delta_Callback                  These callbacks do not have a purpose   % 
%   fba_theta_Callback                  within this GUI as their value is only  % 
%   fba_alpha_Callback                   required by fba_button_Callback        % 
%   fba_beta_Callback                                                           % 
%   fba_gamma_low_Callback                                                      %  
%   fba_gamma_mid_Callback                                                      %  
%   fba_gamma_high_Callback                                                     %  
%   fba_all_Callback                    Selects/Deselects all frequency bands   %  
%   fba_button_Callback                 This Button calls up a preview of the   % 
%                                       Analysis selected in the dropdown menu  % 
%   user_start_Callback                 This calls the update all plots fcn.    % 
%   user_end_Callback                   This calls the update all plots fcn.    % 
%   clear_user_selection_Callback       This calls the clear_user_selection fcn.% 
%   further_analysis_Callback           WHAT DOES THIS DO?                      % 
%   adddata_Callback                    This updates the User's data            % 
%   ZoomSlider_Callback                 This adjusts the plots as the user      % 
%                                       changes the slider                      % 
%   Zoom_out_Callback                   Zooms out of the user Data plot         % 
%   Zoom_in_Callback                    Zooms into the user data plot           % 
%   PowMin_Callback                     Adjusts the axes on the PSD plot        % 
%   PowMax_Callback                     Adjusts the axes on the PSD plot        % 
%   AdvancedScreenPopup_Callback        Does nothing (is a popup menu)          %
%   AdvancedAnalysisBtn_Callback        Opens Advanced analysis Window          %
%   Fs_Callback                         Changes the smapling freq. and plots    %
%                                                                               %
%   update_all_plots                    Updates all plots in the figure         % 
%   update_dropdown                     Updates the variables in the Workspace  % 
%   get_var_names                       Gets the variable selected in Listbox   % 
%                                                                               % 
%                                                                               % 
%                                                                               % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 


% --- Outputs from this function are returned to the command line.
function varargout = Front_Panel_OutputFcn(hObject, eventdata, handles) 
% Get default command line output from handles structure
varargout{1} = handles.output;





% --- Executes on selection change in fb_Analysis data.
    function fb_Analysis_Callback(hObject, eventdata, handles)
% --- Executes during object creation, after setting all properties.
function fb_Analysis_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
%  Here are the function calls for the frequency band radio buttons.              % 
%  Nothing happens here because the GUI only does some thing when                 % 
%  the 'fba_button' button is pressed                                             % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %

% --- Executes on button press in fba_delta.
function fba_delta_Callback(hObject, eventdata, handles)
% --- Executes on button press in fba_theta.
function fba_theta_Callback(hObject, eventdata, handles)
    
% --- Executes on button press in fba_alpha.
function fba_alpha_Callback(hObject, eventdata, handles)

% --- Executes on button press in fba_beta.
function fba_beta_Callback(hObject, eventdata, handles)

% --- Executes on button press in fba_gamma_low.
function fba_gamma_low_Callback(hObject, eventdata, handles)

% --- Executes on button press in fba_gamma_mid.
function fba_gamma_mid_Callback(hObject, eventdata, handles)

% --- Executes on button press in fba_gamma_high.
function fba_gamma_high_Callback(hObject, eventdata, handles)
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % /
% End of frequency band radio buttons                                            %  
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % /    
    

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % /    
% Executes on checkbox press fba_all. This selects/deselects all frequency bands %  
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % /
    function fba_all_Callback(hObject, eventdata, handles)
        % hObject    handle to fba_all (see GCBO)
        % eventdata  reserved - to be defined in a future version of MATLAB
        % handles    structure with handles and user data (see GUIDATA)

        % Hint: get(hObject,'Value') returns toggle state of fba_all
        if (get(hObject,'Value') == get(hObject,'Max'))
            % then checkbox is checked-take approriate action
       
            set(handles.fba_delta,'Value',1);
            set(handles.fba_theta,'Value',1);
            set(handles.fba_alpha,'Value',1);
            set(handles.fba_beta,'Value',1);
            set(handles.fba_gamma_low,'Value',1);
            set(handles.fba_gamma_mid,'Value',1);
            set(handles.fba_gamma_high,'Value',1);
            
        else
            % checkbox is not checked-take approriate action
            set(handles.fba_delta,'Value',0);
            set(handles.fba_theta,'Value',0);
            set(handles.fba_alpha,'Value',0);
            set(handles.fba_beta,'Value',0);
            set(handles.fba_gamma_low,'Value',0);
            set(handles.fba_gamma_mid,'Value',0);
            set(handles.fba_gamma_high,'Value',0);
        end %End If
   % end %EoF

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
%   This is fba_button_Callback. When a User clicks this button, the GUI        % 
%   performs the option selected in the dropdown menu. the handle for the       % 
%   dropdown menu is further_analysis                                           % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
function fba_button_Callback(hObject, eventdata, handles)
% hObject    handle to fba_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


if(get(handles.further_analysis, 'Value') == 1)

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
%  the user wants to see some (!!separate!!) signals, so lets do it             %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %

    m=0; % a counter for the number of bands required
    if(get(handles.fba_delta, 'Value')==1)
        m = m+1;            % Increment the count
        flolim = 1;         % Define the limits
        fhilim = 4;
        %Next define the filter coefficients
        [b, a] = butter(2, [flolim/499, fhilim/499]);
        % We then add the filtered data to the 'm'th row of an array 
        % to be plotted at the end...
        handles.plotme(m, :) = filter(b, a, handles.userdata(str2num(...
            get(handles.user_start, 'String'))*handles.tstep+1:str2num(...
            get(handles.user_end, 'String'))*handles.tstep))
        %Store the limits and a label for the graph. 
        flims(m, :)=[flolim fhilim];    
        labs(m,1:11) = '\delta     ';   % This is  padded so that all labels
                                        % are the same length
    end
    
   %All other bands are abtaied in the same way
    if(get(handles.fba_theta, 'Value')==1)
        m = m+1;
        flolim = 4;
        fhilim = 8;
        [b, a] = butter(2, [flolim/499, fhilim/499]);
        handles.plotme(m, :) = filter(b, a, handles.userdata(str2num(...
            get(handles.user_start, 'String'))*handles.tstep+1:str2num(...
            get(handles.user_end, 'String'))*handles.tstep));
        flims(m, :)=[flolim fhilim];
        labs(m,1:11) = '\theta     ';
    end
    if(get(handles.fba_alpha, 'Value')==1)
        m = m+1;
        flolim = 8;
        fhilim = 14;
        [b, a] = butter(2, [flolim/499, fhilim/499]);
        handles.plotme(m, :) = filter(b, a, handles.userdata(str2num(...
            get(handles.user_start, 'String'))*handles.tstep+1:str2num(...
            get(handles.user_end, 'String'))*handles.tstep));
        flims(m, :)=[flolim fhilim];
        labs(m,1:11) = '\alpha     ';
    end
    if(get(handles.fba_beta, 'Value')==1)
        m = m+1;
        flolim = 14;
        fhilim = 30;
        [b, a] = butter(2, [flolim/499, fhilim/499]);
        handles.plotme(m, :) = filter(b, a, handles.userdata(str2num(...
            get(handles.user_start, 'String'))*handles.tstep+1:str2num(...
            get(handles.user_end, 'String'))*handles.tstep));
        flims(m, :)=[flolim fhilim];
        labs(m,1:11) = '\beta      ';
    end
    if(get(handles.fba_gamma_low, 'Value')==1)
        m = m+1;
        flolim = 30;
        fhilim = 50;
        [b, a] = butter(2, [flolim/499, fhilim/499]);
        handles.plotme(m, :) = filter(b, a, handles.userdata(str2num(...
            get(handles.user_start, 'String'))*handles.tstep+1:str2num(...
            get(handles.user_end, 'String'))*handles.tstep));
        flims(m, :)=[flolim fhilim];
        labs(m,1:11) = '\gamma low ';
    end
    if(get(handles.fba_gamma_mid, 'Value')==1)
        m = m+1;
        flolim = 50;
        fhilim = 100;
        [b, a] = butter(2, [flolim/499, fhilim/499]);
        handles.plotme(m, :) = filter(b, a, handles.userdata(str2num(...
            get(handles.user_start, 'String'))*handles.tstep+1:str2num(...
            get(handles.user_end, 'String'))*handles.tstep));
        flims(m, :)=[flolim fhilim];
        labs(m,1:11) = '\gamma mid ';
    end
    if(get(handles.fba_gamma_high, 'Value')==1)
        m = m+1;
        flolim = 100;
        fhilim = 150;
        [b, a] = butter(2, [flolim/499, fhilim/499]);
        handles.plotme(m, :) = filter(b, a, handles.userdata(str2num(...
            get(handles.user_start, 'String'))*handles.tstep+1:str2num(...
            get(handles.user_end, 'String'))*handles.tstep));
        flims(m, :)=[flolim fhilim];
        labs(m,1:11) = '\gamma high';
    end


    %now the plotting bit
    
    fighandle = figure(handles.numfigs+1);  %Generate a new figure
    handles.numfigs=handles.numfigs+1;      %Increment the number of figure
    h = newplot(fighandle);                 %Get a handle for the plot
    for t = 1:1:m
        subplot(m,1,t);                     %plot each band selected
        plot(handles.plotme(t, :));         
        %Label each plot
        title(['Filtered signal ',labs(t,:),'    ',...
            num2str(flims(t,1)),'-',num2str(flims(t,2)),'Hz'])
        xlabel('Time (s)'); ylabel('Voltage (mV)');
    end
    

elseif(get(handles.further_analysis, 'Value') == 2)
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% The user wants a time PSD                                               % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 

    %The PSD vs. time is calculated here in the same way as the advanced
    %version. The signal is windowed, and the FFT of this windowed signal
    %taken. if the window does not fit an exact number of times the end of
    %the data is discarded.
    %The FFTs are all stored in the columns of the variable STFT.
    %This is then multiplied by its complex conjugate and the duplicate
    %data above the nyquist frequency is discarded. 
    hannwidth = 3;      
    STFTstep = 0.5*1000;                %the step size in datapoints = half a second
    hannN = hannwidth*handles.tstep;    %defines number of points for construction Hanning window
    win = hann(hannN);                  %defines a hannN-point Hanning window
    FFTorder = 2^nextpow2(hannN);       %the order of the fft 

    % Next get the number of samples in the user's selection
    tN = (str2num(get(handles.user_end, 'String'))-...
        str2num(get(handles.user_start, 'String')))*handles.tstep;

    %if the length of the data is shorter than the windowtell the user
    if floor((tN-hannN)/STFTstep) < 2
        errordlg('Selection must be longer than 3 seconds',...
            'Incorrect Selection','modal')
    else
        for pp = 1:floor((tN-hannN)/STFTstep)
            %Multiplication of window with signal
            windowedSIG = handles.userdata((pp-1)*(STFTstep)+1:...
                (pp-1)*(STFTstep)+hannN).*win;
            %Now store the FFt of this windowed signal in the pp(th)
            % COLUMN of STFT
            STFT(:,pp) = fft(windowedSIG,FFTorder);                                                %calculates hannN-point fft
        end
        %We only want the upper half of teh columns since the FFT
        %will be a mirror image about the nyquist frequency
        myPSD = STFT(1:hannN/2,:).*conj(STFT(1:hannN/2,:)); %Defines spectrogram surface

        %Next we break up myPSD into the frequency bands that the user has
        %selected. this is done in a similar manner to the previous
        %function, however the average of the corresponding ROWS of myPSD
        %must be calculated
        
        m=0;            %Set the counter variable to 0
        % the user wants to see some (!!separate!!) signals, so lets do it
        if(get(handles.fba_delta, 'Value')==1)
            m = m+1;    %Increment the counter variable
            flolim = 1; %Define the frequency band limits
            fhilim = 4;
            %Next scale these so that we select the correct parts of myPSD
            scal_flolim = round(flolim*(FFTorder/handles.Fs));
            scal_fhilim = round(fhilim*(FFTorder/handles.Fs));
            %Next Sum the power in this band and store in the columns of
            %bandPSD
            bandPSD(m, :) = sum(myPSD(scal_flolim:scal_fhilim,:),1);
            %Next store the frequency limits and labels
            flims(m, :)=[flolim fhilim];
            labs(m,1:11) = '\delta     ';
        end
        %The remaining bands are all calculated in a similar way
        if(get(handles.fba_theta, 'Value')==1)
            m = m+1;
            flolim = 4;
            fhilim = 8;
            scal_flolim = round(flolim*(FFTorder/handles.Fs));
            scal_fhilim = round(fhilim*(FFTorder/handles.Fs));
            bandPSD(m, :) = sum(myPSD(scal_flolim:scal_fhilim,:),1);
            flims(m, :)=[flolim fhilim];
            labs(m,1:11) = '\theta     ';
        end
        if(get(handles.fba_alpha, 'Value')==1)
            m = m+1;
            flolim = 8;
            fhilim = 14;
            scal_flolim = round(flolim*(FFTorder/handles.Fs));
            scal_fhilim = round(fhilim*(FFTorder/handles.Fs));
            bandPSD(m, :) = sum(myPSD(scal_flolim:scal_fhilim,:),1);
            flims(m, :)=[flolim fhilim];
            labs(m,1:11) = '\alpha     ';
        end
        if(get(handles.fba_beta, 'Value')==1)
            m = m+1;
            flolim = 14;
            fhilim = 30;
            scal_flolim = round(flolim*(FFTorder/handles.Fs));
            scal_fhilim = round(fhilim*(FFTorder/handles.Fs));
            bandPSD(m, :) = sum(myPSD(scal_flolim:scal_fhilim,:),1);
            flims(m, :)=[flolim fhilim];
            labs(m,1:11) = '\beta      ';
        end
        if(get(handles.fba_gamma_low, 'Value')==1)
            m = m+1;
            flolim = 30;
            fhilim = 50;
            scal_flolim = round(flolim*(FFTorder/handles.Fs));
            scal_fhilim = round(fhilim*(FFTorder/handles.Fs));
            bandPSD(m, :) = sum(myPSD(scal_flolim:scal_fhilim,:),1);
            flims(m, :)=[flolim fhilim];
            labs(m,1:11) = '\gamma low ';
        end
        if(get(handles.fba_gamma_mid, 'Value')==1)
            m = m+1;
            flolim = 50;
            fhilim = 100;
            scal_flolim = round(flolim*(FFTorder/handles.Fs));
            scal_fhilim = round(fhilim*(FFTorder/handles.Fs));
            bandPSD(m, :) = sum(myPSD(scal_flolim:scal_fhilim,:),1);
            flims(m, :)=[flolim fhilim];
            labs(m,1:11) = '\gamma mid ';
        end
        if(get(handles.fba_gamma_high, 'Value')==1)
            m = m+1;
            flolim = 100;
            fhilim = 150;
            scal_flolim = round(flolim*(FFTorder/handles.Fs));
            scal_fhilim = round(fhilim*(FFTorder/handles.Fs));
            bandPSD(m, :) = sum(myPSD(scal_flolim:scal_fhilim,:),1);
            flims(m, :)=[flolim fhilim];
            labs(m,1:11) = '\gamma high';
        end
        %Next plot the data stored in the columns of  myPSD
        %First define the x-axis
        x = linspace(str2num(get(handles.user_start, 'String')),...
            str2num(get(handles.user_end, 'String')),...
            floor((tN -hannN)/STFTstep));
        %then create a new figure and increment the counter
        fighandle = figure (handles.numfigs+1);
        handles.numfigs=handles.numfigs+1;
        %Create a new plot in this figure
        h = newplot(fighandle);         
        % Finally plot the data and add titles and labels
        for t = 1:m
            subplot(m,1,t); plot(x, bandPSD(t, :));
            title(['Frequency band ',labs(t,:),'    ',num2str(flims(t,1)),'-',num2str(flims(t,2)),'Hz'])
            xlabel('Time (s)'); ylabel('Power (au)');
        end
    end
end
%Update the handles structure
guidata(hObject,handles);
%End Of Function


% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% Executes when the user modifies the start sample time            % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function user_start_Callback(hObject, eventdata, handles)
update_all_plots(handles);
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function user_start_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end


% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% Executes when the user modifies the sample end time             % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function user_end_Callback(hObject, eventdata, handles)
%Adjust the user selection plot and save the handles structure
update_all_plots(handles);
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function user_end_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% Executes when the user clears their selection                   % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function clear_user_selection_Callback(hObject, eventdata, handles)
%This function clears the user selection 
    if(get(handles.clear_user_selection, 'Value')==1) %%if its checked
        set(handles.user_start, 'String', num2str(0));
        set(handles.user_end, 'String', num2str((length(handles.userdata)-1)/handles.tstep));
        set(handles.user_end, 'Enable', 'off')
        set(handles.user_start, 'Enable', 'off')
    else
        set(handles.user_end, 'Enable', 'on')
        set(handles.user_start, 'Enable', 'on')
    end
    update_all_plots(handles);
%save the handles structure
guidata(hObject,handles);

%End of Function

% --- Executes on selection change in further_analysis.
function further_analysis_Callback(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function further_analysis_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
%  Executes on button press in adddata. Here we update the variable % 
%  handles.userdata which is an mx1 array. Then update all plots    % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
function adddata_Callback(hObject, eventdata, handles)
%Get the selected variable name
userdata = get_var_names(handles);
%assign the selected data to handles.userdata
handles.userdata = evalin('base', userdata);

%Define the x-axis for this variable remembering that the time convention
%states that a 10 ms signal has 11 dataponits if the sampling frequency is
%1000 Hz. This is why a '-1' is required in the 
% (length(handles.userdata)-1) bit.
handles.t = linspace(0,(length(handles.userdata)-1)/handles.tstep,...
    length(handles.userdata));
%Set the user selection end time to the length of the data
set(handles.user_end, 'String', num2str((length(handles.userdata)-1)/handles.tstep));
%Plot the data and label it 
plot(handles.Userdata_plot, handles.t, handles.userdata,'b')
xlabel(handles.Userdata_plot,'Time (s)')
ylabel(handles.Userdata_plot,'Signal (mV)')
%Define handles.dx: this is the length of time (in seconds) that is visible
%on the userselection plot. It is used when the user zooms in/out.
handles.dx=(length(handles.userdata)-1)/handles.tstep; 
%Set appropriate axis limits and settings
xlim(handles.Userdata_plot, [0 handles.dx]);
set(gcf,'doublebuffer','on');
%adjust the user selection plot
update_all_plots(handles);
%update the handles structure
guidata(hObject,handles);

%End of Function




% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% Executes on slider movement.                                    % 
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function ZoomSlider_Callback(hObject, eventdata, handles)
    %This function simply updates the xlimits of the plot
set(handles.Userdata_plot, 'xlim' ,get(handles.ZoomSlider, 'Value')*...
    ((length(handles.userdata)/handles.tstep)-handles.dx)+[0 handles.dx]);

% --- Executes during object creation, after setting all properties.
function ZoomSlider_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% Executes on the user clicking Zoom Out: ' - '                    %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function Zoom_out_Callback(hObject, eventdata, handles)

%Make handles.dx twice as large
handles.dx=(handles.dx)*2;
%if this is now the length of the user's data then stop them from zooming
%out any more
if(handles.dx==(length(handles.userdata)-1)/handles.tstep)
    set(handles.ZoomSlider, 'Enable', 'off');
    set(handles.Zoom_out, 'Enable', 'off');
end

%Adjust the xlimits
set(handles.Userdata_plot, 'xlim' ,get(handles.ZoomSlider, 'Value')*...
    ((length(handles.userdata)/handles.tstep)-handles.dx)+[0 handles.dx]);
%adjust the slider step size [buttonclik percentage> <trough-click
%percentage>]
set(handles.ZoomSlider, 'SliderStep', (1/.75).*get(handles.ZoomSlider, 'SliderStep'));

%Update the handles structure
guidata(hObject, handles);

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% Executes on the user clicking Zoom in : ' + '                    %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function Zoom_in_Callback(hObject, eventdata, handles)
%Half the length of time on display
handles.dx=(handles.dx)*0.5;
%If the slider is not enabled, enable it and the zoom out button
%and set the slider to the center
if(isequal(strfind(get(handles.ZoomSlider, 'Enable'), 'on'),[])==1)
    set(handles.ZoomSlider, 'Enable', 'on');
    set(handles.ZoomSlider, 'Value', 0.5);
    set(handles.Zoom_out, 'Enable', 'on');
end

%Adjust the x limits
set(handles.Userdata_plot, 'xlim' ,get(handles.ZoomSlider, 'Value')*...
   ((length(handles.userdata)-1)/handles.tstep-handles.dx)+[0 handles.dx]);

%adjust the slider step size [<buttonclik percentage> <trough-click
%percentage>]
set(handles.ZoomSlider, 'SliderStep', 0.75.*get(handles.ZoomSlider, 'SliderStep'));

%update the handles structure
guidata(hObject, handles);
%End of function

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% Executes on the user changing the min on the Power Spectum      %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function PowMin_Callback(hObject, eventdata, handles)
    update_all_plots(handles);
%EoF
% --- Executes during object creation, after setting all properties.
function PowMin_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% Executes on the user changing the max on the Power Spectum      %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function PowMax_Callback(hObject, eventdata, handles)
    update_all_plots(handles);
%EoF

% --- Executes during object creation, after setting all properties.
function PowMax_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
%End of Function

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% This does not do anything because its value is used by the            % 
% Advanced Analysis Button                                              %  
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
function AdvancedScreenPopup_Callback(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function AdvancedScreenPopup_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% The User preses  this to move onto the next screen                    %  
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
function AdvancedAnalysisBtn_Callback(hObject, eventdata, handles)
if get(handles.AdvancedScreenPopup, 'Value')==1
        %The user wants to export point to Excel
        %First define the x-values to be plotted
        handles.xvalues = handles.t(str2num(get(handles.user_start, 'String'))...
        *handles.tstep+1:str2num(get(handles.user_end, 'String'))*...
        handles.tstep+1);
        %Now define the Data range to be plotted
        handles.yvalues = handles.userdata(str2num(get(handles.user_start, 'String'))...
        *handles.tstep+1:str2num(get(handles.user_end, 'String'))*handles.tstep+1);
        %Now send handles to plot it.
        Cursor_export(handles)

elseif get(handles.AdvancedScreenPopup, 'Value')==2
    %The user wants to enter Spectrogram Explorer
    interSPECT(handles);
    
elseif get(handles.AdvancedScreenPopup, 'Value')==3
    %The user wants to view the filtered signal
    interFilterBands([handles.userdata(...
        (str2num(get(handles.user_start, 'String')).*handles.tstep)+1: ...
        (str2num(get(handles.user_end, 'String')).*handles.tstep)+1)], ...
        [str2num(get(handles.user_start, 'String'))], ...
        [str2num(get(handles.user_end, 'String'))], [handles.tstep]);

elseif get(handles.AdvancedScreenPopup, 'Value')==4
    %The user 2 wants a PSD and Power Spectrum
    interPSD([handles.userdata(...
        (str2num(get(handles.user_start, 'String')).*handles.tstep)+1: ...
        (str2num(get(handles.user_end, 'String')).*handles.tstep)+1)], ...
        [str2num(get(handles.user_start, 'String'))], ...
        [str2num(get(handles.user_end, 'String'))], [handles.tstep]);
    
elseif get(handles.AdvancedScreenPopup, 'Value')==5
    %The user wants to view Power Spectrum vs. Time
    interPSvsTime([handles.userdata(...
        (str2num(get(handles.user_start, 'String')).*handles.tstep)+1: ...
        (str2num(get(handles.user_end, 'String')).*handles.tstep)+1)], ...
        [str2num(get(handles.user_start, 'String'))], ...
        [str2num(get(handles.user_end, 'String'))], [handles.tstep]);

end
%   EoF


% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% Executes when the user updates the sampling frequency                 %  
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function Fs_Callback(hObject, eventdata, handles)
%Set the sampling frequency (handles.tstep)
handles.tstep = str2num(get(hObject, 'String'));
%Define a new time axis
handles.t = linspace(0,(length(handles.userdata)-1)/handles.tstep,length(handles.userdata));
%Set the start and end time of the user's data
set(handles.user_start, 'String', num2str(0));
set(handles.user_end, 'String', num2str((length(handles.userdata)-1)/handles.tstep));

%Update the userdata plot and label it
plot(handles.Userdata_plot, handles.t, handles.userdata)
xlabel(handles.Userdata_plot,'Time (s)')
ylabel(handles.Userdata_plot,'Signal (mV)')
handles.dx=(length(handles.userdata)-1)/handles.tstep; %axis length in seconds
xlim(handles.Userdata_plot, [0 handles.dx]);
% This prevents the screen flickering as the user scrolls around
set(gcf,'doublebuffer','on');

set(handles.Userdata_plot, 'Color',[1 1 1],... %sets background colour to white
'XColor',[0 0 0],...        %sets x-axis to black line colour    
'YColor',[0 0 0])           %sets y-axis to black line colour 

%Update the other plots
update_all_plots(handles)

%Update the handles structure
guidata(hObject, handles);
%EoF

% --- Executes during object creation, after setting all properties.
function Fs_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
%End of Function

   
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% Updates Userselection_plot and Power Spectrum plot                  %  
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
function update_all_plots(handles)
    %First update the user selection plot
    plot(handles.Userselection_plot, handles.t(str2num(get...
        (handles.user_start, 'String'))*handles.tstep+1:...
        str2num(get(handles.user_end, 'String'))*handles.tstep+1), ...
        handles.userdata(str2num(get(handles.user_start, 'String'))*...
        handles.tstep+1:str2num(get(handles.user_end, 'String'))*...
        handles.tstep+1),'b');

    
    set(handles.Userselection_plot, 'Color',[1 1 1],... %sets background colour to white
        'XColor',[0 0 0],...        %sets x-axis to black line colour    
        'YColor',[0 0 0])           %sets y-axis to black line colour  
    %Label the plot and set the xlimit
    xlabel(handles.Userselection_plot,'Time (s)')
    ylabel(handles.Userselection_plot,'Signal (mV)')
    xlim(handles.Userselection_plot, [str2num(get(handles.user_start, 'String')) str2num(get(handles.user_end, 'String'))]);
    set(gcf,'doublebuffer','on');

    %Now adjust the power spectrum plot: First get the length of teh user's
    %selection
    user_sel_length =length(handles.userdata(round(str2num(...
        get(handles.user_start, 'String'))*handles.tstep)+1:str2num(...
        get(handles.user_end, 'String'))*handles.tstep+1));
    %define the number of fft points
    handles.N = 2^(nextpow2(user_sel_length));
    %FFT the selection
    F=fft(handles.userdata(str2num(get(handles.user_start, 'String'))*...
        handles.tstep+1:str2num(get(handles.user_end, 'String'))*...
        handles.tstep), handles.N);
    %Multiply by the complex conjugate to get the abs value squared
    handles.P=F.*conj(F);
    % Scale the fft so that it is not a function of the length of the
    % user's data. 
    handles.P = handles.P/(user_sel_length^2);
    % times by 2 because we discarded the second half, where half the
    % power was.
    handles.P = handles.P*2;
    % DC Component should be unique.
    handles.P(1) = handles.P(1)/2;
    % Nyquist component should also be unique.
    if ~rem(handles.P,2)
        % Here handles.P is even; therefore,Nyquist point is included so
        % divide it by 2 also
        handles.P(end) = handles.P(end)/2;
    end
    
    %Now define a frequency axis
    f = 1000*(0 :(handles.N)/2-1 )/(handles.N);
    %PLot the fft and label the axes
    plot(handles.Userselection_PowSpec,f, handles.P(1:floor((handles.N)/2)),'b');
    xlabel(handles.Userselection_PowSpec,'Frequency (Hz)')
    ylabel(handles.Userselection_PowSpec,'Signal (mV^2)')
    
    %Now set the limits on the axes
    xlim(handles.Userselection_PowSpec, [str2num(get(handles.PowMin, 'String')) str2num(get(handles.PowMax, 'String'))]);
    %next find the maximum value within the Power spectrum
    ymax = max(handles.P(ceil(str2num(get(handles.PowMin, 'String'))*...
        handles.N/handles.tstep+1):ceil(str2num(get(handles.PowMax, 'String'))*...
        handles.N/handles.tstep)));
    %Set the y-limit
    ylim(handles.Userselection_PowSpec, [0 ymax+ymax*0.1]);

    set(handles.Userselection_PowSpec, 'Color',[1 1 1],... %sets background colour to white
        'XColor',[0 0 0],...        %sets x-axis to black line colour    
        'YColor',[0 0 0])           %sets y-axis to black line colour 

% End of Function


% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% populate the listbox                                                  %  
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function update_dropdown(handles)
vars = evalin('base','who');
set(handles.fb_Analysis,'String',vars)
%EoF

% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % 
% get the variable selected in the listbox                              %  
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
function var1 = get_var_names(handles)
list_entries = get(handles.fb_Analysis,'String');
index_selected = get(handles.fb_Analysis,'Value');
if length(index_selected) ~= 1
    errordlg('You must select only one variable',...
            'Incorrect Selection','modal')
else
    var1 = list_entries{index_selected(1)};
end 
%EoF

%Now the Menu Functions

% --------------------------------------------------------------------
function FILE_Callback(hObject, eventdata, handles)

    

% --------------------------------------------------------------------
function FILE_Refresh_Callback(hObject, eventdata, handles)
update_dropdown(handles);
    
% --------------------------------------------------------------------
function FILE_Close_Callback(hObject, eventdata, handles)
delete(gcf)


% --------------------------------------------------------------------
function HELP_Callback(hObject, eventdata, handles)

% --------------------------------------------------------------------
function HELP_Liscence_Callback(hObject, eventdata, handles)
LiscenceInfo;

% --------------------------------------------------------------------
function HELP_About_Callback(hObject, eventdata, handles)
About;


% --------------------------------------------------------------------
function HELP_Quickstart_Callback(hObject, eventdata, handles)
Front_Panel_Quickstart




% --------------------------------------------------------------------
function File_Callback(hObject, eventdata, handles)
% hObject    handle to File (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function Close_Callback(hObject, eventdata, handles)
% hObject    handle to FILE_Close (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




