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

% Last Modified by GUIDE v2.5 10-Sep-2015 09:41:09

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @Autonomate_OpeningFcn, ...
    'gui_OutputFcn',  @Autonomate_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 Autonomate is made visible.
function Autonomate_OpeningFcn(hObject, eventdata, handles, varargin)

handles.emoToggle = 0;

%Set default analysis parameter values
handles.deltaSlope = .0002;
handles.contPoints = 0.7;
handles.Interval = 25;  %Down-sampling factor
handles.buffLength = 0.125;
handles.Window = 3;
handles.startWindow = 0.8;
handles.finishWindow = 4.2;
handles.postSeconds = 5;
handles.maxUps = 8;
handles.doSF = 0;
handles.doSCL=0;
handles.SR=200;
handles.up_select = 'largest';

set(handles.edt_deltaSlope, 'String', handles.deltaSlope);
set(handles.edt_contPoints, 'String', handles.contPoints);
set(handles.edt_Interval, 'String', handles.Interval);
set(handles.edt_buffLength, 'String', handles.buffLength);
set(handles.edt_Window, 'String', handles.Window);
set(handles.edt_startWindow, 'String', handles.startWindow);
set(handles.edt_finishWindow, 'String', handles.finishWindow);
set(handles.edt_postSeconds, 'String', handles.postSeconds);
set(handles.edt_maxUps, 'String', handles.maxUps);
set(handles.SRedit, 'String', handles.SR);

handles.eventChannel = 1;
handles.dataChannel = 1;
handles.includeRow = 0;
handles.analysis = 0;
handles.files = 0;   %an integer corresponding to the number of GSR input files loaded
handles.dataSet = 1;

set(handles.lst_eventList_Values, 'String', 'No Event Values')
handles.includeList_Display{1} = 'No Selected Events';
set(handles.lst_includeList, 'String', handles.includeList_Display);

handles.output = hObject;

%If GUI is larger than the screen size, shrink it a bit and turn scroll
%bars on

%Get information about the screen dimensions
set(0,'units','characters');  %Make sure the info is coming back in characters, to match the GUI
screen = get(0,'screensize');
screen_height = screen(4);
screen_width = screen(3);

%Get information about the size of the GUI
gui_pos_init = get(handles.gui_loadGSR, 'OuterPosition');
gui_height_init = gui_pos_init(4);
gui_width_init = gui_pos_init(3);

%If the GUI is longer or wider than the screen on which it is to be
%displayed, shrink it and make the scroll bars visible.
if ((gui_height_init+5 >= screen_height) | (gui_width_init+10 >= screen_width))
    set(handles.gui_loadGSR, 'Units', 'Normalized', 'OuterPosition', [0.05 0.05 0.9 0.9]);
    set(handles.SliderVert, 'Visible', 'on');
    set(handles.SliderHoriz, 'Visible', 'on');
else
    %If GUI will fit nicely on the screen, make it appear 5 character heights
    %from the top of the screen and 10 character widths from the left
    gui_y_new = (screen_height-5) - gui_height_init;
    set(handles.gui_loadGSR, 'OuterPosition', [10 gui_y_new gui_width_init gui_height_init]);
    %Turn off scroll bars, as they will not be needed
    set(handles.SliderVert, 'Visible', 'off');
    set(handles.SliderHoriz, 'Visible', 'off');
    set(handles.text72, 'Visible', 'off');
    set(handles.text73, 'Visible', 'off');
end

%Set the position of panel elements so the top ones match up with the top
%of the GUI window (Matlab counts from bottom to top by default, which will
%cause the position of all GUI elements to cue off the bottom of the GUI.
%This looks weird when the top GUI elements are visible but the bottom ones
%are not).

% Get the position of the main GUI in characters (it may be in 'Normalized'
% at this point)
main_gui_units = get(handles.gui_loadGSR, 'Units');
set(handles.gui_loadGSR, 'Units', 'Characters');
gui_pos_set = get(handles.gui_loadGSR, 'Position');
handles.gui_pos_set = gui_pos_set;
set(handles.gui_loadGSR, 'Units', main_gui_units);

uipanel1_pos = get(handles.uipanel1, 'Position');
uipanel1_pos(1) = 4.2;
uipanel1_pos(2) = gui_pos_set(4)-uipanel1_pos(4);
set(handles.uipanel1, 'Position', uipanel1_pos);
handles.uipanel1_pos = uipanel1_pos;

pan_chan_pos = get(handles.pan_Channels, 'Position');
pan_chan_pos(2) = uipanel1_pos(2)-pan_chan_pos(4);
pan_chan_pos(1) = uipanel1_pos(1);
set(handles.pan_Channels, 'Position', pan_chan_pos);
handles.pan_chan_pos = pan_chan_pos;

pan_events_pos = get(handles.pan_specifyEvents, 'Position');
pan_events_pos(2) = gui_pos_set(4)-pan_events_pos(4);
pan_events_pos(1) = uipanel1_pos(1)+uipanel1_pos(3);
set(handles.pan_specifyEvents, 'Position', pan_events_pos);
handles.pan_events_pos = pan_events_pos;

pan_gsr_pos = get(handles.pan_analyzeGSR, 'Position');
pan_gsr_pos(2) = pan_events_pos(2)-pan_gsr_pos(4);
pan_gsr_pos(1) = pan_events_pos(1);
set(handles.pan_analyzeGSR, 'Position', pan_gsr_pos);
handles.pan_gsr_pos = pan_gsr_pos;

