function varargout = MonoBinoActivityPlot(varargin)
% MONOBINOACTIVITYPLOT MATLAB code for MonoBinoActivityPlot.fig
%      MONOBINOACTIVITYPLOT, by itself, creates a new MONOBINOACTIVITYPLOT or raises the existing
%      singleton*.
%
%      H = MONOBINOACTIVITYPLOT returns the handle to a new MONOBINOACTIVITYPLOT or the handle to
%      the existing singleton*.
%
%      MONOBINOACTIVITYPLOT('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MONOBINOACTIVITYPLOT.M with the given input arguments.
%
%      MONOBINOACTIVITYPLOT('Property','Value',...) creates a new MONOBINOACTIVITYPLOT or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before MonoBinoActivityPlot_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to MonoBinoActivityPlot_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 MonoBinoActivityPlot

% Last Modified by GUIDE v2.5 08-Jan-2018 16:49:20

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @MonoBinoActivityPlot_OpeningFcn, ...
                   'gui_OutputFcn',  @MonoBinoActivityPlot_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
end %

% --- Executes just before MonoBinoActivityPlot is made visible.
function MonoBinoActivityPlot_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 MonoBinoActivityPlot (see VARARGIN)

% Choose default command line output for MonoBinoActivityPlot
%specify initiation parameters
handles.output = hObject;
set(handles.edit_rostral,'String',999)
handles.rostral=999;
set(handles.edit_caudal,'String',-999)
handles.caudal=-999;
set(handles.edit_left,'String',-999)
handles.left=-999;
set(handles.edit_right,'String',999)
handles.right=999;
set(handles.edit_dorsal,'String',999)
handles.dorsal=999;
set(handles.edit_ventral,'String',-999)
handles.ventral=-999;
set(handles.edit_inReg,'String',1)
handles.edit_inReg=1;
set(handles.edit_inVal,'String',0)
handles.edit_inVal=0;
set(handles.edit_exReg1,'String',4)
handles.edit_exReg1=4;
set(handles.edit_exReg2,'String',5)
handles.edit_exReg2=5;
set(handles.edit_exVal1,'String',1)
handles.edit_exVal1=1;
set(handles.edit_exVal2,'String',1)
handles.edit_exVal2=1;

set(handles.edit_SLE,'String',1)
handles.edit_SLE=1;
set(handles.edit_SRE,'String',300)
handles.edit_SRE=300;
set(handles.edit_SBE,'String',600)
handles.edit_SBE=600;

handles.check_manualCell=0;
set(handles.edit_frameTime,'String',0.5)
handles.frameTime=0.5;
set(handles.edit_tau,'String',1.1)
handles.tau=1.1;
set(handles.edit_RegThres,'String',0.6)
handles.RegThres=0.6;
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes MonoBinoActivityPlot wait for user response (see UIRESUME)
% uiwait(handles.MainVelPosGUI);
end %

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


function edit_rostral_Callback(hObject, eventdata, handles)
% hObject    handle to edit_rostral (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.rostral=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_rostral as text
%        str2double(get(hObject,'String')) returns contents of edit_rostral as a double
end %

% --- Executes during object creation, after setting all properties.
function edit_rostral_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_rostral (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
end %


function edit_caudal_Callback(hObject, eventdata, handles)
% hObject    handle to edit_caudal (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.caudal=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_caudal as text
%        str2double(get(hObject,'String')) returns contents of edit_caudal as a double
end %

% --- Executes during object creation, after setting all properties.
function edit_caudal_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_caudal (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
end %


function edit_left_Callback(hObject, eventdata, handles)
% hObject    handle to edit_left (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.left=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_left as text
%        str2double(get(hObject,'String')) returns contents of edit_left as a double
end %

% --- Executes during object creation, after setting all properties.
function edit_left_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_left (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
end %


function edit_right_Callback(hObject, eventdata, handles)
% hObject    handle to edit_right (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.right=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_right as text
%        str2double(get(hObject,'String')) returns contents of edit_right as a double
end %

% --- Executes during object creation, after setting all properties.
function edit_right_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_right (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
end %


function edit_dorsal_Callback(hObject, eventdata, handles)
% hObject    handle to edit_dorsal (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.dorsal=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_dorsal as text
%        str2double(get(hObject,'String')) returns contents of edit_dorsal as a double
end %

% --- Executes during object creation, after setting all properties.
function edit_dorsal_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_dorsal (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
end %


function edit_ventral_Callback(hObject, eventdata, handles)
% hObject    handle to edit_ventral (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.ventral=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_ventral as text
%        str2double(get(hObject,'String')) returns contents of edit_ventral as a double
end %

% --- Executes during object creation, after setting all properties.
function edit_ventral_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_ventral (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
end %


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

% --- Executes during object creation, after setting all properties.
function edit_nameTimeseries_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_nameTimeseries (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
end %


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

% --- Executes during object creation, after setting all properties.
function edit_nameR_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_nameR (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
end %

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

%Load data for Step2 (firing threshold analysis)
[fileR, pathR, FilterIndex]=uigetfile('.mat','Please select the appropriate R file(s)','MultiSelect','on');
if isempty(fileR) || FilterIndex==0
    errordlg('No file selected','Warning')
    return
end
fileR=cellstr(fileR); %to run size command when only one file is loaded
handles.fileR=fileR;
handles.pathR=pathR;

[fileExportmat, pathExportmat, FilterIndexex]=uigetfile('.mat','Please select the exportmat file from Step one (AllAutomatedNeuronsWithoutType54)','MultiSelect','off');
if isempty(fileR) || FilterIndexex==0
    errordlg('No file selected','Warning')
    return
end
handles.fileExportmat=fileExportmat;
handles.pathExportmat=pathExportmat;
handles.cellData=importdata(fullfile(pathExportmat,fileExportmat));

prompt='Please specify a folder (path) to save the figures: ';

Savepath_S2=input(prompt,'s');
if isempty(Savepath_S2)
    errordlg('No path selected','Warning')
    return
end
handles.Savepath_S2=Savepath_S2;
guidata(hObject, handles);
end %

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

for k=1:size(handles.cellData,1)
    handles.activeCell=handles.cellData(k,:);
    handles.k=k;
    guidata(hObject, handles);
    set(handles.edit_nameTimeseries,'string',handles.cellData{k,1}(1,2))
    desstr=handles.cellData{k,1}(1,2); %find appropriate R file matching current neuron
    desstrqry=desstr{1,1}(1:12);
    for sk=1:size(handles.fileR,2)
        rRL=handles.fileR{1,sk};
        if strcmpi(rRL(1:12),desstrqry)
            handles.desRfile=importdata(fullfile(handles.pathR,handles.fileR{1,sk}));
            set(handles.edit_nameR,'string',handles.fileR{1,sk})
        end
    end
    strtime=cell2mat(get(handles.edit_nameTimeseries,'String'));
    strR=get(handles.edit_nameR,'String');
    if strcmp(strtime(1:12),strR(1:12))==0
        errordlg('R file and timeseries name do not match','Error')
        FORCEDERROR
    end
    %possibility to only analysze a subset of neurons based on initial ROI
    %seleciton correlation or spatial location (keep as it is for all
    %neurons)
    if (handles.activeCell{1,2}<=handles.right) && (handles.activeCell{1,2}>=handles.left) && ...% left/right
            (handles.activeCell{1,3}<=handles.rostral) && (handles.activeCell{1,3}>=handles.caudal) && ...% rostral/caudal
            (handles.activeCell{1,4}<=handles.dorsal) && (handles.activeCell{1,4}>=handles.ventral) && ...%% ventral/dorsal
            (abs(handles.activeCell{1, 9} (1,handles.edit_inReg))>=handles.edit_inVal) && ...% inclusion regressor
            (abs(handles.activeCell{1, 9} (1,handles.edit_exReg1))<=handles.edit_exVal1) && ...% exclusion regressor 1
            (abs(handles.activeCell{1, 9} (1,handles.edit_exReg2))<=handles.edit_exVal2) % exclusion regressor 1
        out=handles;
        
        %analysis code here
        [exportmatOutput, Successcrit]=MonoBinofig(out,k);
        
        if Successcrit==1
            if ~exist('exportmat','var')
                exportmat=exportmatOutput;
            else
                exportmat(end+1,:)=exportmatOutput;
            end
        elseif Successcrit==0
            if ~exist('exportmatExcluded','var')
                exportmatExcluded=exportmatOutput;
            else
                exportmatExcluded(end+1,:)=exportmatOutput;
            end
        else
            FORCEDERROR
        end 
    end
    clear desstrqry desstr handles.desRfile
   
    if k==size(handles.cellData,1)
        msgbox('batch mode finished','Finished')
    end
end
% save final data
save(fullfile(handles.Savepath_S2,strcat('AutomatedRegressorRevised.mat')),'exportmat')
save(fullfile(handles.Savepath_S2,strcat('AutomatedRegressorExcluded.mat')),'exportmatExcluded')
end %



function edit_inVal_Callback(hObject, eventdata, handles)
% hObject    handle to edit_inVal (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.edit_inVal=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_inVal as text
%        str2double(get(hObject,'String')) returns contents of edit_inVal as a double
end%

% --- Executes during object creation, after setting all properties.
function edit_inVal_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_inVal (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
end%


function edit_exVal1_Callback(hObject, eventdata, handles)
% hObject    handle to edit_exVal1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.edit_exVal1=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_exVal1 as text
%        str2double(get(hObject,'String')) returns contents of edit_exVal1 as a double
end%

% --- Executes during object creation, after setting all properties.
function edit_exVal1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_exVal1 (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
end%


function edit_exVal2_Callback(hObject, eventdata, handles)
% hObject    handle to edit_exVal2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.edit_exVal2=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_exVal2 as text
%        str2double(get(hObject,'String')) returns contents of edit_exVal2 as a double
end%

% --- Executes during object creation, after setting all properties.
function edit_exVal2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_exVal2 (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
end%


function edit_inReg_Callback(hObject, eventdata, handles)
% hObject    handle to edit_inReg (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.edit_inReg=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_inReg as text
%        str2double(get(hObject,'String')) returns contents of edit_inReg as a double
end%

% --- Executes during object creation, after setting all properties.
function edit_inReg_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_inReg (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
end%


function edit_exReg1_Callback(hObject, eventdata, handles)
% hObject    handle to edit_exReg1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.edit_exReg1=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_exReg1 as text
%        str2double(get(hObject,'String')) returns contents of edit_exReg1 as a double
end%

% --- Executes during object creation, after setting all properties.
function edit_exReg1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_exReg1 (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
end%


function edit_exReg2_Callback(hObject, eventdata, handles)
% hObject    handle to edit_exReg2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.edit_exReg2=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_exReg2 as text
%        str2double(get(hObject,'String')) returns contents of edit_exReg2 as a double
end%

% --- Executes during object creation, after setting all properties.
function edit_exReg2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_exReg2 (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
end%


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

%Load data
[fileS1R, pathS1R, FilterIndex]=uigetfile('.mat','Please select the appropriate R file(s)','MultiSelect','on');
if isempty(fileS1R) || FilterIndex==0
    errordlg('No file selected','Warning')
    return
end
fileS1R=cellstr(fileS1R); %to run size command when only one file is loaded
handles.fileS1R=fileS1R;
handles.pathS1R=pathS1R;

[fileS1Exportmat, pathS1Exportmat, FilterIndexex]=uigetfile('.mat','Please select the appropriate exportmat file(s)','MultiSelect','on');
if isempty(fileS1Exportmat) || FilterIndexex==0
    errordlg('No file selected','Warning')
    return
end

fileS1Exportmat=cellstr(fileS1Exportmat); %to run size command when only one file is loaded
handles.fileS1Exportmat=fileS1Exportmat;
handles.pathS1Exportmat=pathS1Exportmat;

if size(fileS1Exportmat,2)~=size(fileS1R,2)
    errordlg('Loaded different amount of R and Exportmat files','Warning')
end

prompt='Please specify a folder (path) to save the figures: ';
savestr=input(prompt,'s');

if isempty(savestr)
    errordlg('No save path selected','Warning')
    return
end


handles.savestr=savestr;

guidata(hObject, handles);

end%



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

% --- Executes during object creation, after setting all properties.
function edit_S1ExpStr_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_S1ExpStr (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
end%


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

% --- Executes during object creation, after setting all properties.
function edit_S1RStr_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_S1RStr (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
end%


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

for S1k=1:size(handles.fileS1Exportmat,2) %cycle through all loaded exportmat files
    currentS1Exportmat=importdata(fullfile(handles.pathS1Exportmat,handles.fileS1Exportmat{1, S1k})); %load current exportmat
    set(handles.edit_S1ExpStr,'string',currentS1Exportmat{1,1}(1,2))
    
    % find respective R file
    desS1str=currentS1Exportmat{1,1}(1,2);
    desS1strqry=desS1str{1,1}(1:12);
    S1Rrunning=0;%to check if there are more than 1 matching file
    for S1Rk=1:size(handles.fileS1R,2)
        currRstr=handles.fileS1R{1, S1Rk};
        currRqry=currRstr(1:12);
        if strcmpi(desS1strqry,currRqry) %check if first 12 file characters match
            currentS1R=importdata(fullfile(handles.pathS1R,handles.fileS1R{1, S1Rk}));
            S1Rrunning=S1Rrunning+1; %to check if there are more than 1 matching file
            set(handles.edit_S1RStr,'string',handles.fileS1R{1, S1Rk})
        end
    end
    if S1Rrunning~=1
        errordlg('There are more than one or none possible matching R files','Warning')
        FORCEDERROR
    end
    savefornoNeuron=0; %variable which checks that one figure is not plotted when exclusion criteria omit all neurons in one exportmat file
    
    %cycle through all the ROIs in one ExportmatFile
    for ek=1:size(currentS1Exportmat,1)
        currentS1ROI=currentS1Exportmat(ek,:);
    %exclude if regressor/spatial position do not match specified range (leave as it is to analyze all ROIs)  
      if (currentS1ROI{1,2}<=handles.right) && (currentS1ROI{1,2}>=handles.left) && ...% left/right
            (currentS1ROI{1,3}<=handles.rostral) && (currentS1ROI{1,3}>=handles.caudal) && ...% rostral/caudal
            (currentS1ROI{1,4}<=handles.dorsal) && (currentS1ROI{1,4}>=handles.ventral) && ...%% ventral/dorsal
            (abs(currentS1ROI{1, 9} (1,handles.edit_inReg))>=handles.edit_inVal) && ...% inclusion regressor
            (abs(currentS1ROI{1, 9} (1,handles.edit_exReg1))<=handles.edit_exVal1) && ...% exclusion regressor 1
            (abs(currentS1ROI{1, 9} (1,handles.edit_exReg2))<=handles.edit_exVal2) % exclusion regressor 1
        savefornoNeuron=savefornoNeuron+1;
        handles.currentS1ROI=currentS1ROI;
        handles.currentS1R=currentS1R;
        guidata(hObject, handles);
        out=handles;
        
        [ADDtoExportmat,temp2]=findCellTypeMBRectified(out,ek); %subfunction to identify if ROI will be used for MonoBino evaluation        
        
        % add otiginal cellnumber in exportmat file to output data
        ADDtoExportmat{1,1}(1,3)={ek};
        
        if exist('exportmat','var')
            exportmat(end+1,:)=ADDtoExportmat;
        else
            exportmat=ADDtoExportmat;
        end
        clear ADDtoExportmat
      end %check position and correlation
    end %all ROIs in current exportmat file
    
    if savefornoNeuron~=0
    disp('running......')
    S1VarFile(S1k).Name=currentS1Exportmat{1,1}{1,2};
    S1VarFile(S1k).S1Off=var(handles.currentS1R(1:299,3));
    S1VarFile(S1k).S2Off=var(handles.currentS1R(300:599,2));
    S1VarFile(S1k).S1On=var(handles.currentS1R(1:299,2));
    S1VarFile(S1k).S2On=var(handles.currentS1R(300:599,3));
    S1VarFile(S1k).OverallCorr=corr(handles.currentS1R(:,2),handles.currentS1R(:,3));
    end
    
    % Yoking Index
    LeLowVel=diff(handles.currentS1R(:,2));
    ReLowVel=diff(handles.currentS1R(:,3));
    SaccnrL=numel(find(LeLowVel>=10));
    SaccnrR=numel(find(ReLowVel>=10));
    LeLowVel(LeLowVel>=4 | LeLowVel<=-4,1)=0;
    ReLowVel(ReLowVel>=4 | ReLowVel<=-4,1)=0;
    for k=3:size(LeLowVel,1)-2 %kernel
        LeLowVel(k,1)=...
            (LeLowVel(k-2,1)*0.25+...
            LeLowVel(k-1,1)*0.5+...
            LeLowVel(k,1)+...
            LeLowVel(k+1,1)*0.5+...
            LeLowVel(k+2,1)*0.25)/2.5;
    end
    
    for k=3:size(ReLowVel,1)-2 %kernel
        ReLowVel(k,1)=...
            (ReLowVel(k-2,1)*0.25+...
            ReLowVel(k-1,1)*0.5+...
            ReLowVel(k,1)+...
            ReLowVel(k+1,1)*0.5+...
            ReLowVel(k+2,1)*0.25)/2.5;
    end
    LeAI=(sum(abs(LeLowVel(1:299,1)))-sum(abs(ReLowVel(1:299,1))))/(sum(abs(LeLowVel(1:299,1)))+sum(abs(ReLowVel(1:299,1)))); %YI LE
    ReAI=(sum(abs(ReLowVel(300:599,1)))-sum(abs(LeLowVel(300:599,1))))/(sum(abs(ReLowVel(300:599,1)))+sum(abs(LeLowVel(300:599,1)))); %YI RE
    BeAI=(sum(abs(ReLowVel(599:end,1)))-sum(abs(LeLowVel(599:end,1))))/(sum(abs(ReLowVel(599:end,1)))+sum(abs(LeLowVel(599:end,1)))); %YI BE    
    S1VarFile(S1k).LeAI=LeAI;
    S1VarFile(S1k).ReAI=ReAI;
    S1VarFile(S1k).BeAI=BeAI;
    S1VarFile(S1k).SaccL=SaccnrL;
    S1VarFile(S1k).SaccR=SaccnrR;
end %all loaded exportmat files

save(fullfile(handles.savestr,'S1VarFile'),'S1VarFile')

% Here the best fitting regressor in all processed neurons is determined
% overwrite column 67 with indedx of highest scoring regressor


if handles.check_manualCell==0
    for wfok=1:size(exportmat,1)
        if max(cell2mat(exportmat(wfok,14:66)))>handles.RegThres %only if at least min correlation value
            exportmat(wfok,67)={find(cell2mat(exportmat(wfok,14:66))==max(cell2mat(exportmat(wfok,14:66))))};
        else
            exportmat(wfok,67)={54}; % identifier to trash neuron
        end
    end 
end


saveexportmat=exportmat;

try
tempsaveRegressor=sortrows(exportmat,67);  
catch
    disp('breakpoint')
end

tempbar=zeros(1,54);
%save data for each regressor
for celltyperunning=1:54
    saveindices=find(cell2mat(tempsaveRegressor(:,67))==celltyperunning);
        if isempty(saveindices)==0
            exportmat=cell(length(saveindices),12);
            exportmat=tempsaveRegressor(saveindices(1):saveindices(end),1:12);
              save(fullfile(handles.savestr,strcat('AutomatedRegressor',num2str(celltyperunning),'.mat')),...
              'exportmat')
          clear exportmat
        end  
        tempbar(1,celltyperunning)=length(saveindices);
end

save(fullfile(handles.savestr,'NewRegressorRaw.mat'),'saveexportmat') %save all data in one file
tempsaveRegressor(find(cell2mat(tempsaveRegressor(:,67))==54),:)=[];
exportmat=tempsaveRegressor;
save(fullfile(handles.savestr,'AllAutomatedNeuronsWithoutType54.mat'),'exportmat') %only identified neurons with min correlation; used in step 2
          
figure(932)
bar(tempbar)
title('Neuron type distribution according to automated classification'), xlabel('neurons type'), ylabel('# of cells')
saveas(932,fullfile(handles.savestr,'SummaryofNeuronTypes'),'tif')
saveas(932,fullfile(handles.savestr,'SummaryofNeuronTypes'),'fig')
disp('finished')
end%



function edit_SLE_Callback(hObject, eventdata, handles)
% hObject    handle to edit_SLE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.edit_SLE=get(hObject,'String');
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_SLE as text
%        str2double(get(hObject,'String')) returns contents of edit_SLE as a double
end

% --- Executes during object creation, after setting all properties.
function edit_SLE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_SLE (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
end


function edit_SRE_Callback(hObject, eventdata, handles)
% hObject    handle to edit_SRE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.edit_SRE=get(hObject,'String');
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_SRE as text
%        str2double(get(hObject,'String')) returns contents of edit_SRE as a double
end

% --- Executes during object creation, after setting all properties.
function edit_SRE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_SRE (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
end


function edit_SBE_Callback(hObject, eventdata, handles)
% hObject    handle to edit_SBE (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.edit_SBE=get(hObject,'String');
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_SBE as text
%        str2double(get(hObject,'String')) returns contents of edit_SBE as a double
end

% --- Executes during object creation, after setting all properties.
function edit_SBE_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_SBE (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
end


% --- Executes on button press in check_manualCell.
function check_manualCell_Callback(hObject, eventdata, handles)
% hObject    handle to check_manualCell (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.check_manualCell=get(hObject,'Value');
guidata(hObject, handles);
% Hint: get(hObject,'Value') returns toggle state of check_manualCell
end



function edit_tau_Callback(hObject, eventdata, handles)
% hObject    handle to edit_tau (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.tau=get(hObject,'String');
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_tau as text
%        str2double(get(hObject,'String')) returns contents of edit_tau as a double
end

% --- Executes during object creation, after setting all properties.
function edit_tau_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_tau (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
end


function edit_frameTime_Callback(hObject, eventdata, handles)
% hObject    handle to edit_frameTime (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.frameTime=get(hObject,'String');
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_frameTime as text
%        str2double(get(hObject,'String')) returns contents of edit_frameTime as a double
end

% --- Executes during object creation, after setting all properties.
function edit_frameTime_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_frameTime (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
end



function edit_RegThres_Callback(hObject, eventdata, handles)
% hObject    handle to edit_RegThres (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.RegThres=str2double(get(hObject,'String'));
guidata(hObject, handles);
% Hints: get(hObject,'String') returns contents of edit_RegThres as text
%        str2double(get(hObject,'String')) returns contents of edit_RegThres as a double
end

% --- Executes during object creation, after setting all properties.
function edit_RegThres_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_RegThres (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
end


