function varargout = Event_triggered(varargin)
% EVENT_TRIGGERED M-file for Event_triggered.fig
%      EVENT_TRIGGERED, by itself, creates a new EVENT_TRIGGERED or raises the existing
%      singleton*.
%
%      H = EVENT_TRIGGERED returns the handle to a new EVENT_TRIGGERED or the handle to
%      the existing singleton*.
%
%      EVENT_TRIGGERED('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in EVENT_TRIGGERED.M with the given input arguments.
%
%      EVENT_TRIGGERED('Property','Value',...) creates a new EVENT_TRIGGERED or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Event_triggered_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Event_triggered_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Event_triggered

% Last Modified by GUIDE v2.5 13-Jan-2000 09:15:59

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Event_triggered_OpeningFcn, ...
                   'gui_OutputFcn',  @Event_triggered_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 Event_triggered is made visible.
function Event_triggered_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 Event_triggered (see VARARGIN)

% Choose default command line output for Event_triggered
handles.output = hObject;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
%% E N T E R   Y O U R   S T U F F   H E R E (PRE USER STUFF)
% clc %clear the Matlab workspace so we can see errors
vars = evalin('base','who');
set(handles.eventtriggers, 'Enable', 'off');
set(handles.rawdata,'String',vars)          %populates rawdata listbox
set(handles.eventtriggers,'String',vars)
handles.userdata=0;
handles.triggers=[];
handles.avg_response = [];
handles.tstep = 1000;

set(handles.slider, 'Enable', 'off');
set(handles.Zoom_out, 'Enable', 'off');
set(handles.Zoom_in, 'Enable', 'off');
set(handles.Start_time, 'Enable', 'off');
set(handles.Stop_time, 'Enable', 'off');
set(handles.Bin_duration, 'Enable', 'off');
set(gcf,'doublebuffer','on'); % sets the current figure's double buffer
clear('handles.rawplot')
clear('handles.Avg_response');
clear('handles.Selection');
handles.count = 0;      %For PCA analysis - count indexes the data sets being exported for PCA analysis
handles.PCA_sel = [];   %Initialises the array for storing all PCA data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55



% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Event_triggered wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Event_triggered_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


%If user updates start time
function Start_time_Callback(hObject, eventdata, handles)

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

% Hints: get(hObject,'String') returns contents of Start_time as text
%        str2double(get(hObject,'String')) returns contents of Start_time as a double

%If the stop time is set also then update the bin duration, average it,
%then plot it
if(length(str2num(get(handles.Stop_time, 'String')))~=0)
    %set the bin duration based on start and stop times
    set(handles.Bin_duration, 'String' ,num2str(str2num(get(handles.Stop_time, 'String'))-str2num(get(handles.Start_time, 'String'))));
    
    % if the time selection is valid then update the graph
    if(str2num(get(handles.Bin_duration, 'String'))>0)
        handles = update_selection(handles); % call the update function
    else
        errordlg('The start time must be less than the stop time for a selection',...
        'Incorrect Selection','modal')
    end
elseif(length(num2str(get(handles.Bin_duration, 'String')))>1)
    %Update the stop time based on bin length and start time
    set(handles.Stop_time, 'String' ,num2str(str2num(get(handles.Start_time, 'String'))+str2num(get(handles.Bin_duration, 'String'))));
    
    % if the time selection is valid then update the graph
    if(str2num(get(handes.Bin_duration, 'String'))>0)
        handles = update_selection(handles);% call the update function
     else
        errordlg('The start time must be less than the stop time for a selection',...
        'Incorrect Selection','modal')
    end
end %if


%

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


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

% Hints: get(hObject,'String') returns contents of Stop_time as text
%        str2double(get(hObject,'String')) returns contents of Stop_time as a double

%If the start time is set also then update the bin length
if(handles.Start_time)
    set(handles.Bin_duration, 'String' ,num2str(str2num(get(handles.Stop_time, 'String'))-str2num(get(handles.Start_time, 'String'))));
    if(str2num(get(handles.Bin_duration, 'String'))>0)
        handles = update_selection(handles); % call the update function
    else
        errordlg('The start time must be less than the stop time for a selection',...
        'Incorrect Selection','modal')
    end
elseif(length(num2str(get(handles.Bin_duration, 'String')))>1)
    %Update the stop time based on bin length and start time
    set(handles.Stop_time, 'String' ,num2str(str2num(get(handles.Start_time, 'String'))+str2num(get(handles.Bin_duration, 'String'))));
    if(str2num(get(handles.Bin_duration, 'String'))>0)
        handles = update_selection(handles); % call the update function
    else
        errordlg('The start time must be less than the stop time for a selection',...
        'Incorrect Selection','modal')
    end
end %if

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

function Bin_duration_Callback(hObject, eventdata, handles)

    if(str2double(get(hObject, 'String'))<0)
        errordlg('The selection time must be positive',...
            'Incorrect Selection','modal')
    else
        if(length(num2str(get(handles.Start_time, 'String'))))
            %Update the stop time based on bin length and start time
            set(handles.Stop_time, 'String' ,num2str(str2num(get(handles.Start_time, 'String'))+str2num(get(handles.Bin_duration, 'String'))));
            handles = update_selection(handles);% call the update function
        elseif(handles.Stop_time)
            %set the start time based on bin duration and stop time
            set(handles.Start_time, 'String' ,num2str(str2num(get(handles.Stop_time, 'String'))-str2num(get(handles.Bin_duration, 'String'))));
            handles = update_selection(handles); % call the update function
        end %if
    end
    %update the handles structure
guidata(hObject, handles);
    
%EoF
        
% --- Executes on selection change in rawdata.
function rawdata_Callback(hObject, eventdata, handles)

handles = refresh(handles);
set(handles.eventtriggers, 'Enable', 'on');
% get the variable selected in the listbox
list_entries = get(handles.rawdata,'String');
index_selected = get(handles.rawdata,'Value');
if length(index_selected) ~= 1
    errordlg('You must select only one variable',...
        'Incorrect Selection','modal')
else
    handles.userdata = evalin('base', list_entries{index_selected(1)});
end

t = linspace(0,(length(handles.userdata) -1)/handles.tstep,length(handles.userdata))';

axes(handles.rawplot);
cla(gca);
plot(handles.rawplot, t, handles.userdata)
xlabel(handles.rawplot,'Time (s)')
ylabel(handles.rawplot,'Signal (mV)')


if(length(handles.triggers>0))
    TRG = find(handles.triggers >= 1);
    if(length(handles.userdata)< TRG(length(TRG))+str2num(get(handles.trigger_spacing, 'String')))
        errordlg('Warning: Trigger spacing is too large',...
            'Incorrect Selection','modal')
    else
        %update teh average selection
        handles = update_average(handles);
        %Allow the user to select parts of the average
        set(handles.Start_time, 'Enable', 'Off');
        set(handles.Stop_time, 'Enable', 'Off');
        set(handles.Bin_duration, 'Enable', 'Off');
        %PLot the triggers
        axes(handles.rawplot)
        for G=1:length(TRG)
            Lin(G)=line([TRG(G)/1000; TRG(G)/1000], [max(handles.userdata);...
                min(handles.userdata)],'Color','r');
        end
    end
end
 
handles.dx=(length(handles.userdata)-1)/handles.tstep; %axis length
%%%%% Set appropriate axis limits and settings
set(gcf,'doublebuffer','on');
% This avoids flickering when updating the axis
set(handles.rawplot,'xlim',[0 handles.dx]);
% set(handles.axes1,'ylim',[min(y) max(y)]);

set(handles.slider, 'Value', 0);
set(handles.slider, 'Enable', 'off');
set(handles.Zoom_out, 'Enable', 'off');
set(handles.Zoom_in, 'Enable', 'on');



% Update handles structure
guidata(hObject, handles);



% --- Executes on selection change in eventtriggers.
function eventtriggers_Callback(hObject, eventdata, handles)
cla(handles.rawplot)
cla(handles.Avg_response)

set(handles.DataStartTime, 'Enable', 'on');
set(handles.FirstTrigTime, 'Enable', 'on');
set(handles.trigger_spacing, 'Enable', 'on');
set(handles.NumTrig, 'Enable', 'on');
set(handles.slider, 'SliderStep', [0.0100    0.1000]);


list_entries = get(handles.eventtriggers,'String');
index_selected = get(handles.eventtriggers,'Value');
if length(index_selected) ~= 1
    errordlg('You must select only one variable',...
        'Incorrect Selection','modal')
else
    handles.triggers = evalin('base', list_entries{index_selected(1)});
end
%Here we guess at the data start time by first looking for a variable and
%if that fails, setting it to the  first trigger time
try
    %Generate the guessed variable name-edit this for your software
    rawvars = get(handles.rawdata,'String');
    rawselected = get(handles.rawdata,'Value');

    rawvarname = strcat(rawvars{rawselected},'_ts');
    set(handles.DataStartTime, 'String', num2str(evalin('base', rawvarname)));
catch
    % if we failed: set(FirstTrigTime,-> handles.triggers(1));
    set(handles.DataStartTime, 'String', num2str(handles.triggers(1)));
end
try
    set(handles.FirstTrigTime, 'String', num2str(handles.triggers(1)));
catch
    errordlg('Your trigger information must be numeric',...
        'Incorrect Selection','modal')
end

set(handles.NumTrig, 'String', num2str(length(handles.triggers)));

try
    newtriggers = zeros(length(handles.userdata), 1);
    newtriggers(round((handles.triggers-str2num(get(handles.DataStartTime, 'String')))*handles.tstep +1 )) =1;
    handles.triggers = newtriggers;

    TRG = find(handles.triggers >= 1);
    t = linspace(0,(length(handles.triggers)-1)/handles.tstep,length(handles.triggers));
    if(max(handles.userdata) ~= 0) && length(handles.userdata)==length(t);
        %Plot the user's data
        plot(handles.rawplot, t, handles.userdata)
        xlabel(handles.rawplot,'Time (s)')
        ylabel(handles.rawplot,'Signal (mV)')
        %%%%% Set appropriate axis limits and settings
        % This avoids flickering when updating the axis
        set(gcf,'doublebuffer','on');
        handles.dx=(length(handles.userdata)-1)/handles.tstep; %axis length
        set(handles.rawplot,'xlim',[0 handles.dx]);
        %Allow the user to select parts of the average
        set(handles.Start_time, 'Enable', 'on');
        set(handles.Stop_time, 'Enable', 'on');
        set(handles.Bin_duration, 'Enable', 'on');

        %Plot the triggers: these appear as dots if there is no Userdata selected
        for G=1:length(TRG)
            line([(TRG(G)-1)/handles.tstep; (TRG(G)-1)/handles.tstep],...
                [max(handles.userdata);min(handles.userdata)],'Color','r');
        end

        set(handles.trigger_spacing, 'String',  num2str(min(...
            (length(handles.userdata)-(TRG(end))),TRG(2)-TRG(1)))) ;
        if(length(handles.userdata) ~= 1)
            if(length(handles.userdata)< TRG(end)+...
                    str2num(get(handles.trigger_spacing, 'String'))) ||...
                    str2num(get(handles.trigger_spacing, 'String'))>TRG(2)-TRG(1)

                errordlg('Warning: Trigger spacing is too large',...
                    'Incorrect Selection','modal')
            else
                handles = update_average(handles);
            end %if
        end %if userdata
    end 
catch
    errordlg(strcat('Warning: There was an error whilst reading the', ...
        'trigger information. Plese revise your selections'),...
        'Incorrect Selection','modal');
end

 guidata(hObject, handles);




%If the user modifies the post-trigger averaging time
function trigger_spacing_Callback(hObject, eventdata, handles)
if((length(handles.userdata) ~= 1) && (length(str2num(get(handles.trigger_spacing, 'String')))~=0) && length(handles.triggers)~= 0)
    TRG = find(handles.triggers >= 1);
    if(length(handles.userdata)< TRG(end)+str2num(get(handles.trigger_spacing, 'String')))
        errordlg('Warning: Trigger spacing is too large',...
            'Incorrect Selection','modal')
        set(handles.trigger_spacing, 'String',  num2str(min(...
            (length(handles.userdata)-(TRG(end))),TRG(2)-TRG(1))))
    elseif(length(handles.userdata) ~= 1)
        if(length(handles.userdata)< TRG(end)+...
                str2num(get(handles.trigger_spacing, 'String'))) |...
                str2num(get(handles.trigger_spacing, 'String'))>TRG(2)-TRG(1)
            errordlg('Warning: Trigger spacing is too large',...
                'Incorrect Selection','modal')
        else
            handles = update_average(handles);
        end
    end % if
end

%This Function updates the average response after a trigger and the
%selected section of that response.
function handles2 = update_selection(handles)
TRG = find(handles.triggers >= 1);

% t = linspace(0,str2num(get(handles.trigger_spacing, 'String'))/handles.tstep,(str2num(get(handles.trigger_spacing, 'String')))+1);
if( length(handles.userdata)> length(TRG)*str2num(get(handles.trigger_spacing, 'String')))
    %update the average 
        %-this might not need to be done really but it cant
        %hurt to do it anyway
    handles = update_average(handles);
    
    %Now update the average selection graph
    t = linspace(floor(str2num(get(handles.Start_time, 'String'))), ...
        floor(str2num(get(handles.Stop_time, 'String'))),...
        floor(str2num(get(handles.Stop_time, 'String')))-...
        floor(str2num(get(handles.Start_time, 'String')))+1);
    plot(handles.Selection, t, handles.avg_response(floor(str2num(get(handles.Start_time, 'String'))+1):floor(str2num(get(handles.Stop_time, 'String'))+1)));
    xlabel(handles.Selection,'Time (ms)')
    ylabel(handles.Selection,'Signal (mV)')
    xlim(handles.Selection, [str2num(get(handles.Start_time, 'String')) str2num(get(handles.Stop_time, 'String'))]);
else %If # bins times the length of a bin is greater than the length of the data...
    errordlg('Warning: Trigger spacing is too large',...
        'Incorrect Selection','modal')
    I=length(TRG+1);
end %if
handles2 = handles;
%handles is still not saved!
%End of Function

%This Function updates the average response plot
function output = update_average(handles)
TRG = find(handles.triggers >= 1);
TriggerSpacing = str2num(get(handles.trigger_spacing, 'String'));

Fs = handles.tstep;


if( length(handles.userdata)> length(TRG)*TriggerSpacing) &&...
        TRG(end)<length(handles.userdata)
    for(I=1:1:length(TRG))
        selection(I, :) = handles.userdata(TRG(I):TRG(I)+TriggerSpacing);
    end %for
    %Average the bins
    handles.avg_response = mean(selection, 1);
    t = linspace(0,TriggerSpacing ,TriggerSpacing+1);
    %plot the average siganl graph
    plot(handles.Avg_response, t, handles.avg_response)
    xlabel(handles.Avg_response,'Time (ms)')
    ylabel(handles.Avg_response,'Signal (mV)')
    xlim(handles.Avg_response, [0 str2num(get(handles.trigger_spacing, 'String'))/handles.tstep*1000]);
else
    errordlg('The trigger times do not appear to correspond with the LFP data',...
        'Incorrect Selection', 'modal');
end
output = handles;



% --- Executes on slider movement (trough click or button-click)
function slider_Callback(hObject, eventdata, handles)
set(handles.rawplot, 'xlim' ,get(handles.slider, 'Value')*((length(handles.userdata)/handles.tstep)-handles.dx)+[0 handles.dx]);

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

% --- Executes on button press: Zoom_out.
function Zoom_out_Callback(hObject, eventdata, handles)
handles.dx=(handles.dx)*2;
if(handles.dx==(length(handles.userdata)-1)/handles.tstep)
    set(handles.slider, 'Enable', 'off');
    set(handles.slider, 'Value', 0);
    set(handles.Zoom_out, 'Enable', 'off');
end
set(handles.rawplot, 'xlim' ,get(handles.slider, 'Value')*((length(handles.userdata)/handles.tstep)-handles.dx)+[0 handles.dx]);
%adjust the slider step size [buttonclik percentage trough-click
%percentage]
set(handles.slider, 'SliderStep', (1/.5).*get(handles.slider, 'SliderStep'));


guidata(hObject, handles);

% --- Executes on button press in Zoom_in.
function Zoom_in_Callback(hObject, eventdata, handles)
% hObject    handle to Zoom_in (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

handles.dx=(handles.dx)*0.5;
if(isequal(strfind(get(handles.slider, 'Enable'), 'on'),[])==1)
    set(handles.slider, 'Enable', 'on');
    set(handles.slider, 'Value', 0.5);
    set(handles.Zoom_out, 'Enable', 'on');
end

set(handles.rawplot, 'xlim' ,get(handles.slider, 'Value')*...
   ((length(handles.userdata)-1)/handles.tstep-handles.dx)+[0 handles.dx]);
%adjust the slider step size [buttonclik percentage trough-click
%percentage]

set(handles.slider, 'SliderStep', 0.5.*get(handles.slider, 'SliderStep'));


guidata(hObject, handles);


% --- Executes on button press in Export_LFP.
function Export_LFP_Callback(hObject, eventdata, handles)

StartT = str2num(get(handles.Start_time, 'String'));
StopT = str2num(get(handles.Stop_time, 'String'));
if(length(handles.avg_response)~=0)
assignin('base', 'ExportedAverage', handles.avg_response(StartT+1:StopT+1)');
Front_Panel;
else
    errordlg(strcat('Please ensure that you have selected all or part',...
        'of the signal.If the problem persists select <Refresh Variables>',...
        'from the File menu'), 'Incorrect Selection', 'modal');
end


% --- Executes on button press in Export_PCA.
function Export_PCA_Callback(hObject, eventdata, handles)
t = (str2num(get(handles.Start_time, 'String')):str2num(get(handles.Stop_time, 'String')));

M = size(handles.PCA_sel,2)

NumTrig = str2num(get(handles.NumTrig, 'String'));

PCA(handles.PCA_sel, M, t, NumTrig);



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
function DataStartTime_Callback(hObject, eventdata, handles)
%This function resets the slider and re-plots any possible plots
if length(handles.userdata)~=1 && length(handles.triggers)~=0
    %reset the slider
    set(handles.slider, 'SliderStep', [0.0100    0.1000])


    %Get the selected trigger
    list_entries = get(handles.eventtriggers,'String');
    index_selected = get(handles.eventtriggers,'Value');
    if length(index_selected) ~= 1
        errordlg('You must select one variable',...
            'Incorrect Selection','modal')
    else
        handles.triggers = evalin('base', list_entries{index_selected(1)});
    end

    %Set the number of triggers
    set(handles.NumTrig, 'String', num2str(length(handles.triggers)));

    %These next statements define the variable: handles.triggers
    %this is an array the same length as the user's data which has a 1
    %wherever a trigger occured.
    newtriggers = zeros(length(handles.userdata), 1);
    %The +1 command is required because the first array element corresponds
    %to ZERO seconds.
    newtriggers(round((handles.triggers-str2num(get(handles.DataStartTime, 'String')))*handles.tstep +1)) =1;


    if length(newtriggers) == length(handles.userdata)
        %If the start time the user entered was too short, it will
        %make newtriggers longer than handles.userdata. if
        %this has happend then this code will not execute
        TRG = find(newtriggers >= 1);

        t = linspace(0,(length(newtriggers)-1)/handles.tstep,length(newtriggers));
        axes(handles.rawplot)
        %Plot the data again
        cla(gca);
        plot(handles.rawplot, t, handles.userdata)
        xlabel(handles.rawplot,'Time (s)')
        ylabel(handles.rawplot,'Signal (mV))')
        handles.dx=length(handles.userdata)/handles.tstep; %axis length
        %%%%% Set appropriate axis limits and settings
        set(gcf,'doublebuffer','on');
        % This avoids flickering when updating the axis
        set(handles.rawplot,'xlim',[0 handles.dx]);

        %The  -1 in the following loop is required because the
        %first element of the array corresponds to zero and the LINE
        %command works on time not position
        for G=1:length(TRG)
            line([(TRG(G)-1)/handles.tstep; (TRG(G)-1)/handles.tstep ], [max(handles.userdata);min(handles.userdata)],'Color','r');
        end

        %Update the length of the post-trigger averaging time
        set(handles.trigger_spacing, 'String',  min(...
            length(handles.userdata)-TRG(end),TRG(2)-TRG(1)));


        if(length(handles.userdata) ~= 1)
            TRG = find(newtriggers >= 1);
            if(length(handles.userdata)< TRG(end)+...
                    str2num(get(handles.trigger_spacing, 'String'))) |...
                    str2num(get(handles.trigger_spacing, 'String'))>TRG(2)-TRG(1)
                errordlg('Warning: Trigger spacing is too large',...
                    'Incorrect Selection','modal')
            else
                handles.triggers = newtriggers;
                handles = update_average(handles);
            end
        end  %if
    else
        %The user entered an in-valid start time, tell tehm and reset the
        %start time
        errordlg('The start time you have enterd is too low or you have not selected any data. Please try again',...
            'Incorrect Selection','modal')
        set(handles.DataStartTime, 'String', num2str(handles.triggers(1)));
    end

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

else
    errordlg('Check that you have selected both LFP and trigger data',...
        'Incorrect Selection','modal');
end


%This is called when nothing is required
function NULL_Callback(hObject, eventdata, handles)

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




% --- Executes on button press in store_PCA.
function store_PCA_Callback(hObject, eventdata, handles)
% hObject    handle to store_PCA (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

TRG = find(handles.triggers >= 1);

%t = linspace(0,str2num(get(handles.trigger_spacing, 'String'))/handles.tstep,(str2num(get(handles.trigger_spacing, 'String')))+1);
%if( length(handles.userdata)> length(TRG)*str2num(get(handles.trigger_spacing, 'String')))

for(I=1:length(TRG))
        handles.PCA_n(:, I) = handles.userdata(TRG(I)+str2num(get(handles.Start_time, 'String')):TRG(I)+str2num(get(handles.Stop_time, 'String')));  
end

handles.count = handles.count+1

handles.PCA_sel = [handles.PCA_sel handles.PCA_n];

guidata(hObject, handles);



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


% --------------------------------------------------------------------
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 FILE_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)
clear;
delete(gcf);

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

guidata(hObject, handles);
% --------------------------------------------------------------------
function Help_Quickstart_Callback(hObject, eventdata, handles)
Event_Triggered_Quickstart;


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

Event_Triggered_Help;

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

%This function re-sets the window and clears variables
function out = refresh(handles)
vars = evalin('base','who');
set(handles.rawdata,'String',vars)          %populates rawdata listbox
set(handles.eventtriggers,'String',vars)
set(handles.eventtriggers,'Enable','off')
handles.userdata=0;
handles.triggers=[];
handles.avg_response = [];
handles.tstep = 1000;
set(handles.slider, 'Enable', 'Off');
set(handles.Zoom_out, 'Enable', 'Off');
set(handles.Zoom_in, 'Enable', 'Off');
set(gcf,'doublebuffer','on'); % sets the current figure's double buffer
cla(handles.rawplot)
cla(handles.Avg_response);
cla(handles.Selection);
set(handles.DataStartTime, 'Enable', 'off');
set(handles.FirstTrigTime, 'Enable', 'off');
set(handles.trigger_spacing, 'Enable', 'off');
set(handles.NumTrig, 'Enable', 'off');

set(handles.Start_time, 'Enable', 'off');
set(handles.Stop_time, 'Enable', 'off');
set(handles.Bin_duration, 'Enable', 'off');
set(handles.FirstTrigTime, 'String', '');
set(handles.DataStartTime, 'String', '');
set(handles.NumTrig, 'String', '');
set(handles.trigger_spacing, 'String', '');
out = handles;
%EOF