pan_an_pos = get(handles.pan_analyses, 'Position');
pan_an_pos(2) = pan_gsr_pos(2)-pan_an_pos(4);
pan_an_pos(1) = pan_gsr_pos(1);
set(handles.pan_analyses, 'Position', pan_an_pos);
handles.pan_an_pos = pan_an_pos;

text_pos = get(handles.text41, 'Position');
text_pos(2) = pan_an_pos(2)-text_pos(4);
set(handles.text41, 'Position', text_pos);
handles.text_pos = text_pos;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Autonomate wait for user response (see UIRESUME)
% uiwait(handles.gui_loadGSR);


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


% --- Executes on button press in bttn_File.
function bttn_File_Callback(hObject, eventdata, handles)

if isempty(get(handles.edt_fullPath, 'String')) == 1
    
    [fileName, filePath] = uigetfile({'*.acq';'*.txt'}, 'Select Data File');
    
    if length([fileName filePath]) == 2 %No file was selected
        disp('No file selected in Browse window...')
        return
    else
        handles.fullPath = strcat(filePath, fileName);
        [filePath, fileName, extension] = fileparts(handles.fullPath);
        handles.files = 1;
        handles.dataSets{1,1} = fileName;
        handles.dataSets{1,2} = handles.fullPath;


        set(handles.edt_fullPath, 'String', handles.fullPath)
    end
    
else
    
    [filePath, fileName, extension] = fileparts(handles.fullPath);
    handles.fullPath = get(handles.edt_fullPath, 'String');
    handles.files = 1;
    handles.dataSets{1,1} = fileName;
    handles.dataSets{1,2} = handles.fullPath;
    
    
    set(handles.txt_filePath, 'String', strcat(fileName));
    set(handles.edt_fullPath, 'String', '');
    
end


if exist(handles.fullPath) == 2
    
    
    set(handles.txt_filePath, 'String', strcat(fileName));
    set(handles.edt_fullPath, 'String', '');
    
    
    set(handles.txt_Status_load, 'String', 'Loading...');
    set(handles.txt_Status_load, 'ForegroundColor', [.667, .133, .133]);
    drawnow;
    
    %     [handles.header handles.data] = acqread(handles.dataSets{1,2});
   
    if strcmp(handles.dataSets{1,2}(end-3:end),'.acq')
    acq=load_acq(handles.dataSets{1,2});
    elseif strcmp(handles.dataSets{1,2}(end-3:end),'.txt')
    acq.data=importdata(handles.dataSets{1,2});       
    end
    
    for c=1:size(acq.data,2)
        handles.data{c}=acq.data(:,c);
    end
    
    handles.dataSets{1,3} = handles.data;
%     handles.dataSets{1,4} = acq.hdr;
    
    set(handles.txt_Status_load, 'String', 'Finished');
    set(handles.txt_Status_load, 'ForegroundColor', [.0, .502, .0]);
    drawnow;
    
    set(handles.pan_Channels, 'Visible', 'On')
    
    handles.channels = size(handles.data,2);
    set(handles.txt_totalChannels, 'String', handles.channels);
    
    set(handles.popM_channelList_Data, 'String', 1:handles.channels)
    set(handles.popM_channelList_Event, 'String', 1:handles.channels)
    
    Index=min(handles.files);
    %  SF=handles.dataSets{Index,4}.dAmplScale(handles.dataChannel);
    %  %temporary fix for very small scale factor on newer acq files
    %     if (SF-3.0518e-004)<.000000001 | SF <.00001 %| (SF-.0031)<.0000001
    %         SF=1;
    %     end
    
    
    axes(handles.axe_dataChannel);
    plot(double(handles.data{handles.dataChannel}));
    axes(handles.axe_eventChannel);
    plot(handles.data{handles.eventChannel});
    
else
end


guidata(hObject, handles);


