function varargout = ADPerieventGUIA(varargin)
% This GUI is a modified version of Software originally written by Plexon
% Inc for version 6 of Matlab. The .m/.mat files and perieventFns.m were
% combined and edited to the current .m/.fig files of this version to work
% in 7.2 (R2006a) by Richard Peter contactable at
% infinitybeckon@hotmail.com.
%
% The file is designed to take live data and plot each event either
% individually or average successive events.
% Last Modified by Richard Peter 20-Jul-2006 23:10:25

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

% Choose default command line output for ADPerieventGUIA
handles.output = hObject;
handles.S1 = [];
handles.PARS1 = [];
handles.CONNECTED1  = [];
handles.RUNNING1 = [];
handles.lfp_ave = [];
% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = ADPerieventGUIA_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;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function perieventFns(handles, hObject)
% functions used by ADPerieventGUI1


switch handles.action

case 'connect'
   if ~isempty(handles.RUNNING1) | ~isempty(handles.CONNECTED1)
      dialogString=char('Already Connected to Server');
      set(handles.dialogBox,'String',dialogString);
      return
   end
   handles.S1=0;
   %Use a TRY statement to avoid error messages in the command window
%    try
   handles.S1=PL_InitClient(0);
%    catch
%       dialogString=char('Error: Cannot Connect to Server');
%       set(handles.dialogBox,'String',dialogString);
%    end
   if handles.S1 ~= 0
      handles.CONNECTED1=1;
      dialogString=char('Connected to Server');
      set(handles.dialogBox,'String',dialogString);
      handles.PARS1=PL_GetPars(handles.S1);
      NumADchan=handles.PARS1(7);
      set(handles.ADchanList,'String',char(num2str([1:NumADchan]')))
   end
   % Update handles structure
guidata(hObject, handles);

case 'disconnect'

   if ~isempty(handles.RUNNING1)
      handles.action = 'stop';
      perieventFns(handles, hObject);
      pause(0.5);
   end
   if ~isempty(handles.CONNECTED1)
      dialogString=char('Disconnected from Server');
      set(handles.dialogBox,'String',dialogString);
      PL_Close(handles.S1);
      handles.S1=[];
      handles.CONNECTED1=[];
      handles.RUNNING1 = [];
   end
   % Update handles structure
   guidata(hObject, handles);

case 'plot'
   if isempty(handles.CONNECTED1)
      dialogString=char('Error: First Connect to Server');
      set(handles.dialogBox,'String',dialogString);
      return
   end
   if ~isempty(handles.RUNNING1)
      return
   end
   dialogString=char('Plotting AD Perievent Data');
   set(handles.dialogBox,'String',dialogString);
   handles.RUNNING1=1;
   NumADchan=handles.PARS1(7);
   ADfreq=handles.PARS1(8); %AD freq in Hz
   lfp_pre=GetPreTime(handles); %Pre-event time in sec
   lfp_post=GetPostTime(handles); %Post-event time in sec
   event=GetEvent(handles);
   ADchan=GetADchan(handles);
   eventCue=[];
   totNumEvents=0;
   SetNumEvents(totNumEvents, handles)
   S = GetNum2Plot(handles);
   %To view the filter, insert a breakpoint on line 142 and when the
   %program stops, type: fvtool(Coeffs). - There is a small ammount of
   %passband ripple, however the phase response is linear.
   Coeffs = fir1(400, [49 51]/ADfreq*2, 'stop');


   [num,ts]=PL_GetTS(handles.S1);
   handles.lfp_ave=zeros(round((lfp_pre+lfp_post)*ADfreq+1),NumADchan);
   [n,t,d]=PL_GetAD(handles.S1);
   while ~get(handles.StopButton, 'Value')
      serverEventIn=0;
      while serverEventIn==0
         if get(handles.StopButton, 'Value')
            set(handles.StopButton, 'Value',1);
            return
         end
         pause(max([(lfp_pre+lfp_post)*2 1.55]));
         %Use try in case the user disconnects whilst plotting
         try
         serverEventIn=PL_WaitForServer(handles.S1,(lfp_pre+lfp_post)*1000);
         catch
             return
         end
      end
      %   n - 1 by 1 matrix, number of timestamps retrieved
      %   t - n by 4 matrix, timestamp info:
      %       t(:, 1) - timestamp types (1 - neuron, 4 - external event)
      %       t(:, 2) - channel numbers ( =257 for strobed ext events )
      %       t(:, 3) - unit numbers ( strobe value for strobed ext events )
      %       t(:, 4) - timestamps in seconds
      [num,ts]=PL_GetTS(handles.S1);
      nn=n;tt=t;dd=d;
      %   n - 1 by 1 matrix, number of data points retrieved (for each 
channel)
      %   t - 1 by 1 matrix, timestamp of the first data point (in seconds)
      %   d - n by nch matrix, where nch is the number of active A/D 
channels,
      [n,t,d]=PL_GetAD(handles.S1);
      if handles.filter
         d = filtfilt(Coeffs, 1,  d);
      end

      eventCue=[eventCue; (ts(find((ts(:,1)==4).*(ts(:,2)==event)),4))];
      nn=nn+n;
      dd=[dd;d];
      while ~get(handles.StopButton, 'Value') & length(eventCue)>0 & ( 
ceil((tt+(nn-1)/ADfreq-eventCue(1))*ADfreq)/ADfreq > lfp_post )
         lfp_start=round((eventCue(1)-lfp_pre-tt)*ADfreq)+1;
         lfp_stop=lfp_start+(lfp_pre+lfp_post)*ADfreq;
         totNumEvents=totNumEvents+1;
         if Average(handles)
            handles.lfp_ave=((totNumEvents-1)*handles.lfp_ave + 
dd(lfp_start:lfp_stop,:))/totNumEvents;
         else
            handles.lfp_ave=dd(lfp_start:lfp_stop,:);
         end
         x=-1*lfp_pre:1/ADfreq:lfp_post;
         y=handles.lfp_ave(:,ADchan);
         plot(handles.Axes1, x,y,'b')
         hold on
         set(gca,'XLim',[-1*lfp_pre lfp_post])
         ylim=get(gca,'YLim');
         plot(handles.Axes1, x*0,[ones(1,length(y)-1)*ylim(1),ylim(2)],'k:')
         hold off
         SetNumEvents(totNumEvents, handles)
         eventCue=eventCue(2:length(eventCue));
         if S %if there is a limit to how many to plot
             if S == totNumEvents
                 dialogString=char('Completed Plotting');
                 set(handles.dialogBox,'String',dialogString);
                 handles.RUNNING1 = [];
                 %u=pdate the handles structure then quit
                 guidata(hObject, handles);
                 return
             end
         end
         guidata(hObject, handles);

      end

   end
   %pop the stop button out
    set(handles.StopButton, 'Value', 0);
    handles.RUNNING1 = [];
    % Update handles structure
    guidata(hObject, handles);

case 'stop'
   if ~isempty(handles.RUNNING1)
      dialogString=char('Stopped Perievent Plotting');
      set(handles.dialogBox,'String',dialogString);
   else
      set(handles.StopButton, 'Value', 0);
   end

   % Update handles structure
    guidata(hObject, handles);


end

%-----------------------------------------------------
%Functions for perieventFns

function y=GetPreTime(handles)
% get pre-event time
y=str2num(get(handles.pre,'String'));

function y=GetPostTime(handles)
% get post-event time
y=str2num(get(handles.post,'String'));

function y=GetEvent(handles)
% get pre-event time
y=str2num(get(handles.eventBox,'String'));

function S = GetNum2Plot(handles)
% get the number of events that are to be plotted
y = get(handles.NumEvents2Plot, 'String');
S = y{get(handles.NumEvents2Plot, 'Value')};
if S == 'All'
    S = '0';
end
S = str2num(S);

function SetNumEvents(n,handles)
% Set the #Events text string
set(handles.numEvents,'String',sprintf('%5.0f',n))

function SetADchanList(textstring, handles)
% Set the AD Channels listbox
set(handles.ADchanList,'String',textstring)

function y=GetADchan(handles)
% get AD channel
string = get(handles.ADchanList,'String');
value = get(handles.ADchanList,'Value');
string=cellstr(string);
y=str2num(string{value});

function y=Average(handles)
% Set the plot mode to single or average
value = get(handles.mode,'Value');
string = get(handles.mode,'String');
if strcmp(string{value},'Average')
   y=1;
else
   y=0;
end

%%%---------------------------------------------------------------






function eventBox_Callback(hObject, eventdata, handles)
% hObject    handle to eventBox (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 eventBox as text
%        str2double(get(hObject,'String')) returns contents of eventBox as a 
double


% --- Executes during object creation, after setting all properties.
function eventBox_CreateFcn(hObject, eventdata, handles)
% hObject    handle to eventBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), 
get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function numEvents_Callback(hObject, eventdata, handles)
% hObject    handle to numEvents (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 numEvents as text
%        str2double(get(hObject,'String')) returns contents of numEvents as 
a double


% --- Executes during object creation, after setting all properties.
function numEvents_CreateFcn(hObject, eventdata, handles)
% hObject    handle to numEvents (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), 
get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function dialogBox_Callback(hObject, eventdata, handles)
% hObject    handle to dialogBox (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 dialogBox as text
%        str2double(get(hObject,'String')) returns contents of dialogBox as 
a double


% --- Executes during object creation, after setting all properties.
function dialogBox_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dialogBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), 
get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function post_Callback(hObject, eventdata, handles)
% hObject    handle to post (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 post as text
%        str2double(get(hObject,'String')) returns contents of post as a 
double


% --- Executes during object creation, after setting all properties.
function post_CreateFcn(hObject, eventdata, handles)
% hObject    handle to post (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), 
get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function pre_Callback(hObject, eventdata, handles)
% hObject    handle to pre (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 pre as text
%        str2double(get(hObject,'String')) returns contents of pre as a 
double


% --- Executes during object creation, after setting all properties.
function pre_CreateFcn(hObject, eventdata, handles)
% hObject    handle to pre (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), 
get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in ADchanList.
function ADchanList_Callback(hObject, eventdata, handles)
% hObject    handle to ADchanList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns ADchanList contents as 
cell array
%        contents{get(hObject,'Value')} returns selected item from 
ADchanList


% --- Executes during object creation, after setting all properties.
function ADchanList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ADchanList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), 
get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in mode.
function mode_Callback(hObject, eventdata, handles)
% hObject    handle to mode (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns mode contents as cell 
array
%        contents{get(hObject,'Value')} returns selected item from mode


% --- Executes during object creation, after setting all properties.
function mode_CreateFcn(hObject, eventdata, handles)
% hObject    handle to mode (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), 
get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes on button press in ConnectBtn.
function ConnectBtn_Callback(hObject, eventdata, handles)
handles.action = 'connect';
perieventFns(handles, hObject)


% --- Executes on button press in PlotButton.
function PlotButton_Callback(hObject, eventdata, handles)
handles.action = 'plot';
perieventFns(handles, hObject)


% --- Executes on button press in DisConBtn.
function DisConBtn_Callback(hObject, eventdata, handles)
handles.action = 'disconnect';
perieventFns(handles, hObject)


% --- Executes on button press in StopButton.
function StopButton_Callback(hObject, eventdata, handles)
handles.action = 'stop';
perieventFns(handles, hObject)




% --- Executes on selection change in NumEvents2Plot.
function NumEvents2Plot_Callback(hObject, eventdata, handles)
% hObject    handle to NumEvents2Plot (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns NumEvents2Plot contents as 
cell array
%        contents{get(hObject,'Value')} returns selected item from 
NumEvents2Plot


% --- Executes during object creation, after setting all properties.
function NumEvents2Plot_CreateFcn(hObject, eventdata, handles)
% hObject    handle to NumEvents2Plot (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), 
get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in ExportFigure. -
%Plots the current selection in a new figure
function ExportFigure_Callback(hObject, eventdata, handles)

ADfreq=handles.PARS1(8); %AD freq in Hz
lfp_pre=GetPreTime(handles); %Pre-event time in sec
lfp_post=GetPostTime(handles); %Post-event time in sec
ADchan=GetADchan(handles);

x=-1*lfp_pre:1/ADfreq:lfp_post;
y=handles.lfp_ave(:,ADchan);

handles.userdata = y;
handles.t = x;
handles.tstep = ADfreq;

handles.yvalues = y;
handles.xvalues = x;
handles.tstep = ADfreq;
   % Update handles structure
    guidata(hObject, handles);

Cursor_export(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 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)

AboutADPerieven;


% --- Executes on button press in filter.
function filter_Callback(hObject, eventdata, handles)
% hObject    handle to filter (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 filter