function txt_fullPath_Callback(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function txt_fullPath_CreateFcn(hObject, eventdata, handles)

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







guidata(hObject, handles);




function popM_channelList_Data_Callback(hObject, eventdata, handles)
Index=min(handles.files);
val = get(hObject,'Value');
handles.dataChannel = val;

%  SF=handles.dataSets{Index,4}.dAmplScale(handles.dataChannel);
%  %temporary fix for very small scale factor on newer acq files
%     if (SF-3.0518e-004)<.000000001 | SF <.00001 %| (SF-.0031)<.0000001
%         SF=1;
%     end


axes(handles.axe_dataChannel);
plot(double(handles.data{handles.dataChannel}));
axes(handles.axe_eventChannel);
plot(handles.data{handles.eventChannel});

guidata(hObject, handles);


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



function popM_channelList_Event_Callback(hObject, eventdata, handles)
% Index=min(handles.files);
val = get(hObject,'Value');
handles.eventChannel = val;

axes(handles.axe_dataChannel);
plot(double(handles.dataSets{1,3}{handles.dataChannel}));
axes(handles.axe_eventChannel);
plot(handles.dataSets{1,3}{handles.eventChannel});


guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function popM_channelList_Event_CreateFcn(hObject, eventdata, handles)

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




% --- Executes on button press in bttn_extractData.
function bttn_extractData_Callback(hObject, eventdata, handles)


set(handles.txt_statusExtract, 'String', 'Loading...');
set(handles.txt_statusExtract, 'ForegroundColor', [.667, .133, .133]);
drawnow;

for Index = 1:handles.files
    
    handles.dataSets{Index,5} = double(handles.dataSets{Index,3}{handles.dataChannel});
    handles.dataSets{Index,6} = double(handles.dataSets{Index,3}{handles.eventChannel});
    
    
    if handles.emoToggle == 1
        
        handles.dataSets{Index,5} = handles.dataSets{Index,5}.*10;
    end
    
end

set(handles.txt_statusExtract, 'String', 'Finished');
set(handles.txt_statusExtract, 'ForegroundColor', [.0, .502, .0]);
drawnow;

handles.numValues = unique(handles.dataSets{handles.dataSet,6});

for Index = 1:size(handles.numValues,1)
    
    handles.eventValues{Index} = handles.numValues(Index);
    
    
end


set(handles.lst_eventList_Values, 'String', handles.eventValues);
set(handles.pan_specifyEvents, 'Visible', 'On');

handles.event = 1;

guidata(hObject, handles);



% --- Executes on selection change in lst_includeList_eventList_raw.
function lst_includeList_eventList_raw_Callback(hObject, eventdata, handles)
% hObject    handle to lst_includeList_eventList_raw (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 lst_includeList_eventList_raw contents as cell array
%        contents{get(hObject,'Value')} returns selected item from lst_includeList_eventList_raw


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

% Hint: listbox 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 listbox3.
function listbox3_Callback(hObject, eventdata, handles)
% hObject    handle to listbox3 (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 listbox3 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox3


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

% Hint: listbox 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 bttn_includeEvent.
function bttn_includeEvent_Callback(hObject, eventdata, handles)

set(handles.txt_eventName, 'Visible', 'On')
set(handles.edt_eventName, 'Visible', 'On')
set(handles.bttn_addEvent, 'Visible', 'On')

guidata(hObject, handles);

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


% --- Executes on selection change in lst_includeList.
function lst_includeList_Callback(hObject, eventdata, handles)
% hObject    handle to lst_includeList (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 lst_includeList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from lst_includeList


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

% Hint: listbox 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 lst_eventList_Values.
function lst_eventList_Values_Callback(hObject, eventdata, handles)

val = get(hObject,'Value');
handles.event = val;

guidata(hObject, handles);

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

% Hint: listbox 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 edt_eventName_Callback(hObject, eventdata, handles)

guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function edt_eventName_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_eventName (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 key press over edt_eventName with no controls selected.
function edt_eventName_KeyPressFcn(hObject, eventdata, handles)
% hObject    handle to edt_eventName (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)




% --- Executes on button press in bttn_acceptEvents.
function bttn_acceptEvents_Callback(hObject, eventdata, handles)

set(handles.pan_analyzeGSR, 'Visible', 'On');
set(handles.pan_analyzeArguments, 'Visible', 'On');
set(handles.popM_eventAnalyze, 'String', handles.includeList(:,1));


guidata(hObject, handles);

% --- Executes on button press in bttn_resetEvents.
function bttn_resetEvents_Callback(hObject, eventdata, handles)

handles.includeRow = 0;
handles.includeList = {};
handles.includeList_Display = {};

handles.includeList_Display{1} = 'No Selected Events';

set(handles.lst_includeList, 'Value', 1);
set(handles.lst_includeList, 'String', handles.includeList_Display);
set(handles.edt_eventName, 'String', '');
set(handles.txt_eventName, 'Visible', 'Off');
set(handles.edt_eventName, 'Visible', 'Off');
set(handles.bttn_acceptEvents, 'Visible', 'Off');
set(handles.bttn_resetEvents, 'Visible', 'Off');


guidata(hObject, handles);


% --- Executes on selection change in popM_eventAnalyze.
function popM_eventAnalyze_Callback(hObject, eventdata, handles)

val = get(hObject,'Value');
handles.event = val;

set(handles.bttn_analyzeGSR, 'Visible', 'On');
set(handles.edt_analysisName, 'Visible', 'On');
set(handles.txt_nameInstruct, 'Visible', 'On');
set(handles.txt_totalSetsAnalyzed, 'String', handles.files);
set(handles.txt_setsAnalyzed, 'String', 0);

set(handles.edt_analysisName, 'String', 'Default');

guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function popM_eventAnalyze_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popM_eventAnalyze (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 checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)

val = get(hObject,'Value');
handles.argumentToggle = val;

if handles.argumentToggle == 1
    
    if get(handles.SCL, 'Value') == 0
        %Only turn on if SCL is not selected
        set(handles.edt_deltaSlope, 'Enable', 'On');
        set(handles.edt_contPoints, 'Enable', 'On');
        set(handles.edt_buffLength, 'Enable', 'On');
        set(handles.edt_postSeconds, 'Enable', 'On');
        if get(handles.NSR, 'Value') == 0
            set(handles.edt_maxUps, 'Enable', 'On');
        end
    end
    
    set(handles.edt_startWindow, 'Enable', 'On');
    set(handles.edt_finishWindow, 'Enable', 'On');
    set(handles.edt_Interval, 'Enable', 'On');
    if get(handles.NSR, 'Value') == 0
        set(handles.edt_Window, 'Enable', 'On');
    end
    set(handles.SRedit, 'Enable', 'On');

else
    
    set(handles.edt_deltaSlope, 'Enable', 'Off');
    set(handles.edt_contPoints, 'Enable', 'Off');
    set(handles.edt_Interval, 'Enable', 'Off');
    set(handles.edt_buffLength, 'Enable', 'Off');
    set(handles.edt_Window, 'Enable', 'Off');
    set(handles.edt_startWindow, 'Enable', 'Off');
    set(handles.edt_finishWindow, 'Enable', 'Off');
    set(handles.edt_postSeconds, 'Enable', 'Off');
    set(handles.edt_maxUps, 'Enable', 'Off');
    set(handles.SRedit, 'Enable', 'Off');
    
end

guidata(hObject, handles);


% Hint: get(hObject,'Value') returns toggle state of checkbox1



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


% --- Executes during object creation, after setting all properties.
function edt_deltaSlope_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_deltaSlope (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 edt_buffLength_Callback(hObject, eventdata, handles)
% hObject    handle to edt_buffLength (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 edt_buffLength as text
%        str2double(get(hObject,'String')) returns contents of edt_buffLength as a double


% --- Executes during object creation, after setting all properties.
function edt_buffLength_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_buffLength (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 edt_window_Callback(hObject, eventdata, handles)
% hObject    handle to edt_window (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 edt_window as text
%        str2double(get(hObject,'String')) returns contents of edt_window as a double


% --- Executes during object creation, after setting all properties.
function edt_window_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_window (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 edt_Interval_Callback(hObject, eventdata, handles)
% hObject    handle to edt_Interval (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 edt_Interval as text
%        str2double(get(hObject,'String')) returns contents of edt_Interval as a double


% --- Executes during object creation, after setting all properties.
function edt_Interval_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_Interval (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 edt_contPoints_Callback(hObject, eventdata, handles)
% hObject    handle to edt_contPoints (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 edt_contPoints as text
%        str2double(get(hObject,'String')) returns contents of edt_contPoints as a double


% --- Executes during object creation, after setting all properties.
function edt_contPoints_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_contPoints (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 edt_startWindow_Callback(hObject, eventdata, handles)
% hObject    handle to edt_startWindow (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 edt_startWindow as text
%        str2double(get(hObject,'String')) returns contents of edt_startWindow as a double


% --- Executes during object creation, after setting all properties.
function edt_startWindow_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_startWindow (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 edt_finishWindow_Callback(hObject, eventdata, handles)
% hObject    handle to edt_finishWindow (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 edt_finishWindow as text
%        str2double(get(hObject,'String')) returns contents of edt_finishWindow as a double


% --- Executes during object creation, after setting all properties.
function edt_finishWindow_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_finishWindow (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 edt_postSeconds_Callback(hObject, eventdata, handles)
% hObject    handle to edt_postSeconds (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 edt_postSeconds as text
%        str2double(get(hObject,'String')) returns contents of edt_postSeconds as a double


% --- Executes during object creation, after setting all properties.
function edt_postSeconds_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_postSeconds (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 edt_Window_Callback(hObject, eventdata, handles)
% hObject    handle to edt_Window (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 edt_Window as text
%        str2double(get(hObject,'String')) returns contents of edt_Window as a double


% --- Executes during object creation, after setting all properties.
function edt_Window_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_Window (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 button press in bttn_addEvent.
function bttn_addEvent_Callback(hObject, eventdata, handles)

handles.includeRow = handles.includeRow + 1;

handles.includeList{handles.includeRow,1} = get(handles.edt_eventName, 'String');

temp = [];

for Index = 1:size(handles.event,2)
    temp = [temp handles.eventValues{handles.event(Index)}];
end

handles.includeList{handles.includeRow,2} = temp;

handles.includeList_Display{handles.includeRow} = strcat('(', num2str(handles.includeList{handles.includeRow, 2}), ')', handles.includeList{handles.includeRow,1});

set(handles.lst_includeList, 'String', handles.includeList_Display);
set(handles.edt_eventName, 'String', '');
set(handles.txt_eventName, 'Visible', 'Off');
set(handles.edt_eventName, 'Visible', 'Off');
set(handles.bttn_addEvent, 'Visible', 'Off');
set(handles.bttn_acceptEvents, 'Visible', 'On');
set(handles.bttn_resetEvents, 'Visible', 'On');

guidata(hObject, handles);


% --- Executes on button press in bttn_analyzeGSR.
function bttn_analyzeGSR_Callback(hObject, eventdata, handles)

set(handles.txt_statusAnalyze, 'String', 'Analyzing...');
set(handles.txt_statusAnalyze, 'ForegroundColor', [.667, .133, .133]);
drawnow;

handles.deltaSlope = str2num(get(handles.edt_deltaSlope, 'String'));
handles.contPoints = str2num(get(handles.edt_contPoints, 'String'));
handles.Interval = str2num(get(handles.edt_Interval, 'String'));
handles.buffLength = str2num(get(handles.edt_buffLength, 'String'));
handles.Window= str2num(get(handles.edt_Window, 'String'));
handles.startWindow = str2num(get(handles.edt_startWindow, 'String'));
handles.finishWindow = str2num(get(handles.edt_finishWindow, 'String'));
handles.postSeconds = str2num(get(handles.edt_postSeconds, 'String'));
handles.SR = str2num(get(handles.SRedit, 'String'));
handles.maxUps = str2num(get(handles.edt_maxUps, 'String'));

handles.sectosamp = handles.SR / handles.Interval;
handles.samptosec = handles.Interval / handles.SR;

for Index = 1:handles.files  %For each GSR input file...
    
    %Determine time indices of when user-specified events occurred
    handles.eventTable = findEvents(handles.dataSets{Index,6}, handles.includeList{handles.event,1}, handles.includeList{handles.event,2});
    %Apply the various criteria to determine if there was a significant
    %response to the events
    handles.gsrStruct =  analyzeGSR(handles.dataSets{Index,5}, handles.eventTable, handles.deltaSlope, handles.buffLength, handles.Window, ...
        handles.Interval, handles.contPoints, handles.startWindow, handles.finishWindow, handles.postSeconds,  handles.maxUps, handles.dataSets(Index,1), ...
        handles.eventTable(1).binLabel, get(handles.edt_analysisName, 'String'),handles.doSF,handles.SR,handles.doSCL,handles.up_select);
    
    handles.analysis = handles.analysis + 1;  %Add one to the count of analyses
    handles.analyses(handles.analysis) = struct('gsrStruct', handles.gsrStruct);
    handles.analysisNames{handles.analysis} = strcat(get(handles.edt_analysisName, 'String'), '_', handles.gsrStruct.analysisArguments.EventName, ...
        '_',handles.dataSets{Index,1});
    handles.analyses(handles.analysis).gsrStruct.analysisArguments.doSF=handles.doSF;     handles.analyses(handles.analysis).gsrStruct.analysisArguments.doSCL=handles.doSCL;
    set(handles.txt_setsAnalyzed, 'String', Index);
    drawnow;
    
end

set(handles.txt_statusAnalyze, 'String', 'Finished');
set(handles.txt_statusAnalyze, 'ForegroundColor', [.0, .502, .0]);
drawnow;

set(handles.edt_analysisName, 'String', '');
set(handles.txt_viewData, 'String', handles.analysis);
set(handles.bttn_analyzeGSR, 'Visible', 'Off');
set(handles.bttn_viewData, 'Visible', 'On');
set(handles.lst_analyses, 'String', handles.analysisNames);
set(handles.pan_analyses, 'Visible', 'On');

set(handles.NSR, 'Enable', 'Off');
set(handles.SCR, 'Enable', 'Off');
set(handles.SCL, 'Enable', 'Off');

% gsrGUI(handles.gsrStruct);

guidata(hObject, handles);

%


% --- Executes on button press in bttn_viewData.
function bttn_viewData_Callback(hObject, eventdata, handles)

ViewResponses(handles.analyses, handles.analysisNames, handles.dataSets, handles.SR, handles.samptosec)




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


% --- Executes during object creation, after setting all properties.
function edt_analysisName_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_analysisName (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 edt_maxUps_Callback(hObject, eventdata, handles)
% hObject    handle to edt_maxUps (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 edt_maxUps as text
%        str2double(get(hObject,'String')) returns contents of edt_maxUps as a double


% --- Executes during object creation, after setting all properties.
function edt_maxUps_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edt_maxUps (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 lst_analyses.
function lst_analyses_Callback(hObject, eventdata, handles)




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

% Hint: listbox 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 lst_fileNames.
function lst_fileNames_Callback(hObject, eventdata, handles)
% hObject    handle to lst_fileNames (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 lst_fileNames contents as cell array
%        contents{get(hObject,'Value')} returns selected item from lst_fileNames


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

% Hint: listbox 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 bttn_addFile.
function bttn_addFile_Callback(hObject, eventdata, handles)

if isempty(get(handles.edt_fullPath, 'String')) == 1
    
    [fileName, filePath] = uigetfile({'*.acq';'*.txt'}, 'Select Data File');
    if length([fileName filePath]) == 2 %No file was selected
        disp('No file selected in Browse window...')
        return
    end
    handles.fullPath = strcat(filePath, fileName);
    set(handles.edt_fullPath, 'String', handles.fullPath)
    
else
    
    handles.fullPath = get(handles.edt_fullPath, 'String');
    
end


if exist(handles.fullPath) == 2
    
    [filePath, fileName, extension] = fileparts(handles.fullPath);
    set(handles.txt_filePath, 'String', strcat(fileName));
    set(handles.edt_fullPath, 'String', '');
    
    handles.files = handles.files + 1;
    handles.dataSets{handles.files,1} = fileName;
    handles.dataSets{handles.files,2} = handles.fullPath;
    set(handles.lst_fileNames, 'String', handles.dataSets(:,1));
    
    
    
    
else
end

set(handles.txt_totalFilesLoaded, 'String', handles.files);

guidata(hObject, handles);



% --- Executes on button press in chbx_batchAnalysis.
function chbx_batchAnalysis_Callback(hObject, eventdata, handles)

val = get(hObject,'Value');
handles.batchToggle = val;

if handles.batchToggle == 1
    
    set(handles.pan_batchAnalysis, 'Visible', 'On');
    
else
    
    set(handles.pan_batchAnalysis, 'Visible', 'Off');
    
end

guidata(hObject, handles);




% --- Executes on button press in bttn_loadFiles.
function bttn_loadFiles_Callback(hObject, eventdata, handles)

set(handles.txt_Status_load, 'String', 'Loading...');
set(handles.txt_Status_load, 'ForegroundColor', [.667, .133, .133]);
drawnow;

filesLoaded = 0;

for Index = 1:handles.files
    
    %     [handles.header handles.data] = acqread(handles.dataSets{Index,2});
    
    
    if strcmp(handles.dataSets{Index,2}(end-3:end),'.acq')
    acq=load_acq(handles.dataSets{Index,2});
    elseif strcmp(handles.dataSets{Index,2}(end-3:end),'.txt')
    acq.data=importdata(handles.dataSets{Index,2});       
    end
    
    handles.data={};
    
    for c=1:size(acq.data,2)
        handles.data{c}=acq.data(:,c);
    end
    
    
    handles.dataSets{Index,3} = handles.data;
    %     handles.dataSets{Index,4} = handles.header;
    
    filesLoaded = filesLoaded + 1;
    set(handles.txtFilesLoaded, 'String', filesLoaded);
    set(handles.txt_Status_load, 'ForegroundColor', [.69, .102, .102]);
    drawnow;
    
end


set(handles.txt_Status_load, 'String', 'Finished');
set(handles.txt_Status_load, 'ForegroundColor', [.0, .502, .0]);
drawnow;


set(handles.pan_Channels, 'Visible', 'On');

handles.channels = size(handles.dataSets{1,3},2);
set(handles.txt_totalChannels, 'String', handles.channels);

set(handles.popM_channelList_Data, 'String', 1:handles.channels);
set(handles.popM_channelList_Event, 'String', 1:handles.channels);


axes(handles.axe_dataChannel);
plot(handles.dataSets{1,3}{handles.dataChannel});
axes(handles.axe_eventChannel);
plot(handles.dataSets{1,3}{handles.eventChannel});


guidata(hObject, handles);


% --- Executes on button press in bttn_txtFile.
function bttn_txtFile_Callback(hObject, eventdata, handles)

[fileName, filePath] = uigetfile('*.txt', 'Select Batch Text File');

if length([fileName filePath]) == 2 %No file was selected
    disp('No file selected in Browse window...')
    return
end

fileNames = textread(strcat(filePath, fileName),'%s','delimiter','\n');


for Index = 1:size(fileNames,1)
    
    handles.fullPath = fileNames{Index};
    [filePath, fileName, extension] = fileparts(handles.fullPath);
    set(handles.txt_filePath, 'String', strcat(fileName));
    set(handles.edt_fullPath, 'String', '');
    
    handles.files = handles.files + 1;
    handles.dataSets{handles.files,1} = fileName;
    handles.dataSets{handles.files,2} = handles.fullPath;
    set(handles.lst_fileNames, 'String', handles.dataSets(:,1));
    
end

set(handles.txt_totalFilesLoaded, 'String', handles.files);

guidata(hObject, handles);


% --- Executes on button press in bttn_toExcel.
function bttn_toExcel_Callback(hObject, eventdata, handles)
handles.out={};
count = 0;
for Index = 1:size(handles.analyses,2)
    if isfield(handles.analyses(Index).gsrStruct,'Event')
        handles.spreadSheet{Index,1} = handles.analyses(Index).gsrStruct.analysisArguments.FileName;
        handles.spreadSheet{Index,2} = handles.analyses(Index).gsrStruct.analysisArguments.EventName;
        handles.spreadSheet{Index,3} = handles.analyses(Index).gsrStruct.analysisArguments.AnalysisName;
        
        if ~handles.analyses(Index).gsrStruct.analysisArguments.doSF;
            
            if ~handles.analyses(Index).gsrStruct.analysisArguments.doSCL
                handles.spreadSheet{Index,4} = t2pTable(handles.analyses(Index).gsrStruct);
            else
                handles.spreadSheet{Index,4} = t2pTableSCL(handles.analyses(Index).gsrStruct);
            end
            
        elseif handles.analyses(Index).gsrStruct.analysisArguments.doSF
            handles.spreadSheet{Index,4} = t2pTableSF(handles.analyses(Index).gsrStruct);
        end
    end
end

for Index = 1:size(handles.spreadSheet,1)
    temp = handles.spreadSheet{Index,4};
    eventIndex = 0;
    if ~handles.analyses(Index).gsrStruct.analysisArguments.doSCL
        for e=1:length(handles.analyses(Index).gsrStruct.Event)
            eventIndex= eventIndex +1;
            for u=1:length(handles.analyses(Index).gsrStruct.Event(e).Iteration(length(handles.analyses(Index).gsrStruct.Event(e).Iteration)).Ups)
                if  ~isempty(handles.analyses(Index).gsrStruct.Event(e).Iteration(length(handles.analyses(Index).gsrStruct.Event(e).Iteration)).Ups(u).p2p);
                    count = count+1;
                    handles.out{count,1} = handles.spreadSheet{Index,1};
                    handles.out{count,2} = handles.spreadSheet{Index,2};
                    handles.out{count,3} = handles.spreadSheet{Index,3};
                    handles.out{count,4} = num2str(eventIndex);
                    handles.out{count,5} = num2str(handles.analyses(Index).gsrStruct.Event(e).Iteration(length(handles.analyses(Index).gsrStruct.Event(e).Iteration)).Ups(u).p2p);
                    handles.out{count,6} = num2str(handles.analyses(Index).gsrStruct.Event(e).Iteration(length(handles.analyses(Index).gsrStruct.Event(e).Iteration)).Ups(u).Start*handles.Interval/handles.SR);
                    handles.out{count,7} = num2str(handles.analyses(Index).gsrStruct.Event(e).Iteration(length(handles.analyses(Index).gsrStruct.Event(e).Iteration)).Ups(u).Length*handles.Interval/handles.SR);
                end
            end
        end
    elseif handles.analyses(Index).gsrStruct.analysisArguments.doSCL
        for e=1:length(handles.analyses(Index).gsrStruct.Event)
            count = count  +1;
            handles.out{count,1} = handles.spreadSheet{Index,1};
            handles.out{count,2} = handles.spreadSheet{Index,2};
            handles.out{count,3} = handles.spreadSheet{Index,3};
            handles.out{count,4} = num2str(e);
            handles.out{count,5} = handles.spreadSheet{Index,4}(e);
        end
    end
end



if ~handles.analyses(Index).gsrStruct.analysisArguments.doSCL
    header = {'File' 'Condition' 'Analysis' 'Event' 't2pValue' 'Onset' 'Duration'};
else
    header = {'File' 'Condition' 'Analysis' 'Event' 'meanSCL'};
    
end

now = clock;
stamp = [num2str(now(1)) num2str(now(2)) num2str(now(3)) '_' num2str(now(4)) num2str(now(5))];

fid=fopen(['Autonomate_Batch_Output_' stamp '.txt'],'wt');
x=handles.out;
[rows,cols]=size(handles.out);

fprintf(fid,'%s\t',header{1,1:end});
fprintf(fid,'\n','');
for i=1:rows
    fprintf(fid,'%s\t',x{i,1:end-1});
    if ~handles.analyses(Index).gsrStruct.analysisArguments.doSCL
        fprintf(fid,'%s\n',x{i,end});
    else
        fprintf(fid,'%f\n',x{i,end});
    end
end

fclose(fid);


guidata(hObject, handles);





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


% --- Executes during object creation, after setting all properties.
function SRedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SRedit (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 button press in SCR.
function SCR_Callback(hObject, eventdata, handles)
% hObject    handle to SCR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if get(hObject,'Value')
    set(handles.NSR,'Value',0)
    set(handles.SCL,'Value',0)
    handles.doSF=0;
    handles.doSCL=0;
    set(handles.edt_maxUps,'String','8');
    set(handles.edt_Window, 'String', '9');
    set(handles.radio_largest, 'Enable', 'On');
    set(handles.radio_first, 'Enable', 'On');
    
    set(handles.text33, 'Enable', 'On');
    set(handles.text37, 'Enable', 'On');
    set(handles.text34, 'Enable', 'On');
    set(handles.text40, 'Enable', 'On');
    set(handles.text70, 'Enable', 'On');
    set(handles.text35, 'Enable', 'On');
    
    if get(handles.checkbox1, 'Value') == 1
        set(handles.edt_deltaSlope, 'Enable', 'On');
        set(handles.edt_contPoints, 'Enable', 'On');
        set(handles.edt_buffLength, 'Enable', 'On');
        set(handles.edt_maxUps, 'Enable', 'On');
        set(handles.edt_Window, 'Enable', 'On');
        set(handles.edt_postSeconds, 'Enable', 'On');
    end
    
    set(handles.text35, 'String', 'Window (sec)');
    set(handles.text38, 'String', 'Rise Start - Begin (sec)');
    set(handles.text39, 'String', 'Rise Start - End (sec)');
    
else
    set(hObject,'Value',1)
end

guidata(hObject, handles);

% Hint: get(hObject,'Value') returns toggle state of SCR


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

if get(hObject,'Value')
    set(handles.SCR,'Value',0)
    set(handles.NSR,'Value',0)
    handles.doSF=0;
    handles.doSCL=1;
    set(handles.edt_maxUps,'String','8');
    set(handles.edt_Window, 'String', '9');
    set(handles.edt_startWindow, 'String', '0');
    set(handles.edt_finishWindow, 'String', '9');
    set(handles.radio_largest, 'Enable', 'Off');
    set(handles.radio_first, 'Enable', 'Off');
    set(handles.edt_deltaSlope, 'Enable', 'Off');
    set(handles.text33, 'Enable', 'Off');
    set(handles.edt_contPoints, 'Enable', 'Off');
    set(handles.text37, 'Enable', 'Off');
    set(handles.edt_buffLength, 'Enable', 'Off');
    set(handles.text34, 'Enable', 'Off');
    set(handles.edt_maxUps, 'Enable', 'Off');
    set(handles.text40, 'Enable', 'Off');
    set(handles.edt_postSeconds, 'Enable', 'Off');
    set(handles.text70, 'Enable', 'Off');
    set(handles.text35, 'Enable', 'On');
    
    if get(handles.checkbox1, 'Value') == 1
        set(handles.edt_Window, 'Enable', 'On');
    end
    
    set(handles.text35, 'String', 'Event Window Length (sec)');
    set(handles.text38, 'String', 'SCL Window Start (sec)');
    set(handles.text39, 'String', 'SCL Window End (sec)');
    
else
    set(hObject,'Value',1)
end

guidata(hObject, handles);
% --- Executes on button press in NSR.
function NSR_Callback(hObject, eventdata, handles)
% hObject    handle to NSR (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 NSR
if get(hObject,'Value')
    set(handles.SCR,'Value',0)
    set(handles.SCL,'Value',0)
    handles.doSF=1;
    handles.doSCL=0;
    set(handles.edt_maxUps,'String','Inf');
    set(handles.edt_Window,'String','Inf');
    set(handles.edt_maxUps,'Enable','Off');
    set(handles.edt_Window,'Enable','Off');
    set(handles.radio_largest, 'Enable', 'Off');
    set(handles.radio_first, 'Enable', 'Off');
    
    set(handles.text33, 'Enable', 'On');
    set(handles.text37, 'Enable', 'On');
    set(handles.text34, 'Enable', 'On');
    set(handles.text40, 'Enable', 'On');
    set(handles.text70, 'Enable', 'Off');
    set(handles.text35, 'Enable', 'Off');
    
    if get(handles.checkbox1, 'Value') == 1
        set(handles.edt_deltaSlope, 'Enable', 'On');
        set(handles.edt_contPoints, 'Enable', 'On');
        set(handles.edt_buffLength, 'Enable', 'On');
        set(handles.edt_postSeconds, 'Enable', 'On');
    end
    
    set(handles.text35, 'String', 'Window (sec)');
    set(handles.text38, 'String', 'Rise Start - Begin (sec)');
    set(handles.text39, 'String', 'Rise Start - End (sec)');
    
else
    set(hObject,'Value',1)
end

guidata(hObject, handles);


% --- Executes on mouse press over figure background.
function gui_loadGSR_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to gui_loadGSR (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on slider movement.
function SliderHoriz_Callback(hObject, eventdata, handles)
% hObject    handle to SliderHoriz (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

%Calculate the width of the GUI panels that are hanging off the edge of the
%main GUI window
gui_edge = handles.gui_pos_set(3);
panel_parts_edge = handles.pan_events_pos(1) + handles.pan_events_pos(3);
x_range = panel_parts_edge - gui_edge;

% x_range = 150;
%Move file selection UI panel
MoveHoriz(hObject, handles, handles.uipanel1, handles.uipanel1_pos, x_range);

%Move Channel display UI panel
MoveHoriz(hObject, handles, handles.pan_Channels, handles.pan_chan_pos, x_range);

%Move event selection UI panel
MoveHoriz(hObject, handles, handles.pan_specifyEvents, handles.pan_events_pos, x_range);

%Move GSR analysis UI panel
MoveHoriz(hObject, handles, handles.pan_analyzeGSR, handles.pan_gsr_pos, x_range);

%Move analysis UI panel
MoveHoriz(hObject, handles, handles.pan_analyses, handles.pan_an_pos, x_range);

%Move names text
MoveHoriz(hObject, handles, handles.text41, handles.text_pos, x_range);

guidata(hObject, handles);

%Function for moving GUI elements horizontally (used by slider CallBacks)
function MoveHoriz(hObject, handles, element_handle, orig_pos, x_range)
%element_handle : handle for the element to be moved
%orig_pos : rect of the original (upon being made visible) position of the element
%x_range : the full range of horizontal movement the slider can provide
old_pos = get(element_handle, 'Position');
min_x = orig_pos(1);
slider_val = get(handles.SliderHoriz, 'Value');
new_x = min_x + (-1 * slider_val * x_range);
old_pos(1) = new_x;
set(element_handle, 'Position', old_pos);
guidata(hObject, handles);



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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


% --- Executes on slider movement.
function SliderVert_Callback(hObject, eventdata, handles)
% hObject    handle to SliderVert (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

%Calculate the width of the GUI panels that are hanging off the edge of the
%main GUI window
panel_parts_edge = handles.text_pos(2);
y_range = (-1.0 * panel_parts_edge)+2;

% y_range = 50;
%Move file selection UI panel
MoveVert(hObject, handles, handles.uipanel1, handles.uipanel1_pos, y_range);

%Move Channel display UI panel
MoveVert(hObject, handles, handles.pan_Channels, handles.pan_chan_pos, y_range);

%Move event selection UI panel
MoveVert(hObject, handles, handles.pan_specifyEvents, handles.pan_events_pos, y_range);

%Move GSR analysis UI panel
MoveVert(hObject, handles, handles.pan_analyzeGSR, handles.pan_gsr_pos, y_range);

%Move analysis UI panel
MoveVert(hObject, handles, handles.pan_analyses, handles.pan_an_pos, y_range);

%Move names text
MoveVert(hObject, handles, handles.text41, handles.text_pos, y_range);

guidata(hObject, handles);

%Function for moving GUI elements horizontally (used by slider CallBacks)
function MoveVert(hObject, handles, element_handle, orig_pos, y_range)
%element_handle : handle for the element to be moved
%orig_pos : rect of the original (upon being made visible) position of the element
%y_range : the full range of vertical movement the slider can provide
old_pos = get(element_handle, 'Position');
min_y = orig_pos(2);
slider_val = get(handles.SliderVert, 'Value');
new_y = min_y + ((1.0 - slider_val) * y_range);
old_pos(2) = new_y;
set(element_handle, 'Position', old_pos);
guidata(hObject, handles);


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

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end


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

set(hObject, 'Value', 1);
set(handles.radio_first, 'Value', 0);
handles.up_select = 'largest';

guidata(hObject, handles);


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

set(hObject, 'Value', 1);
set(handles.radio_largest, 'Value', 0);
handles.up_select = 'first';

guidata(hObject, handles);



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

%Create a dummy event data channel with a "1" at the beginning and all "0"s
%afterwords
data_size = length(handles.data{1});
dummy_data = zeros(data_size,1);
dummy_data(3:6) = 10;
handles.channels = handles.channels+1;
handles.eventChannel = handles.channels;
handles.data{handles.eventChannel} = dummy_data;

%Add this dummy data channel to all dataSet entries
for index=1:size(handles.dataSets,1)
    handles.dataSets{index,3}{handles.channels} = handles.data{handles.eventChannel};
end

%Add the channel to the event channel drop-down list
set(handles.popM_channelList_Event, 'String', 1:handles.channels);
set(handles.popM_channelList_Data, 'String', 1:handles.channels);
set(handles.popM_channelList_Event, 'Value', handles.eventChannel);

%Plot dummy event data channel
axes(handles.axe_eventChannel);
plot(handles.dataSets{1,3}{handles.eventChannel});

%Disable this button to prevent additional dummy channels from being added
set(hObject, 'Enable', 'Off');

%Set the analysis type to NSR
set(handles.SCR, 'Value', 0);
set(handles.NSR, 'Value', 1);
set(handles.SCL, 'Value', 0);
set(handles.SCR, 'Enable', 'Off');
set(handles.NSR, 'Enable', 'Off');
set(handles.SCL, 'Enable', 'Off');
set(handles.text70,'Enable','Off');
set(handles.text35,'Enable','Off');
set(handles.radio_largest, 'Enable', 'Off');
set(handles.radio_first, 'Enable', 'Off');
handles.doSF=1;
handles.doSCL=0;
set(handles.edt_maxUps,'String','Inf')
set(handles.edt_Window,'String','Inf')
set(handles.radio_largest, 'Enable', 'Off');
set(handles.radio_first, 'Enable', 'Off');

guidata(hObject, handles);
