classdef Episodic_ABF_analysis < matlab.apps.AppBase

    % Properties that correspond to app components
    properties (Access = public)
        UIFigure                        matlab.ui.Figure
        DataMenu                        matlab.ui.container.Menu
        ImportrawfolderMenu             matlab.ui.container.Menu
        NewfilesfolderMenu              matlab.ui.container.Menu
        AddfilesfolderMenu              matlab.ui.container.Menu
        ImportrawfilesMenu              matlab.ui.container.Menu
        NewfilesMenu                    matlab.ui.container.Menu
        AddfilesMenu                    matlab.ui.container.Menu
        SaveMenu                        matlab.ui.container.Menu
        LoadMenu                        matlab.ui.container.Menu
        ChangefilemodeMenu              matlab.ui.container.Menu
        CSVConverterMenu                matlab.ui.container.Menu
        OptionsMenu                     matlab.ui.container.Menu
        ROIboundsspinnerresolutionMenu  matlab.ui.container.Menu
        SetholdingcommandMenu           matlab.ui.container.Menu
        SetsignalunitMenu               matlab.ui.container.Menu
        HelpMenu                        matlab.ui.container.Menu
        OpenManualpdfMenu               matlab.ui.container.Menu
        AboutMenu                       matlab.ui.container.Menu
        EmergencysaveMenu               matlab.ui.container.Menu
        TestStop                        matlab.ui.container.Menu
        Debug                           matlab.ui.container.Menu
        TextArea                        matlab.ui.control.TextArea
        AboutPanel                      matlab.ui.container.Panel
        CloseAboutButton                matlab.ui.control.Button
        Episodic_ABF_analysisLabel      matlab.ui.control.Label
        abfloadLabel                    matlab.ui.control.Label
        Licence_AppTextArea             matlab.ui.control.TextArea
        Licence_ABFloadTextArea         matlab.ui.control.TextArea
        Gauge                           matlab.ui.control.LinearGauge
        ChangefiletypemodePanel         matlab.ui.container.Panel
        CancelButton_2                  matlab.ui.control.Button
        OKButton_2                      matlab.ui.control.Button
        ButtonGroup_3                   matlab.ui.container.ButtonGroup
        EventerfilesButton_2            matlab.ui.control.RadioButton
        LabcharttxtButton_2             matlab.ui.control.RadioButton
        abfButton_2                     matlab.ui.control.RadioButton
        FilemodeLabel                   matlab.ui.control.Label
        Panel_5                         matlab.ui.container.Panel
        AboutButton                     matlab.ui.control.Button
        CSVConverterButton              matlab.ui.control.Button
        ImportrawPanel                  matlab.ui.container.Panel
        UnitLabel                       matlab.ui.control.Label
        UnitEditField                   matlab.ui.control.EditField
        FullfolderButton                matlab.ui.control.StateButton
        FileselectionButton             matlab.ui.control.StateButton
        ButtonGroup_2                   matlab.ui.container.ButtonGroup
        LabcharttxtButton               matlab.ui.control.RadioButton
        abfButton                       matlab.ui.control.RadioButton
        EventerfilesButton              matlab.ui.control.RadioButton
        ManualpdfButton                 matlab.ui.control.Button
        LoadsessionButton               matlab.ui.control.Button
        EpisodicABFanalysisv6Label      matlab.ui.control.Label
        ExportinprogressLabel           matlab.ui.control.Label
        AnalysisinprogressLabel         matlab.ui.control.Label
        SetcommandlevelPanel            matlab.ui.container.Panel
        CancelButton_Level              matlab.ui.control.Button
        OKButton_Level                  matlab.ui.control.Button
        LevelDropDown                   matlab.ui.control.DropDown
        HoldinglevelEditField           matlab.ui.control.NumericEditField
        HoldinglevelEditFieldLabel      matlab.ui.control.Label
        SetROIsleftrightboundaryspinnerresolutionPanel  matlab.ui.container.Panel
        CancelButton                    matlab.ui.control.Button
        Default01msButton               matlab.ui.control.Button
        OKButton                        matlab.ui.control.Button
        SpinnerresolutionmsEditField    matlab.ui.control.NumericEditField
        SpinnerresolutionmsEditFieldLabel  matlab.ui.control.Label
        TabGroup2                       matlab.ui.container.TabGroup
        RawTab                          matlab.ui.container.Tab
        RawPanel                        matlab.ui.container.Panel
        GeneralcommentsTextArea         matlab.ui.control.TextArea
        GeneralcommentsTextAreaLabel    matlab.ui.control.Label
        Panel_4                         matlab.ui.container.Panel
        RemoverecordingButton           matlab.ui.control.Button
        ExcludesweepButton              matlab.ui.control.Button
        SweepLabel                      matlab.ui.control.NumericEditField
        InvertsweepselectionButton      matlab.ui.control.Button
        RecordingspecificcommentsTextArea  matlab.ui.control.TextArea
        RecordingspecificcommentsTextAreaLabel  matlab.ui.control.Label
        SelectallsweepsButton           matlab.ui.control.Button
        SweepsListBox                   matlab.ui.control.ListBox
        SweepsListBoxLabel              matlab.ui.control.Label
        SelectrecordingforanalysisButton  matlab.ui.control.StateButton
        SweepSpinner                    matlab.ui.control.Spinner
        DisplaymeanButton               matlab.ui.control.StateButton
        DisplaySDButton                 matlab.ui.control.StateButton
        DisplayallButton                matlab.ui.control.StateButton
        HighlightsweepButton            matlab.ui.control.StateButton
        RecordingSpinner                matlab.ui.control.Spinner
        RecordingDropDown               matlab.ui.control.DropDown
        RecordingDropDownLabel          matlab.ui.control.Label
        UnselectallrecordingsButton     matlab.ui.control.Button
        SelectallrecordingsButton       matlab.ui.control.Button
        Panel_2                         matlab.ui.container.Panel
        Marker8_SendvaluetoDropDown     matlab.ui.control.DropDown
        Marker8Button                   matlab.ui.control.StateButton
        MarkerSpinner_8                 matlab.ui.control.Spinner
        Marker7_SendvaluetoDropDown     matlab.ui.control.DropDown
        Marker7Button                   matlab.ui.control.StateButton
        MarkerSpinner_7                 matlab.ui.control.Spinner
        Marker6_SendvaluetoDropDown     matlab.ui.control.DropDown
        Marker6Button                   matlab.ui.control.StateButton
        MarkerSpinner_6                 matlab.ui.control.Spinner
        Marker5_SendvaluetoDropDown     matlab.ui.control.DropDown
        Marker5Button                   matlab.ui.control.StateButton
        MarkerSpinner_5                 matlab.ui.control.Spinner
        Marker4_SendvaluetoDropDown     matlab.ui.control.DropDown
        Marker3_SendvaluetoDropDown     matlab.ui.control.DropDown
        Marker2_SendvaluetoDropDown     matlab.ui.control.DropDown
        Marker1_SendvaluetoDropDown     matlab.ui.control.DropDown
        LockmanuelselectionCheckBox     matlab.ui.control.CheckBox
        yMinSpinner                     matlab.ui.control.Spinner
        yMaxSpinner                     matlab.ui.control.Spinner
        xMinSpinner                     matlab.ui.control.Spinner
        xMaxSpinner                     matlab.ui.control.Spinner
        AutoyButton                     matlab.ui.control.Button
        AutoxButton                     matlab.ui.control.Button
        minLabel                        matlab.ui.control.Label
        maxLabel                        matlab.ui.control.Label
        Marker1Button                   matlab.ui.control.StateButton
        Marker2Button                   matlab.ui.control.StateButton
        Marker3Button                   matlab.ui.control.StateButton
        Marker4Button                   matlab.ui.control.StateButton
        MarkerSpinner_1                 matlab.ui.control.Spinner
        MarkerSpinner_2                 matlab.ui.control.Spinner
        MarkerSpinner_3                 matlab.ui.control.Spinner
        MarkerSpinner_4                 matlab.ui.control.Spinner
        Raw_RecordingDataText           matlab.ui.control.TextArea
        RecordingDataLabel              matlab.ui.control.Label
        BaselinecorrectionPanel         matlab.ui.container.Panel
        ButtonGroup                     matlab.ui.container.ButtonGroup
        BaseCorFailedTextArea           matlab.ui.control.TextArea
        FailedforTextAreaLabel          matlab.ui.control.Label
        RightSpinner                    matlab.ui.control.Spinner
        RightSpinnerLabel               matlab.ui.control.Label
        LeftSpinner                     matlab.ui.control.Spinner
        LeftSpinnerLabel                matlab.ui.control.Label
        EpisodeSpinner                  matlab.ui.control.Spinner
        EpochButton                     matlab.ui.control.ToggleButton
        CursorsButton                   matlab.ui.control.ToggleButton
        OffButton                       matlab.ui.control.ToggleButton
        AnalysisoptionsPanel            matlab.ui.container.Panel
        IncludecommandlevelButton       matlab.ui.control.StateButton
        Button_ROIBaseline              matlab.ui.control.StateButton
        Panel_3                         matlab.ui.container.Panel
        DigitallyaltersampleratebyfactorLabel  matlab.ui.control.Label
        Analysis_SampleRateSpinner      matlab.ui.control.Spinner
        SampleRateEditField             matlab.ui.control.NumericEditField
        Analysis_RegressionDropDown_6   matlab.ui.control.DropDown
        Analysis_RegressionDropDown_5   matlab.ui.control.DropDown
        Analysis_RegressionDropDown_4   matlab.ui.control.DropDown
        Analysis_RegressionDropDown_3   matlab.ui.control.DropDown
        Analysis_RegressionDropDown_2   matlab.ui.control.DropDown
        Analysis_RegressionDropDown_1   matlab.ui.control.DropDown
        RegressionLabel                 matlab.ui.control.Label
        AutoswitchtoresulttabLabel      matlab.ui.control.Label
        Analysis_AutoSwitchCheckBox     matlab.ui.control.CheckBox
        ROIrelativtoresultofLabel       matlab.ui.control.Label
        RelativetoDropDown_6            matlab.ui.control.DropDown
        RelativetoDropDown_5            matlab.ui.control.DropDown
        RelativetoDropDown_4            matlab.ui.control.DropDown
        RelativetoDropDown_3            matlab.ui.control.DropDown
        RelativetoDropDown_2            matlab.ui.control.DropDown
        AnalysisAddtoresultsCheckBox    matlab.ui.control.CheckBox
        PeakDirDropDown_6               matlab.ui.control.DropDown
        PeakDirDropDown_5               matlab.ui.control.DropDown
        PeakDirDropDown_4               matlab.ui.control.DropDown
        PeakDirDropDown_3               matlab.ui.control.DropDown
        PeakDirDropDown_2               matlab.ui.control.DropDown
        PeakDirDropDown_1               matlab.ui.control.DropDown
        ROISpinnerLeft_6                matlab.ui.control.Spinner
        ROI6Label                       matlab.ui.control.Label
        SlopeSpinner_Upper_6            matlab.ui.control.Spinner
        SlopeSpinner_Lower_6            matlab.ui.control.Spinner
        AnalysisDropDown_6              matlab.ui.control.DropDown
        ROISpinnerRight_6               matlab.ui.control.Spinner
        CheckBox_ROI_6                  matlab.ui.control.CheckBox
        ROISpinnerLeft_5                matlab.ui.control.Spinner
        ROI5Label                       matlab.ui.control.Label
        SlopeSpinner_Upper_5            matlab.ui.control.Spinner
        SlopeSpinner_Lower_5            matlab.ui.control.Spinner
        AnalysisDropDown_5              matlab.ui.control.DropDown
        ROISpinnerRight_5               matlab.ui.control.Spinner
        CheckBox_ROI_5                  matlab.ui.control.CheckBox
        MethodLabel                     matlab.ui.control.Label
        RightboundaryLabel              matlab.ui.control.Label
        LeftboundaryLabel               matlab.ui.control.Label
        SlopeSpinner_Upper_4            matlab.ui.control.Spinner
        SlopeSpinner_Lower_4            matlab.ui.control.Spinner
        SlopeSpinner_Upper_3            matlab.ui.control.Spinner
        SlopeSpinner_Lower_3            matlab.ui.control.Spinner
        SlopeSpinner_Upper_2            matlab.ui.control.Spinner
        SlopeSpinner_Lower_2            matlab.ui.control.Spinner
        SlopeSpinner_Upper_1            matlab.ui.control.Spinner
        SlopeSpinner_Lower_1            matlab.ui.control.Spinner
        SlopeamplitudeLabel             matlab.ui.control.Label
        PeakdirectionLabel              matlab.ui.control.Label
        AnalysisDropDown_4              matlab.ui.control.DropDown
        AnalysisDropDown_3              matlab.ui.control.DropDown
        AnalysisDropDown_2              matlab.ui.control.DropDown
        AnalysisDropDown_1              matlab.ui.control.DropDown
        StartanalysisButton             matlab.ui.control.Button
        SelectedSweepsDropDown          matlab.ui.control.DropDown
        ApplytoLabel                    matlab.ui.control.Label
        ROISpinnerLeft_4                matlab.ui.control.Spinner
        ROI4Label                       matlab.ui.control.Label
        ROISpinnerRight_4               matlab.ui.control.Spinner
        CheckBox_ROI_4                  matlab.ui.control.CheckBox
        ROISpinnerLeft_3                matlab.ui.control.Spinner
        ROI3Label                       matlab.ui.control.Label
        ROISpinnerRight_3               matlab.ui.control.Spinner
        ROISpinnerLeft_2                matlab.ui.control.Spinner
        ROI2Label                       matlab.ui.control.Label
        ROISpinnerRight_2               matlab.ui.control.Spinner
        ROISpinnerRight_1               matlab.ui.control.Spinner
        CheckBox_ROI_3                  matlab.ui.control.CheckBox
        CheckBox_ROI_2                  matlab.ui.control.CheckBox
        ROISpinnerLeft_1                matlab.ui.control.Spinner
        ROI1SpinnerLabel                matlab.ui.control.Label
        RecordingListBox                matlab.ui.control.ListBox
        RecordingListBoxLabel           matlab.ui.control.Label
        RawUIAxes                       matlab.ui.control.UIAxes
        ResultsTab                      matlab.ui.container.Tab
        AnalysisPanel                   matlab.ui.container.Panel
        ExportresultsPanel              matlab.ui.container.Panel
        AdditionallyunifyresultsinsingleExceltableCheckBox  matlab.ui.control.CheckBox
        AddpostfixEditField             matlab.ui.control.EditField
        AddpostfixLabel                 matlab.ui.control.Label
        Export_resultsButton            matlab.ui.control.Button
        Export_meansweepwithSDCheckBox  matlab.ui.control.CheckBox
        Export_SetsavepathButton        matlab.ui.control.Button
        Export_Label                    matlab.ui.control.Label
        Export_FormatDropDown           matlab.ui.control.DropDown
        yvaluePanel                     matlab.ui.container.Panel
        Results_yaxisDropDown_Met_1     matlab.ui.control.DropDown
        ResultLabel                     matlab.ui.control.Label
        Results_yaxisDropDown_Rec_1     matlab.ui.control.DropDown
        RecordingLabel                  matlab.ui.control.Label
        Results_yaxisLamp_6             matlab.ui.control.Lamp
        Results_yaxisLamp_5             matlab.ui.control.Lamp
        Results_yaxisLamp_4             matlab.ui.control.Lamp
        Results_yaxisLamp_3             matlab.ui.control.Lamp
        Results_yaxisLamp_2             matlab.ui.control.Lamp
        Results_yaxisLamp_1             matlab.ui.control.Lamp
        Results_yaxisCheckBox_6         matlab.ui.control.CheckBox
        Results_yaxisCheckBox_5         matlab.ui.control.CheckBox
        Results_yaxisCheckBox_4         matlab.ui.control.CheckBox
        Results_yaxisCheckBox_3         matlab.ui.control.CheckBox
        Results_yaxisCheckBox_2         matlab.ui.control.CheckBox
        Results_yaxisDropDown_Rec_6     matlab.ui.control.DropDown
        Results_yaxisDropDown_Met_6     matlab.ui.control.DropDown
        Results_yaxisDropDown_Rec_5     matlab.ui.control.DropDown
        Results_yaxisDropDown_Met_5     matlab.ui.control.DropDown
        Results_yaxisDropDown_Rec_4     matlab.ui.control.DropDown
        Results_yaxisDropDown_Met_4     matlab.ui.control.DropDown
        Results_yaxisDropDown_Rec_3     matlab.ui.control.DropDown
        Results_yaxisDropDown_Met_3     matlab.ui.control.DropDown
        Results_yaxisDropDown_Rec_2     matlab.ui.control.DropDown
        Results_yaxisDropDown_Met_2     matlab.ui.control.DropDown
        xvaluePanel                     matlab.ui.container.Panel
        mintime0Label                   matlab.ui.control.Label
        XCorCheckBox                    matlab.ui.control.CheckBox
        Results_timescaleDropDown       matlab.ui.control.DropDown
        timescaleDropDownLabel          matlab.ui.control.Label
        Results_xaxisDropDown           matlab.ui.control.DropDown
        ResultLabel_2                   matlab.ui.control.Label
        LinestyleButtonGroup            matlab.ui.container.ButtonGroup
        LineMarkerButton                matlab.ui.control.ToggleButton
        MarkerButton                    matlab.ui.control.ToggleButton
        LineButton                      matlab.ui.control.ToggleButton
        PlotButton                      matlab.ui.control.Button
        RecordingListBox_2              matlab.ui.control.ListBox
        RecordingListBox_2Label         matlab.ui.control.Label
        Results_AnalysislogTextArea     matlab.ui.control.TextArea
        AnalysislogTextAreaLabel        matlab.ui.control.Label
        Results_UITable2                matlab.ui.control.Table
        Results_UIAxes                  matlab.ui.control.UIAxes
    end

    %%Episodic_ABF_analysis_v6 (03/2024)
    % by Michael Rabenstein
    %Cite as: Rabenstein, Michael, 2024, "Episodic ABF analysis", https://doi.org/10.60507/FK2/LBX1UB, bonndata, V1
    %Licensed under the BSD-3-Clause license
    %
    %Uses abfload function by Forrest Collman (2021). fcollman/abfload (https://github.com/fcollman/abfload), GitHub. Retrieved December 1, 2021.
    %New in v2: save and load last session incl. selected analysis
    %settings. App size and layout adjusted.
    %New in v3: Commentary function. Not analysed recordings and sweeps are
    %listet in export log. Import of LabChart recordings (txt). For mean
    %sweep results, results can additionally be added to a single Excel table,
    %when exported as tsv. Marker values can be directly send to ROI bound
    %spinners. Smaller performance changes.
    %New in v4: Loaded recordings can be selected with the list box. Loaded
    %recordings can be removed from the session. Sweeps can be highlighted
    %or excluded via clicking in the plot. Mixed visualization and performance changes.
    %New in v5: AUC analysis, import of converted csv files as LabChart
    %txt files (Converter: CSV_Converter_Episodic_ABF_analysis). Unit of
    %LabChart txt files can be defined in start window
    %New in v6: Upgrade to Matlab 2024a.Increase of markers to eight.
    %'Eventer' output can be imported (https://eventerneuro.netlify.app/; accessed 22.03.2024).

    properties (Access = private)
        channels = char('a'); %Read all with abfload
        sweeps = char('a'); %Read all with abfload
        headerlines = 6; %Lines to skip for LabChart txt import

        loaded_files; %Struct of loaded files with elements: ABF header, full and selection based data table, lists of all/ selected/ unselected sweeps, baselines, time resolution, table with baseln (un)corrected mean sweep and sd, file name and selected header infos
        selected_recording %Recording selected to be displayed in raw tab

        plotted_data %plot of displayed sweeps in raw tab

        results_analysis = [] %Struct with elements, filled after analysis button was pushed. Contains results and values for the ui elements in results tab.
        analysis_resolution = 0.1; %can be modified to alter resolution of ROI left/right boundary spinner
        spinner_resolution = 0.1; %General spinner resolution
        spinner_limits = [0.1,Inf]

        ROI_selected = 1; %List of selected ROIs for analysis

        holding_command_set = 0; %Property to determine if user has added holding command level

        save_load_path %path of formerly selected save/load action

        save_name = '' %name of previously loaded file
        save_session_done = 0 % Check if session was saved
        file_type_mode = 1 % File type mode (ABF == 1, LabChart txt == 2, Eventer files == 3);
        time_correction %Correction value in case negative time points are in recording (LabChart txt only)
        load_active = 0 %for skipping dialog during file type change if session should be loaded

        analysis_sweep_mode = 1 %Property to define if analysis should be done with the mean sweep (1) or all selected sweeps (2)

        menue_state %To avoid tool activation, if option menues are selected

        RecordingListBox_Value_BU %Cache needed during change of selected recording in RecordingListBox
        selectedStyle %Propertiy to highlight selected recording in RecordingListBox
        baseStyle %Property used for unselected recordings in RecordingListBox

        manual = 'Episodic_ABF_analysis_manual_v6.pdf'; %Manual version
    end

    properties (Access = public)
        sweep_index_highlight = 1;
    end

    methods (Access = private)
        function load_files_type(app, mode, dir_type, save_var) %Select loading function in dependence of loaded file type
            if     app.file_type_mode == 1
                app.SetholdingcommandMenu.Visible =  "on";
                app.xvaluePanel.Visible =  "on";
                app.yvaluePanel.Visible =  "on";
                app.LinestyleButtonGroup.Visible =  "on";
                app.PlotButton.Visible =  "on";
                app.Results_UIAxes.Visible =  "on";
                app.SetsignalunitMenu.Visible = "off";
                app.load_files_abf(mode, dir_type, save_var);
            elseif app.file_type_mode == 2
                app.SetholdingcommandMenu.Visible =  "off";
                app.xvaluePanel.Visible =  "off";
                app.yvaluePanel.Visible =  "off";
                app.LinestyleButtonGroup.Visible =  "off";
                app.PlotButton.Visible =  "off";
                app.Results_UIAxes.Visible =  "off";
                app.SetsignalunitMenu.Visible = "on";
                app.load_files_txt(mode, dir_type, save_var);
            elseif app.file_type_mode == 3
                app.SetholdingcommandMenu.Visible =  "off";
                app.xvaluePanel.Visible =  "off";
                app.yvaluePanel.Visible =  "off";
                app.LinestyleButtonGroup.Visible =  "off";
                app.PlotButton.Visible =  "off";
                app.Results_UIAxes.Visible =  "off";
                app.SetsignalunitMenu.Visible = "off";
                app.load_files_eventer(mode, dir_type, save_var);
            end
            app.TabGroup2.Visible = "on";
        end

        function load_files_abf(app, mode, dir_type, save_var)
            %%Load all .ABF files from selected folder

            if dir_type == 1 %load full folder
                %Ask user to select folder
                selpath = uigetdir('','Select data folder');
                if selpath == 0 %In case user canceled folder selection
                    return
                end
                cd (selpath)
                abffiles = dir('*.abf'); %All ABF in selected directory
                if isempty(abffiles) %In case no ABF are in selected folder
                    return
                end
                abffiles = {abffiles.name}; %Isolate file names
            elseif dir_type == 2 %Single files
                [abffiles,selpath] = uigetfile({'*.abf','All Files'},...
                    'Select one or more ABF files', ...
                    'MultiSelect', 'on');
                if selpath == 0 %In case no files were selected
                    return
                end
                cd (selpath)
            elseif dir_type == 3 %previous session
                %Loading was done in a previous step
            end
            figure(app.UIFigure) %Necessary to move app window back to foreground after use of 'uigetfile'

            if mode == 2 %If files should be added
                already_loaded = app.RecordingListBox.Items;
                shift_recording_counter = size(already_loaded,2);
                loaded_files_loc =  app.loaded_files;
                selected_recordings = app.RecordingListBox.Value;
            elseif mode == 1 %If new files should be loaded, clear old ones
                addStyle(app.RecordingListBox, app.baseStyle);
                app.RecordingListBox.Items = {};
                app.RecordingListBox.ItemsData = {};
                shift_recording_counter = 0;
                loaded_files_loc = struct;
                app.GeneralcommentsTextArea.Value = "";
            end

            if dir_type == 1 || dir_type == 2 %Import new data
                %Settings for abfload
                doDispInfo  = false;
                recording_counter = 1 + shift_recording_counter;

                if ischar(abffiles)
                    no_of_abfs = 1; %If only single file was selected
                else
                    no_of_abfs = length(abffiles); %If multiple files were selected
                end

                for i=1:no_of_abfs %for every ABF in selected folder
                    %Load ABF
                    if ischar(abffiles)
                        fn = abffiles;
                    else
                        fn = abffiles{i};
                    end
                    [d,si,h]=abfload(fn,app.sweeps,app.channels, 'doDispInfo', doDispInfo);

                    if ~(h.nOperationMode == 5) %in case recording is not a Episodic stimulation
                        msg = sprintf('%s could not be loaded.\nPlease check if recording was done with an episodic stimulation protocol.', fn);
                        title = 'File could not be loaded';
                        waitfor(msgbox(msg,title));
                        continue
                    end
                    %create index of datapoints
                    datapoint_index = 1:size(d(:,:,1),1);

                    %Calculate sample point time coloumn in ms
                    timescale = (((datapoint_index)*si)/1000).'; %time in ms
                    data_iso = permute(d,[1 3 2]);
                    for i_channels = 1:size(data_iso,3) %For every recording channel

                        data_table = [timescale,data_iso(:,:,i_channels)]; %isolate data points and link them with time

                        %Prepare recording name for display
                        fn_clean = fn(1:end-4); %remove '.ABF' from filename
                        fn_clean_channel = sprintf('%s_%s', fn_clean, string(i_channels)); %add channel

                        if mode == 2 && sum(ismember(already_loaded, fn_clean_channel)) %If file is already loaded
                            continue
                        end

                        app.RecordingListBox.Items = [app.RecordingListBox.Items,fn_clean_channel]; %add recording to list box

                        %simplify sample frequency for selected header info
                        samplefreq_cache = 1/(si/1000000);
                        samplefreq_unit_counter = 0;
                        while samplefreq_cache >= 1000 && samplefreq_unit_counter < 2
                            samplefreq_cache = samplefreq_cache/1000;app.spinner_limits;
                            samplefreq_unit_counter = samplefreq_unit_counter + 1;
                        end
                        if samplefreq_unit_counter == 0
                            samplefreq_unit = "Hz";
                        elseif samplefreq_unit_counter == 1
                            samplefreq_unit = "kHz";
                        elseif samplefreq_unit_counter == 2
                            samplefreq_unit = "MHz";
                        end


                        %Fetch epochs information
                        epoch_firstHolding = h.DACEpoch.firstHolding; %sample point delay between start of recording and execution of protocol
                        epoch_number = h.DACEpoch.nEpochNum; %Epoch number (0-n);
                        epoch_level = h.DACEpoch.fEpochInitLevel; %Command levels
                        epoch_durations = h.DACEpoch.lEpochInitDuration; %Epoch durations in sample points
                        epoch_durations_ms = epoch_durations * (si/1000); %Epoch durations in ms
                        epoch_level_step = h.DACEpoch.fEpochLevelInc; %Sweep wise increase of command level
                        epoch_infos = [epoch_number; epoch_level; epoch_durations; epoch_durations_ms; epoch_level_step];

                        %Prepare epoch table for baseline correction (in sample
                        %points)
                        epoch_baseline = [];
                        epoch_time_area_start = epoch_firstHolding + 1; %Based on delay plus one sample point
                        for i_epoch = 1:size(epoch_number,2)
                            epoch_time_area_end = sum(epoch_durations(1:i_epoch)) + epoch_firstHolding;
                            epoch_baseline_cache = [epoch_time_area_start, epoch_time_area_end];
                            epoch_baseline = [epoch_baseline; epoch_baseline_cache];
                            epoch_time_area_start = epoch_time_area_end + 1;
                        end

                        % Set spinner limits and resolution
                        app.spinner_limits = [data_table(1,1), data_table(end,1)];
                        app.spinner_resolution = 0.1;

                        %Prepare epoch table for command level. Holding level not included in
                        %header information --> must be added manually by user

                        epoch_commandLevel = data_table; %Create table
                        epoch_commandLevel(:,1)= datapoint_index'; %Replace time in ms into no of datapoint
                        epoch_commandLevel(:,2:end) = NaN; %Replace second column with NaN (placeholder for command level)
                        command_step = epoch_level_step;
                        for i_sweep = 2:size(epoch_commandLevel,2) %For every sweep
                            command_startpoint = epoch_firstHolding + 1; %starting position for replacing NaN with known command level
                            command_level = epoch_level + (command_step * (i_sweep - 2)); %Calculate command_level including step increase
                            for i_command = 1: size(epoch_number,2) %For every epoch
                                command_endpoint = command_startpoint + epoch_durations(i_command); %Define last point of epoch
                                epoch_commandLevel(command_startpoint:command_endpoint, i_sweep) = command_level(i_command); %add command level to table
                                command_startpoint = command_endpoint + 1; %Define first point of next epoch
                            end
                        end
                        if app.holding_command_set == 1 %In case a new dataset is loaded and holding command was set previously
                            commandLevel_complete = epoch_commandLevel; %create a copy of commandLevel without holding command level
                            commandLevel_complete(isnan(commandLevel_complete)) = app.HoldinglevelEditField.Value; %add set holding command level
                            unit = app.LevelDropDown.Value; %Save command level unit
                            %Save to temporary struct
                            data_temp.epoch.commandLevel_complete = commandLevel_complete;
                            data_temp.epoch.unit = unit;
                        end

                        %Prepare epoch information in ms for header info
                        header_epochs = ["Epoch information";string(sprintf('Number\t\tCommand level\t\tCommand level increase\t\ttime area (ms)'))];
                        epoch_time_area_start = epoch_firstHolding * (si/1000) + (si/1000);
                        for i_epoch = 1:size(epoch_number,2)

                            %Create epoch duration string (e.g. "0.5 - 500")
                            epoch_time_area_end = sum(epoch_durations_ms(1:i_epoch)) + (epoch_firstHolding * (si/1000));
                            epoch_time_area_string = string(sprintf('%s - %s', string(epoch_time_area_start), string(epoch_time_area_end)));
                            epoch_time_area_start = epoch_time_area_end + (si/1000);

                            %Add values to header info string
                            header_epochs_cache = string(sprintf('%s\t\t%s\t\t%s\t\t%s', string(epoch_number(i_epoch)), string(epoch_level(i_epoch)), string(epoch_level_step(i_epoch)), epoch_time_area_string));
                            header_epochs = [header_epochs; header_epochs_cache];
                        end

                        %Stitch selected header info
                        if app.holding_command_set == 0
                            headerinfo_cache = [fn_clean;...
                                string(sprintf('Channel: %s', string(i_channels)));...
                                string(sprintf('Unit: %s', h.recChUnits{1}));...
                                string(sprintf('Sample frequency: %d %s', samplefreq_cache, samplefreq_unit));...
                                string(sprintf('Amplifier gain: %d', h.fTelegraphAdditGain));...
                                string(sprintf('Sweeps: %d', h.lActualEpisodes));...
                                string(sprintf('Holding command not set'));...
                                header_epochs
                                ];
                        elseif app.holding_command_set == 1
                            headerinfo_cache = [fn_clean;...
                                string(sprintf('Channel: %s', string(i_channels)));...
                                string(sprintf('Unit: %s', h.recChUnits{1}));...
                                string(sprintf('Sample frequency: %d %s', samplefreq_cache, samplefreq_unit));...
                                string(sprintf('Amplifier gain: %d', h.fTelegraphAdditGain));...
                                string(sprintf('Sweeps: %d', h.lActualEpisodes));...
                                string(sprintf('Holding command set to %s %s', num2str(app.HoldinglevelEditField.Value), app.LevelDropDown.Value));...
                                header_epochs
                                ];
                        end

                        %Prepare mean and sd tables out of every sweep
                        mean_temp = mean(data_iso(:,:,i_channels),2,'omitnan');
                        sd_temp = std(data_iso(:,:,i_channels),0,2,'omitnan');
                        mean_sd_temp = [timescale, mean_temp, sd_temp];

                        %Prepare selected / unselected swep tables
                        Nr_Sweeps = (size(data_table,2)-1);
                        Nr_of_sweeps_temp = (1:Nr_Sweeps);
                        Unselected_sweeps_temp = [];

                        %Create recording struct with prepared data
                        data_temp.header = h;
                        data_temp.channel = i_channels;
                        data_temp.unit = h.recChUnits{i_channels};
                        data_temp.data = data_table;
                        data_temp.selected_sweeps = Nr_of_sweeps_temp;
                        data_temp.unselected_sweeps = Unselected_sweeps_temp;
                        data_temp.all_sweeps =  Nr_of_sweeps_temp;
                        data_temp.data_table_selected = data_table;
                        data_temp.baseline = 0; %for selected baseline correction
                        data_temp.resolution = si/1000;
                        data_temp.mean_sd = mean_sd_temp;
                        data_temp.filename = fn_clean;
                        data_temp.headerinfo = headerinfo_cache;
                        data_temp.epoch.infos = epoch_infos;
                        data_temp.epoch.firstHolding = epoch_firstHolding;
                        data_temp.epoch.baseline = epoch_baseline;
                        data_temp.epoch.commandLevel = epoch_commandLevel;
                        data_temp.comment = "";
                        struct_name = sprintf('recording_%d', recording_counter); %create structname. Filename not usable, since struct name can't start with a number (e.g. 211011_Rec_1)
                        loaded_files_loc.(struct_name) = data_temp; %Save recording struct to combined struct

                        recording_counter = recording_counter + 1;
                    end
                end
                app.loaded_files = loaded_files_loc; %Save loaded files struct to property

                %Create and add values for RecordingListBox
                ItemsListBox = 1:size(app.RecordingListBox.Items,2);
                app.RecordingListBox.ItemsData = ItemsListBox;
                addStyle(app.RecordingListBox, app.selectedStyle, "item", 1);
                if mode == 1
                    app.loaded_files.general_comment = "";
                    app.RecordingListBox.Value = app.RecordingListBox.ItemsData; %Select all
                elseif mode == 2
                    new_data_index = shift_recording_counter + 1;
                    new_data_values = app.RecordingListBox.ItemsData(new_data_index:end);
                    selected_recordings = [selected_recordings, new_data_values];
                    app.RecordingListBox.Value = selected_recordings;
                end
                app.RecordingListBox_Value_BU = app.RecordingListBox.Value;

            elseif dir_type == 3 %Load previous session
                app.load_session(save_var);
            else
                return
            end

            %Create recording drop down list and selection spinner
            app.RecordingDropDown.Items = app.RecordingListBox.Items;
            app.RecordingDropDown.ItemsData = app.RecordingListBox.ItemsData;
            app.RecordingDropDown.Value = 1; %Preselect first recording

            if app.RecordingDropDown.ItemsData(end)>1 %More than one recording was loaded
                app.RecordingSpinner.Limits = [1, app.RecordingDropDown.ItemsData(end)];
                app.RecordingSpinner.Value = 1;
                app.RecordingSpinner.Enable = "on";
            else %Fix spinner at value 1
                app.RecordingSpinner.Limits = [0, app.RecordingDropDown.ItemsData(end)];
                app.RecordingSpinner.Value = 1;
                app.RecordingSpinner.Enable = "off";
            end

            app.selected_recording = sprintf('recording_%d', app.RecordingDropDown.Value); %save recording_1 to selected recording property
            app.change_recording(); %Start setting the uifigure controls
            app.LeftSpinnerValueChanged();

            app.set_spinner_resolution();

            app.RawPanel.Enable = "on"; %Enable app
            app.TabGroup2.SelectedTab = app.RawTab; %Switch to raw tab

            %Enable 'add file' option
            app.AddfilesfolderMenu.Enable = "on";
            app.AddfilesMenu.Enable = "on";
            app.SaveMenu.Enable = "on";
            if dir_type == 3
                app.save_session_done = 1;
            else
                app.save_session_done = 0;
            end
            app.LockmanuelselectionCheckBox.Value = 1; %Lock axes boundaries
        end

        function load_files_txt(app, mode, dir_type, save_var)
            %%Load all .txt files from selected folder
            warning('off','all')
            if dir_type == 1 %load full folder
                %Ask user to select folder
                selpath = uigetdir('','Select data folder');
                if selpath == 0 %In case user canceled folder selection
                    return
                end
                cd (selpath)
                files_to_load = dir('*.txt'); %All txt in selected directory
                if isempty(files_to_load) %In case no ABF are in selected folder
                    return
                end
                files_to_load = {files_to_load.name}; %Isolate file names
            elseif dir_type == 2 %Single files
                [files_to_load,selpath] = uigetfile({'*.txt','All Files'},...
                    'Select one or more LabChart txt files', ...
                    'MultiSelect', 'on');
                if selpath == 0 %In case no files were selected
                    return
                end
                cd (selpath)
            elseif dir_type == 3 %previous session
                %Loading was done in a previous step
            end
            figure(app.UIFigure) %Necessary to move app window back to foreground after use of 'uigetfile'

            if mode == 2 %If files should be added
                already_loaded = app.RecordingListBox.Items;
                shift_recording_counter = size(already_loaded,2);
                loaded_files_loc =  app.loaded_files;
                selected_recordings = app.RecordingListBox.Value;
            elseif mode == 1 %If new files should be loaded, clear old ones
                addStyle(app.RecordingListBox, app.baseStyle);
                app.RecordingListBox.Items = {};
                app.RecordingListBox.ItemsData = {};
                shift_recording_counter = 0;
                loaded_files_loc = struct;
                app.GeneralcommentsTextArea.Value = "";
            end


            if dir_type == 1 || dir_type == 2 %Import new data

                %Settings for txt load
                recording_counter = 1 + shift_recording_counter;

                if ischar(files_to_load)
                    no_of_files = 1; %If only single file was selected
                else
                    no_of_files = length(files_to_load); %If multiple files were selected
                end

                for i=1:no_of_files %for every file in selected folder
                    %Load txt
                    if ischar(files_to_load)
                        fn = files_to_load;
                    else
                        fn = files_to_load{i};
                    end
                    fn_clean = fn(1:end-4); %remove '.txt' from filename
                    %Load Header info
                    fid = fopen(fn);
                    headerinfo_cache = [string(fn_clean)];
                    tline = fgetl(fid);
                    headerno = 1;
                    while ischar(tline) && headerno <= app.headerlines
                        if isempty(str2num(tline)) %#ok<ST2NM> %Check if line contains numeric data, stored as char
                            headerinfo_cache = [headerinfo_cache; string(tline)];
                            tline = fgetl(fid);
                            headerno = headerno + 1;
                        else
                            break
                        end
                    end
                    fclose(fid);

                    t = readtable(fn, 'HexType','int32','BinaryType','int32');
                    t{:,1} = t{:,1}*1000; %Convert s to ms
                    index_NaN = ~isnan(t{:,1}); %Remove in between headers
                    t_extract = t{index_NaN,1:2}; %Remove in between headers
                    index_start = find(t_extract(:,1)==t_extract(1,1)); %Get Index of sweep start

                    if isscalar(index_start)
                        % if length(index_start) == 1 %Old way
                        end_value = t_extract(end, 1);
                    else
                        end_value = t_extract((index_start(2) -1), 1);
                    end
                    index_end = find(t_extract(:,1)==end_value); %Get Index of sweep end
                    index_stim = find((t_extract(:,1)==0));
                    if ~isempty(index_stim) && index_stim(1) > 1 %If timepoint zero is present but not first
                        try %#ok<TRYNC> %Fetch tag in third column, if present
                            headerinfo_cache = [headerinfo_cache; string(t_extract(index_stim(1),3))];
                        end
                    end

                    %Define units (ms, mV)
                    data_table = t_extract(index_start(1):index_end(1),1); %Get time
                    for i_sweeps = 1:size(index_start, 1) %fetch every sweep and add to matrix
                        data_cache = t_extract(index_start(i_sweeps):index_end(i_sweeps),2);
                        data_table = [data_table, data_cache];
                    end

                    app.RecordingListBox.Items = [app.RecordingListBox.Items,fn_clean]; %add recording to list box

                    %simplify sample frequency for selected header info
                    sampleintervall = data_table(2,1) - data_table(1,1);
                    samplefreq_cache = 1/(sampleintervall/1000);
                    samplefreq_unit_counter = 0;
                    while samplefreq_cache >= 1000 && samplefreq_unit_counter < 2
                        samplefreq_cache = samplefreq_cache/1000;
                        samplefreq_unit_counter = samplefreq_unit_counter + 1;
                    end
                    if samplefreq_unit_counter == 0
                        samplefreq_unit = "Hz";
                    elseif samplefreq_unit_counter == 1
                        samplefreq_unit = "kHz";
                    elseif samplefreq_unit_counter == 2
                        samplefreq_unit = "MHz";
                    end

                    headerinfo_cache = [headerinfo_cache; string(sprintf('%s %s', string(samplefreq_cache), samplefreq_unit))];

                    % epoch_baseline = [];
                    index_epoch = find(t_extract(:,1)==0) - 1;
                    if ~isempty(index_epoch) && index_epoch(1) > 0 %If timepoint zero is present but not first
                        index_epoch = index_epoch(1);
                        % epoch_baseline = [1, index_epoch];
                        epoch_baseline = [1, index_epoch; (index_epoch + 1), index_end(1)];
                    else
                        epoch_baseline = [1, 2; 3, index_end(1)];
                        index_epoch = []; %empty index in case timepoint zero is present but not first
                    end

                    % Set spinner limits and resolution
                    app.spinner_limits = [data_table(1,1), data_table(end,1)];
                    app.spinner_resolution = sampleintervall;

                    %Save time correction value in case negative time points
                    %are in recording
                    if data_table(1,1) <= 0
                        app.time_correction = abs(data_table(1,1)) + sampleintervall;
                    else
                        app.time_correction = 0;
                    end

                    %Prepare epoch information in ms for header info
                    header_epochs = ["Epoch information";string(sprintf('Number\t\ttime area (ms)'))];
                    if ~isempty(index_epoch)
                        epoch_time_area_string = string(sprintf('%s - %s', string(t_extract(1,1)), string(t_extract(index_epoch,1))));
                        header_epochs_cache = string(sprintf('%s\t\t%s', "0 (pre stimulation)", epoch_time_area_string));
                        header_epochs = [header_epochs; header_epochs_cache];
                        epoch_time_area_string = string(sprintf('%s - %s', string(t_extract((index_epoch + 1),1)), string(t_extract(end,1))));
                        header_epochs_cache = string(sprintf('%s\t\t%s', "1 (post stimulation)", epoch_time_area_string));
                    else
                        epoch_time_area_string = string(sprintf('%s - %s', string(t_extract(1,1)), string(t_extract(2))));
                        header_epochs_cache = string(sprintf('%s\t\t%s', "0 (first two datapoints)", epoch_time_area_string));
                        header_epochs = [header_epochs; header_epochs_cache];
                        epoch_time_area_string = string(sprintf('%s - %s', string(t_extract((3),1)), string(t_extract(end,1))));
                        header_epochs_cache = string(sprintf('%s\t\t%s', "1 (remaining data points)", epoch_time_area_string));
                    end
                    header_epochs = [header_epochs; header_epochs_cache];

                    headerinfo_cache = [headerinfo_cache; header_epochs];

                    %Prepare mean and sd tables out of every sweep
                    data_iso = data_table(:,2:end);
                    mean_temp = mean(data_iso(:,:),2,'omitnan');
                    sd_temp = std(data_iso(:,:),0,2,'omitnan');
                    mean_sd_temp = [data_table(:,1), mean_temp, sd_temp];

                    %Prepare selected / unselected swep tables
                    Nr_Sweeps = (size(data_table,2)-1);
                    Nr_of_sweeps_temp = (1:Nr_Sweeps);
                    Unselected_sweeps_temp = [];

                    %Create recording struct with prepared data
                    if isempty(app.UnitEditField.Value)
                        data_temp.unit = "Units";
                        app.UnitEditField.Value = 'Units';
                    else
                        data_temp.unit = string(app.UnitEditField.Value);
                    end
                    data_temp.data = data_table;
                    data_temp.selected_sweeps = Nr_of_sweeps_temp;
                    data_temp.unselected_sweeps = Unselected_sweeps_temp;
                    data_temp.all_sweeps =  Nr_of_sweeps_temp;
                    data_temp.data_table_selected = data_table;
                    data_temp.baseline = 0; %for selected baseline correction
                    data_temp.resolution = sampleintervall;
                    data_temp.mean_sd = mean_sd_temp;
                    data_temp.filename = fn_clean;
                    data_temp.headerinfo = headerinfo_cache;
                    data_temp.epoch.baseline = epoch_baseline;
                    data_temp.comment = "";
                    struct_name = sprintf('recording_%d', recording_counter); %create structname. Filename not usable, since struct name can't start with a number (e.g. 211011_Rec_1)
                    loaded_files_loc.(struct_name) = data_temp; %Save recording struct to combined struct

                    recording_counter = recording_counter + 1;
                end
                app.loaded_files = loaded_files_loc; %Save loaded files struct to property

                %Create and add values for RecordingListBox
                ItemsListBox = 1:size(app.RecordingListBox.Items,2);
                app.RecordingListBox.ItemsData = ItemsListBox;
                addStyle(app.RecordingListBox, app.selectedStyle, "item", 1);
                if mode == 1
                    app.loaded_files.general_comment = "";
                    app.RecordingListBox.Value = app.RecordingListBox.ItemsData; %Select all
                elseif mode == 2
                    new_data_index = shift_recording_counter + 1;
                    new_data_values = app.RecordingListBox.ItemsData(new_data_index:end);
                    selected_recordings = [selected_recordings, new_data_values];
                    app.RecordingListBox.Value = selected_recordings;
                end
                app.RecordingListBox_Value_BU = app.RecordingListBox.Value;

            elseif dir_type == 3 %Load previous session
                app.load_session(save_var)
            else
                return
            end

            %Create recording drop down list and selection spinner
            app.RecordingDropDown.Items = app.RecordingListBox.Items;
            app.RecordingDropDown.ItemsData = app.RecordingListBox.ItemsData;
            app.RecordingDropDown.Value = 1; %Preselect first recording

            if app.RecordingDropDown.ItemsData(end)>1 %More than one recording was loaded
                app.RecordingSpinner.Limits = [1, app.RecordingDropDown.ItemsData(end)];
                app.RecordingSpinner.Value = 1;
                app.RecordingSpinner.Enable = "on";
            else %Fix spinner at value 1
                app.RecordingSpinner.Limits = [0, app.RecordingDropDown.ItemsData(end)];
                app.RecordingSpinner.Value = 1;
                app.RecordingSpinner.Enable = "off";
            end

            app.selected_recording = sprintf('recording_%d', app.RecordingDropDown.Value); %save recording_1 to selected recording property
            app.change_recording(); %Start setting the uifigure controls

            app.RawPanel.Enable = "on"; %Enable app
            app.TabGroup2.SelectedTab = app.RawTab; %Switch to raw tab

            %Enable 'add file' option
            app.AddfilesfolderMenu.Enable = "on";
            app.AddfilesMenu.Enable = "on";
            app.SaveMenu.Enable = "on";
            app.set_spinner_resolution();
            app.LockmanuelselectionCheckBox.Value = 1; %Lock axes boundaries
            warning('on','all')
        end

        function load_files_eventer(app, mode, dir_type, save_var)
            % %%Load all Eventer recordings from selected Eventer output
            % directory
            warning('off','all')
            if dir_type == 1 %load new
                %Ask user to select folder
                selpath = uigetdir('','Select ''Eventer'' output folder'); %Select 'Eventer' output folder (the one containing the files 'analysis.evt' and 'filepaths.txt').
                if selpath == 0 %In case user canceled folder selection
                    return
                end
                cd (selpath)
                try %Check if a valid eventer output folder was probably selected
                    filenames = readlines("filepaths.txt");
                catch
                    return
                end

                filenames = filenames(2:end); %Delete main path entry
                filenames(strcmp(filenames, "")) = []; %Delete empty entries
                % filenames = strrep(filenames,'.\','');
                [~,filenames,~] = fileparts(filenames);

                cd 'eventer.output'

                waves = dir('*_YWave*'); %Fetch list with all single recording output folders
                if isempty(waves) %In case no subdirectories are in selected folder
                    return
                end
                wavepaths = fullfile({waves.folder}, {waves.name}); %Generate paths
                %Create path list to recording files
                files_to_load = fullfile(wavepaths, 'event_data.phy')';
                files_to_load_summary = fullfile(wavepaths, 'summary.txt')';

            elseif dir_type == 3 %previous session
                %Loading was done in a previous step
            end
            figure(app.UIFigure) %Necessary to move app window back to foreground after use of 'uigetfile'

            if mode == 2 %If files should be added
                already_loaded = app.RecordingListBox.Items;
                shift_recording_counter = size(already_loaded,2);
                loaded_files_loc =  app.loaded_files;
                selected_recordings = app.RecordingListBox.Value;
            elseif mode == 1 %If new files should be loaded, clear old ones
                addStyle(app.RecordingListBox, app.baseStyle);
                app.RecordingListBox.Items = {};
                app.RecordingListBox.ItemsData = {};
                shift_recording_counter = 0;
                loaded_files_loc = struct;
                app.GeneralcommentsTextArea.Value = "";
            end

            if dir_type == 1 || dir_type == 2 %Import new data

                %Settings for Eventer files load
                recording_counter = 1 + shift_recording_counter;

                no_of_files = size(files_to_load, 1);

                no_events = [];

                for i=1:no_of_files %for every file in selected folder
                    if mode == 2 && sum(ismember(already_loaded, filenames(i))) %If file is already loaded
                        continue
                    end

                    fn = files_to_load{i};
                    if exist(fn, 'file') == 0 %If recording does not contains events
                        no_events = [no_events; filenames(i)];
                        continue
                    end

                    %Load Eventer files
                    fn_summary = files_to_load_summary{i};
                    fn_clean = char(filenames(i));

                    %Load header info
                    fid = fopen(fn_summary);
                    headerinfo_cache = [string(fn_clean)];
                    tline = fgetl(fid);
                    while ischar(tline)
                        headerinfo_cache = [headerinfo_cache; string(tline)];
                        tline = fgetl(fid);
                    end
                    fclose(fid);

                    scale=double(h5read(fn,'/scale'));
                    start=double(h5read(fn,'/start'));
                    array=double(h5read(fn,'/array'));
                    scale = 2.^(scale*ones(1,size(array,2)));
                    array = array./scale;
                    array = cat(2,start,array);
                    array = transpose(cumsum(array,2));
                    yunit = double(h5read(fn,'/yunit'));
                    if yunit == 65 %A
                        array = array * 1e12; %Convert A to pA
                        data_temp.unit = "pA";
                    else %V
                        array = array * 1e3;%Convert V to mV
                        data_temp.unit = "mV";
                    end

                    sampleintervall = (double(h5read(fn,'/xdiff'))) * 1000;  %Sample intervall in ms
                    time_cache = ((0:(size(array, 1)-1)) * sampleintervall)';
                    data_table = [time_cache, array];

                    app.RecordingListBox.Items = [app.RecordingListBox.Items,fn_clean]; %add recording to list box

                    % Set baseline epochs, generally first two data points
                    % will be divided in first two data points and rest
                    epoch_baseline = [1, 2; 3, size(array, 1)];

                    % Set spinner limits and resolution
                    app.spinner_limits = [data_table(1,1), data_table(end,1)];
                    app.spinner_resolution = sampleintervall;

                    %Save time correction value in case negative time points
                    %are in recording
                    app.time_correction = 0;

                    %Prepare epoch information in ms for header info
                    header_epochs = ["Epoch information";string(sprintf('Number\t\ttime area (ms)'))];
                    epoch_time_area_string = string(sprintf('%s - %s', string(time_cache(1)), string(time_cache(2))));
                    header_epochs_cache = string(sprintf('%s\t\t%s', "0 (first two datapoints)", epoch_time_area_string));
                    header_epochs = [header_epochs; header_epochs_cache];
                    epoch_time_area_string = string(sprintf('%s - %s', string(time_cache(3)), string(time_cache(end))));
                    header_epochs_cache = string(sprintf('%s\t\t%s', "1 (remaining data points)", epoch_time_area_string));
                    % end
                    header_epochs = [header_epochs; header_epochs_cache];

                    headerinfo_cache = [headerinfo_cache; ""; header_epochs];

                    %Prepare mean and sd tables out of every sweep
                    data_iso = data_table(:,2:end);
                    mean_temp = mean(data_iso(:,:),2,'omitnan');
                    sd_temp = std(data_iso(:,:),0,2,'omitnan');
                    mean_sd_temp = [data_table(:,1), mean_temp, sd_temp];

                    %Prepare selected / unselected swep tables
                    Nr_Sweeps = (size(data_table,2)-1);
                    Nr_of_sweeps_temp = (1:Nr_Sweeps);
                    Unselected_sweeps_temp = [];

                    data_temp.data = data_table;
                    data_temp.selected_sweeps = Nr_of_sweeps_temp;
                    data_temp.unselected_sweeps = Unselected_sweeps_temp;
                    data_temp.all_sweeps =  Nr_of_sweeps_temp;
                    data_temp.data_table_selected = data_table;
                    data_temp.baseline = 0; %for selected baseline correction
                    data_temp.resolution = sampleintervall;
                    data_temp.mean_sd = mean_sd_temp;
                    data_temp.filename = fn_clean;
                    data_temp.headerinfo = headerinfo_cache;
                    data_temp.epoch.baseline = epoch_baseline;
                    data_temp.comment = "";
                    struct_name = sprintf('recording_%d', recording_counter); %create structname. Filename not usable, since struct name can't start with a number (e.g. 211011_Rec_1)
                    loaded_files_loc.(struct_name) = data_temp; %Save recording struct to combined struct

                    recording_counter = recording_counter + 1;
                end

                if ~isempty(no_events) && ~exist('data_temp', 'var')

                    msgbox(["All selected recordings did not contain events:"; no_events],"modal", "warn");
                    if mode == 1 %Replace loaded data
                        app.Reset()
                        return
                    end

                elseif  ~isempty(no_events)
                    msgbox(["The following recordings did not contain events:"; no_events],"modal", "warn");
                end

                cd (selpath)
                app.loaded_files = loaded_files_loc; %Save loaded files struct to property

                %Create and add values for RecordingListBox
                ItemsListBox = 1:size(app.RecordingListBox.Items,2);
                app.RecordingListBox.ItemsData = ItemsListBox;
                addStyle(app.RecordingListBox, app.selectedStyle, "item", 1);
                if mode == 1
                    app.loaded_files.general_comment = "";
                    app.RecordingListBox.Value = app.RecordingListBox.ItemsData; %Select all
                elseif mode == 2
                    new_data_index = shift_recording_counter + 1;
                    new_data_values = app.RecordingListBox.ItemsData(new_data_index:end);
                    selected_recordings = [selected_recordings, new_data_values];
                    app.RecordingListBox.Value = selected_recordings;
                end
                app.RecordingListBox_Value_BU = app.RecordingListBox.Value;

            elseif dir_type == 3 %Load previous session
                app.load_session(save_var)
            else
                return
            end

            %Create recording drop down list and selection spinner
            app.RecordingDropDown.Items = app.RecordingListBox.Items;
            app.RecordingDropDown.ItemsData = app.RecordingListBox.ItemsData;
            app.RecordingDropDown.Value = 1; %Preselect first recording

            if app.RecordingDropDown.ItemsData(end)>1 %More than one recording was loaded
                app.RecordingSpinner.Limits = [1, app.RecordingDropDown.ItemsData(end)];
                app.RecordingSpinner.Value = 1;
                app.RecordingSpinner.Enable = "on";
            else %Fix spinner at value 1
                app.RecordingSpinner.Limits = [0, app.RecordingDropDown.ItemsData(end)];
                app.RecordingSpinner.Value = 1;
                app.RecordingSpinner.Enable = "off";
            end

            app.selected_recording = sprintf('recording_%d', app.RecordingDropDown.Value); %save recording_1 to selected recording property
            app.change_recording(); %Start setting the uifigure controls

            app.RawPanel.Enable = "on"; %Enable app
            app.TabGroup2.SelectedTab = app.RawTab; %Switch to raw tab

            %Enable 'add file' option
            app.AddfilesfolderMenu.Enable = "on";
            app.SaveMenu.Enable = "on";
            app.set_spinner_resolution();
            app.LockmanuelselectionCheckBox.Value = 1; %Lock axes boundaries
            warning('on','all')
        end

        function load_session(app, save_var) %Import properties from loaded mat file
            app.loaded_files = save_var.loaded_files;
            app.RecordingListBox.Items = save_var.RecordingListBox.Items;
            app.RecordingListBox.ItemsData = save_var.RecordingListBox.ItemsData;
            addStyle(app.RecordingListBox, app.selectedStyle, "item", 1);
            app.RecordingListBox.Value = save_var.RecordingListBox.Value;
            app.RecordingListBox_Value_BU = app.RecordingListBox.Value;
            app.HoldinglevelEditField.Value = save_var.HoldinglevelEditField.Value;
            app.holding_command_set = save_var.holding_command_set;

            recording_cache = 'recording_1';
            app.spinner_limits = [app.loaded_files.(recording_cache).data(1,1), app.loaded_files.(recording_cache).data(end,1)];
            app.spinner_resolution =  app.loaded_files.(recording_cache).resolution;
            app.set_spinner_resolution();

            app.OffButton.Value = save_var.OffButton.Value;
            app.EpochButton.Value = save_var.EpisodeButton.Value;
            app.CursorsButton.Value = save_var.CursorsButton.Value;
            app.LeftSpinner.Value = save_var.LeftSpinner.Value;
            app.RightSpinner.Value = save_var.RightSpinner.Value;
            app.EpisodeSpinner.Value = save_var.EpisodeSpinner.Value;

            app.SelectedSweepsDropDown.Value = save_var.analysis_settings.SelectedSweepsDropDown.Value;
            app.Button_ROIBaseline.Value = save_var.analysis_settings.Button_ROIBaseline.Value;
            app.IncludecommandlevelButton.Value = save_var.analysis_settings.IncludecommandlevelButton.Value;
            app.SampleRateEditField.Value = save_var.analysis_settings.SampleRateEditField.Value;

            if isfield(save_var.analysis_settings, 'Analysis_SampleRateSpinner')
                app.Analysis_SampleRateSpinner.Value = save_var.analysis_settings.Analysis_SampleRateSpinner.Value;
            else %For compatibility with sessions saved with older versions
                if save_var.analysis_settings.SampleRateEditField.Value == 1
                    app.Analysis_SampleRateSpinner.Value = 0;
                elseif save_var.analysis_settings.SampleRateEditField.Value > 1 %If sample rate should be increased
                    app.Analysis_SampleRateSpinner.Value = save_var.analysis_settings.SampleRateEditField.Value - 1;
                elseif save_var.analysis_settings.SampleRateEditField.Value < 1 %If sample rate should be decreased
                    app.Analysis_SampleRateSpinner.Value = (round(1/save_var.analysis_settings.SampleRateEditField.Value) - 1) * -1;
                end
            end

            app.save_load_analysis_settings(save_var.analysis_settings, 2); %load analysis settings

            if isfield(app.loaded_files, 'general_comment') %Fetch general comment
                app.GeneralcommentsTextArea.Value = app.loaded_files.general_comment;
            else %For compatibility with sessions saved with v2. Comment fields will be added
                app.loaded_files.general_comment = "";
                %Add comment field to single recordings
                run_on = 1;
                i_recording = 0;
                while run_on == 1 %more dynamic in case additional elements will be added to app.loaded_fields in future releases
                    i_recording = i_recording + 1;
                    recording_cache = sprintf('recording_%d', i_recording);
                    if isfield(app.loaded_files, recording_cache)
                        app.loaded_files.(recording_cache).comment = "";
                    else
                        run_on = 0;
                    end

                end
            end
        end

        function set_ROISpinner(app) %Set left/right boundary of ROI spinner resolution
            if isfield(app.loaded_files, 'recording_1') %If recordings are loaded
                minSpinner = app.loaded_files.recording_1.data(1,1);
            else
                minSpinner = app.analysis_resolution;
            end

            for i_ROISpinner = 1:6
                ROISpinnerLeft = sprintf('ROISpinnerLeft_%d', i_ROISpinner);
                ROISpinnerRight = sprintf('ROISpinnerRight_%d', i_ROISpinner);
                RelativetoDropDown = sprintf('RelativetoDropDown_%d', i_ROISpinner);

                RelativetoDropDown_value = 0;
                if i_ROISpinner > 1 %ROI_1 doesn't have a RelativeDropDown menue. Therfore the value can only be changed starting with ROI_2
                    RelativetoDropDown_value = app.(RelativetoDropDown).Value;
                end
                if app.(ROISpinnerLeft).Value == 0 && RelativetoDropDown_value == 0  %During start-up
                    app.(ROISpinnerLeft).Value = app.analysis_resolution;
                end
                if app.(ROISpinnerRight).Value == 0 && RelativetoDropDown_value == 0 %During start-up
                    app.(ROISpinnerRight).Value = app.analysis_resolution * 2;
                end

                app.(ROISpinnerLeft).Step = app.analysis_resolution;
                app.(ROISpinnerRight).Step = app.analysis_resolution;

                if RelativetoDropDown_value == 0 %If the ROI is relative to another, lower limit will be kept at -inf

                    app.(ROISpinnerLeft).Limits(1) = minSpinner;
                    app.(ROISpinnerRight).Limits(1) = minSpinner + app.analysis_resolution;
                end
            end
            for i_MarkerSpinner = 1:8 %Set marker spinner limits
                MarkerSpinner = sprintf('MarkerSpinner_%d', i_MarkerSpinner);

                if app.(MarkerSpinner).Value < minSpinner
                    app.(MarkerSpinner).Value = minSpinner;
                end
                app.(MarkerSpinner).Limits(1) = minSpinner;
            end
        end

        function change_recording(app) %Will be used when a different recording is selected via the Recording drop down menue in raw tab
            app.RecordingspecificcommentsTextArea.Value = ""; %Clear field
            select_cache = sprintf('recording_%d', app.RecordingDropDown.Value);
            app.RecordingspecificcommentsTextArea.Value = app.loaded_files.(select_cache).comment; %Load specific comment
            Nr_Sweeps = app.loaded_files.(select_cache).all_sweeps(end);
            %Set select sweep spinner
            if Nr_Sweeps <2 %Necessary since Limits must always be a pair of values
                app.SweepSpinner.Limits = [0,1];
                app.SweepSpinner.Value = 0;
                app.SweepSpinner.Enable = "off";
            else
                app.SweepSpinner.Limits = [-1,1];
                app.SweepSpinner.Value = 0;
                app.SweepSpinner.Enable = "on";
            end
            %Set sweeps list box
            app.SweepsListBox.Items = string(1:Nr_Sweeps);
            app.SweepsListBox.ItemsData = (1:Nr_Sweeps);
            app.SweepsListBox.Value = app.loaded_files.(select_cache).selected_sweeps; %to load former sweep selection

            %Set Baseline correction spinner limits and resolution
            app.LeftSpinner.Limits = [app.loaded_files.(select_cache).data(1,1), app.loaded_files.(select_cache).data((end-1),1)];
            % app.LeftSpinner.Limits = [app.loaded_files.(select_cache).resolution, app.loaded_files.(select_cache).data((end-1),1)];
            app.LeftSpinner.Step = app.loaded_files.(select_cache).resolution;
            app.RightSpinner.Limits = [app.loaded_files.(select_cache).data(2,1), app.loaded_files.(select_cache).data((end),1)];
            app.RightSpinner.Step = app.loaded_files.(select_cache).resolution;

            %Set 'Select recording for analysis' button based on former
            %selection
            if isempty(app.RecordingListBox.Value) || (~(ismember(app.RecordingDropDown.Items(app.RecordingDropDown.Value), app.RecordingListBox.Items(app.RecordingListBox.Value))))
                app.SelectrecordingforanalysisButton.Value = 0;
            elseif ismember(app.RecordingDropDown.Items(app.RecordingDropDown.Value), app.RecordingListBox.Items(app.RecordingListBox.Value))
                app.SelectrecordingforanalysisButton.Value = 1;
            end
            %set recording data info box
            app.Raw_RecordingDataText.Value = app.loaded_files.(select_cache).headerinfo;

            app.selected_recording = select_cache;

            app.baseline_calc(select_cache); %calculate baseline values
        end

        function plot_selected(app,select_cache, mode) %Function to plot sweeps of selected recording
            cla(app.RawUIAxes);
            hold(app.RawUIAxes,'on')
            data_table_selected_temp = app.loaded_files.(select_cache).data_table_selected;

            if app.OffButton.Value == 0 %Baseline correction
                data_table_selected_temp =  data_table_selected_temp - app.loaded_files.(select_cache).baseline;
            end
            if app.DisplayallButton.Value == 1 %If every sweep should be shown
                %@sweep_click is a nested function and defined at the end
                %of this function
                app.plotted_data=plot(app.RawUIAxes,data_table_selected_temp(:,1),data_table_selected_temp(:,2:end),'-k', 'ButtonDownFcn',@sweep_click);
            end
            if ~(isempty(app.SweepsListBox.Value))
                if app.HighlightsweepButton.Value == 1 && app.DisplayallButton.Value == 1 %One sweep should be highlighted between the other sweeps
                    plot(app.RawUIAxes,data_table_selected_temp(:,1),data_table_selected_temp(:,(app.SweepsListBox.Value(app.sweep_index_highlight) + 1)),'-r', 'ButtonDownFcn',@sweep_click); %Plot seperatly on top
                elseif app.HighlightsweepButton.Value == 1 && app.DisplayallButton.Value == 0 %If only the highlighted sweep should be shown
                    plot(app.RawUIAxes,data_table_selected_temp(:,1),data_table_selected_temp(:,(app.SweepsListBox.Value(app.sweep_index_highlight) + 1)),'-r', 'ButtonDownFcn',@sweep_click);
                end
                mean_sd_temp = app.loaded_files.(select_cache).mean_sd;
                if app.DisplaymeanButton.Value == 1 && app.OffButton.Value == 1 %Plot mean sweep without baseline correction
                    plot(app.RawUIAxes,mean_sd_temp(:,1),mean_sd_temp(:,2),'-.', 'Color', [1.00,0.41,0.16], 'ButtonDownFcn',@sweep_click);
                elseif app.DisplaymeanButton.Value == 1 && app.OffButton.Value == 0 %Plot mean sweep with baseline correction
                    plot(app.RawUIAxes,mean_sd_temp(:,1),mean_sd_temp(:,4),'-.', 'Color', [1.00,0.41,0.16], 'ButtonDownFcn',@sweep_click);
                end
                if app.DisplaySDButton.Value == 1 && app.OffButton.Value == 1 %Plot sd of sweeps without baseline correction
                    plot(app.RawUIAxes,mean_sd_temp(:,1),mean_sd_temp(:,3),'-.', 'Color', [0.30,0.75,0.93], 'ButtonDownFcn',@sweep_click);
                elseif app.DisplaySDButton.Value == 1 && app.OffButton.Value == 0 %Plot sd of sweeps with baseline correction
                    plot(app.RawUIAxes,mean_sd_temp(:,1),mean_sd_temp(:,5),'-.', 'Color', [0.30,0.75,0.93], 'ButtonDownFcn',@sweep_click);
                end
            end
            hold(app.RawUIAxes,'off')

            if mode == 1 %Different recording was selected, axes must be adjusted
                ylabel_temp = sprintf('Amplitude (%s)', app.loaded_files.(select_cache).unit);
                app.RawUIAxes.YLabel.String = ylabel_temp;
                app.RawUIAxes.YLimMode = 'auto';
                app.RawUIAxes.XLimMode = 'auto';
                if app.LockmanuelselectionCheckBox.Value == 0 %If manual selection of axis limits was not locked, set values to max
                    app.xMinSpinner.Limits = [app.RawUIAxes.XLim(1), (app.RawUIAxes.XLim(2) - app.loaded_files.(select_cache).resolution)];
                    app.xMaxSpinner.Limits = [(app.RawUIAxes.XLim(1) + app.loaded_files.(select_cache).resolution), app.RawUIAxes.XLim(2)];
                    app.xMinSpinner.Value = app.RawUIAxes.XLim(1);
                    app.xMaxSpinner.Value = app.RawUIAxes.XLim(2);
                    app.yMinSpinner.Value = app.RawUIAxes.YLim(1);
                    app.yMaxSpinner.Value = app.RawUIAxes.YLim(2);
                end
                %Set x spinner resolution
                app.xMinSpinner.Step = app.loaded_files.(select_cache).resolution;
                app.xMaxSpinner.Step = app.loaded_files.(select_cache).resolution;

                for i_spinner = 1:8 %correct marker position if necessary
                    MarkerSpinner = sprintf('MarkerSpinner_%d', i_spinner);
                    MarkerButton_raw =  sprintf('Marker%dButton', i_spinner);
                    if   app.(MarkerSpinner).Value > app.RawUIAxes.XLim(2)
                        app.(MarkerSpinner).Limits = [app.loaded_files.(select_cache).resolution, data_table_selected_temp(end,1)];
                        app.(MarkerSpinner).Step = app.loaded_files.(select_cache).resolution;
                        app.(MarkerSpinner).Value = app.RawUIAxes.XLim(2);
                        app.(MarkerButton_raw).Value = 0;
                        app.(MarkerSpinner).Enable = "off";
                    end
                end
                if app.LockmanuelselectionCheckBox.Value == 1 %In case manual axis settings are locked, apply them to plot
                    app.yMinSpinnerValueChanged()
                    app.yMaxSpinnerValueChanged()
                    app.xMinSpinnerValueChanged()
                    app.xMaxSpinnerValueChanged()
                end

            elseif mode == 2 %If other sweep of same recording was selected
                app.yMinSpinnerValueChanged()
                app.yMaxSpinnerValueChanged()
                app.xMinSpinnerValueChanged()
                app.xMaxSpinnerValueChanged()
            end
            app.set_marker(); %draw marker to plot

            function sweep_click(~,eventData) %Function for highlighting or deselecting sweeps
                relative_ydata = eventData.Source.YData' - eventData.Source.YData(1); %normalize to first rows datapoint
                select_cache_nested = sprintf('recording_%d', app.RecordingDropDown.Value);
                relative_position_all = app.loaded_files.(select_cache_nested).data(:, 2:end) - app.loaded_files.(select_cache_nested).data (1, 2:end); %fetch sweeps y values normalize to first rows datapoint
                sweep_index = mean(relative_position_all(2:end, :) == relative_ydata(2:end)); %calculate mean similarity of clicked sweep with recordings sweeps
                sweep_index = find(sweep_index == max(sweep_index)); %sometimes not all values are 100 % identical. Fetches the most identical data row
                if ~isempty(sweep_index) && max(sweep_index) > 0.95 %Reducing the chance, that clicking the mean sweep will remove another sweep
                    value_index = find(app.SweepsListBox.Value == sweep_index);
                    alteration.PreviousValue = app.SweepsListBox.Value;
                    if eventData.Button == 1 % highlight sweep
                        app.HighlightsweepButton.Value = 1;
                        app.sweep_index_highlight = value_index;
                        app.SweepLabel.Value = app.SweepsListBox.Value(app.sweep_index_highlight);
                        alteration.Value = app.SweepsListBox.Value;
                        app.SweepSpinnerValueChanged(alteration)
                    elseif eventData.Button == 2 || 3 % delete sweep
                        app.SweepsListBox.Value(find(app.SweepsListBox.Value == sweep_index)) = [];
                        alteration.Value = app.SweepsListBox.Value;
                        if app.sweep_index_highlight >= value_index && app.sweep_index_highlight ~= 1
                            app.sweep_index_highlight = app.sweep_index_highlight - 1;
                            app.SweepLabel.Value = app.SweepsListBox.Value(app.sweep_index_highlight);
                        end
                        alteration.manual = 1;
                        app.change_sweep(alteration)
                    end
                end
            end

        end

        function set_marker(app) %draw marker to plot

            delete(findobj(app.RawUIAxes,'Type','ConstantLine')) %delete old marker
            if app.Marker1Button.Value == 1
                app.MarkerSpinner_1.Enable = "on";
                xline(app.RawUIAxes,app.MarkerSpinner_1.Value, '--b', {'Marker 1'})
            else
                app.MarkerSpinner_1.Enable = "off";
            end
            if app.Marker2Button.Value == 1
                app.MarkerSpinner_2.Enable = "on";
                xline(app.RawUIAxes,app.MarkerSpinner_2.Value, '--g', {'Marker 2'})
            else
                app.MarkerSpinner_2.Enable = "off";
            end
            if app.Marker3Button.Value == 1
                app.MarkerSpinner_3.Enable = "on";
                xline(app.RawUIAxes,app.MarkerSpinner_3.Value, '--m', {'Marker 3'})
            else
                app.MarkerSpinner_3.Enable = "off";
            end
            if app.Marker4Button.Value == 1
                app.MarkerSpinner_4.Enable = "on";
                xline(app.RawUIAxes,app.MarkerSpinner_4.Value, '--c', {'Marker 4'})
            else
                app.MarkerSpinner_4.Enable = "off";
            end
            if app.Marker5Button.Value == 1
                app.MarkerSpinner_5.Enable = "on";
                xline(app.RawUIAxes,app.MarkerSpinner_5.Value, '--', {'Marker 5'}, 'Color', [0.20,0.45,0.10])
            else
                app.MarkerSpinner_5.Enable = "off";
            end
            if app.Marker6Button.Value == 1
                app.MarkerSpinner_6.Enable = "on";
                xline(app.RawUIAxes,app.MarkerSpinner_6.Value, '--', {'Marker 6'}, 'Color', [1,0.5,0.2])
            else
                app.MarkerSpinner_6.Enable = "off";
            end
            if app.Marker7Button.Value == 1
                app.MarkerSpinner_7.Enable = "on";
                xline(app.RawUIAxes,app.MarkerSpinner_7.Value, '--', {'Marker 7'}, 'Color', [0.318 0.024 0.502])
            else
                app.MarkerSpinner_7.Enable = "off";
            end
            if app.Marker8Button.Value == 1
                app.MarkerSpinner_8.Enable = "on";
                xline(app.RawUIAxes,app.MarkerSpinner_8.Value, '--', {'Marker 8'}, 'Color', [0.929 0.831 0.078])
            else
                app.MarkerSpinner_8.Enable = "off";
            end
        end

        function baseline_calc(app, select_cache) %calculate baselines, mean sweeps and sd of mean sweeps of data table based on settings

            no_of_recordings = app.RecordingListBox.ItemsData(end);
            cor_failed = [];
            BaseCorFailedTextArea_cache = []; %Reset textbox
            for i_baseline = 1:no_of_recordings
                recording_cache = sprintf('recording_%d', i_baseline);

                data_table_selected_temp = app.loaded_files.(recording_cache).data_table_selected; %fetch data table of selected sweeps

                try %Baseline correction
                    if app.CursorsButton.Value == 1 %Fetch boundaries based on cursor. convert time unit from spinner to data point
                        left_boundary = (app.LeftSpinner.Value/app.loaded_files.(recording_cache).resolution) - (app.loaded_files.(recording_cache).data(1,1)/app.loaded_files.(recording_cache).resolution) + 1;
                        right_boundary = (app.RightSpinner.Value/app.loaded_files.(recording_cache).resolution) - (app.loaded_files.(recording_cache).data(1,1)/app.loaded_files.(recording_cache).resolution) + 1;
                    elseif app.EpochButton.Value == 1 %Fetch boundaries based on selected episode (already in data points)
                        selected_epoch = app.EpisodeSpinner.Value + 1; %Fetch selected epoch and change to index
                        left_boundary = app.loaded_files.(recording_cache).epoch.baseline(selected_epoch,1);
                        right_boundary = app.loaded_files.(recording_cache).epoch.baseline(selected_epoch,2);
                        app.LeftSpinner.Value = app.loaded_files.(recording_cache).data(left_boundary,1);
                        app.RightSpinner.Value = app.loaded_files.(recording_cache).data(right_boundary,1);
                    elseif app.OffButton.Value == 1 %No baseline correction; value may be used for baseline output after analysis
                        left_boundary = (app.LeftSpinner.Value/app.loaded_files.(recording_cache).resolution) - (app.loaded_files.(recording_cache).data(1,1)/app.loaded_files.(recording_cache).resolution) + 1;
                        right_boundary = (app.RightSpinner.Value/app.loaded_files.(recording_cache).resolution) - (app.loaded_files.(recording_cache).data(1,1)/app.loaded_files.(recording_cache).resolution) + 1;
                    end
                    app.loaded_files.(recording_cache).baseline_cor_failed = 0; %set base line correction failed marker
                    data_temp_baseline = data_table_selected_temp(int32(left_boundary):int32(right_boundary), 2:end); %isolate data points based on ROI for baseline calculation from all sweeps

                catch %In case cursor boundaries are to large for recording
                    cor_failed = [cor_failed; i_baseline];
                    app.loaded_files.(recording_cache).baseline_cor_failed = 1; %set base line correction failed marker
                    BaseCorFailedTextArea_cache = [BaseCorFailedTextArea_cache; string(app.loaded_files.(recording_cache).filename)];
                    %Define left and right boundary to allow the following
                    %code to proceed
                    left_boundary = 1;
                    right_boundary = 2;
                    data_temp_baseline = data_table_selected_temp(left_boundary:right_boundary, 2:end) * 0; %Set baseline to zero if baseline correction failed
                end

                baseline_temp = mean(data_temp_baseline,1,'omitnan'); %Baseline = mean from ROI
                baseline_temp = [0,  baseline_temp]; %add time coloumn as zero

                app.loaded_files.(recording_cache).baseline = baseline_temp;

                data_table_selected_temp =  data_table_selected_temp - app.loaded_files.(recording_cache).baseline; %substract baselines from data table
                mean_temp = mean(data_table_selected_temp(:,2:end),2,'omitnan'); %calculate mean by row
                sd_temp = std(data_table_selected_temp(:,2:end),0,2,'omitnan'); %calculate sd by row, normalized by #sweeps-1
                mean_sd_temp = [app.loaded_files.(recording_cache).mean_sd(:,1:3), mean_temp, sd_temp];
                app.loaded_files.(recording_cache).mean_sd = mean_sd_temp;

            end
            %Write to text field the recordings where the baseline
            %correction failed
            if isempty(BaseCorFailedTextArea_cache) %No failure
                app.BaseCorFailedTextArea.Value = '';
                app.BaseCorFailedTextArea.BackgroundColor = [1.00, 1.00, 1.00];
            else
                app.BaseCorFailedTextArea.Value = BaseCorFailedTextArea_cache;
                app.BaseCorFailedTextArea.BackgroundColor = [1.00, 0.50, 0.50];
            end

            app.loaded_files.baseline_cor_failed = cor_failed;
            app.baseline_cor_failed_func()

            app.plot_selected(select_cache, 1) %plot
        end

        function analysis_ROI_selection(app) %enables/disables editable analysis settings based on rows check box
            RelativetoDropDown_Items = ["None", "ROI_1"];
            RelativetoDropDown_ItemsData = [0,1];
            ROI_selected_cache = 1;
            for i = 2:6
                CheckBox_ROI = sprintf('CheckBox_ROI_%d', i);
                ROISpinnerLeft = sprintf('ROISpinnerLeft_%d', i);
                ROISpinnerRight = sprintf('ROISpinnerRight_%d', i);
                AnalysisDropDown = sprintf('AnalysisDropDown_%d', i);
                PeakDirDropDown = sprintf('PeakDirDropDown_%d', i);
                SlopeSpinner_Lower = sprintf('SlopeSpinner_Lower_%d', i);
                SlopeSpinner_Upper = sprintf('SlopeSpinner_Upper_%d', i);
                RelativetoDropDown = sprintf('RelativetoDropDown_%d', i);
                Analysis_RegressionDropDown = sprintf('Analysis_RegressionDropDown_%d', i);

                app.(ROISpinnerLeft).Enable = app.(CheckBox_ROI).Value;
                app.(ROISpinnerRight).Enable = app.(CheckBox_ROI).Value;
                app.(AnalysisDropDown).Enable = app.(CheckBox_ROI).Value;
                app.(PeakDirDropDown).Enable = app.(CheckBox_ROI).Value;
                app.(SlopeSpinner_Lower).Enable = app.(CheckBox_ROI).Value;
                app.(SlopeSpinner_Upper).Enable = app.(CheckBox_ROI).Value;
                app.(RelativetoDropDown).Enable = app.(CheckBox_ROI).Value;
                app.(Analysis_RegressionDropDown).Enable = app.(CheckBox_ROI).Value;
                if app.(CheckBox_ROI).Value == 1 %add ROI to relative to drop down if check box if selected
                    ROI_selected_cache = [ROI_selected_cache, i];
                    app.(RelativetoDropDown).Items = RelativetoDropDown_Items;
                    app.(RelativetoDropDown).ItemsData = RelativetoDropDown_ItemsData;
                    RelativetoDropDown_Item_cache = string(sprintf('ROI_%d', i));
                    RelativetoDropDown_Items = [RelativetoDropDown_Items, RelativetoDropDown_Item_cache];
                    RelativetoDropDown_ItemsData = [RelativetoDropDown_ItemsData, i];
                end
            end
            app.ROI_selected = ROI_selected_cache;
            app.AnalysisDropDown_1ValueChanged();
        end

        function [peaks_result] = peakdirection_abs(~, recording, mode) %calculates peak direction and amplitude

            if mode == 1 %Amplitude analysis, amplitude and peak direction will be determined
                min_value = min(recording);
                max_value = max(recording);
                delta_value = (abs(max_value - recording(1)) - abs(min_value - recording(1)))'; %if positive, positive peak direction. If negative, negative peak direction

                peaks_result = [];
                for i = 1:size(delta_value,1) %Determine single sweeps peak direction (-1 = negative, 1 = positive, 0 = no peak)
                    if isnan(delta_value(i))
                        peak_result_cache = [NaN, NaN];
                    elseif delta_value(i) < 0
                        peak_result_cache = [min_value(i), -1];
                    elseif delta_value(i) > 0
                        peak_result_cache = [max_value(i), 1];
                    else
                        peak_result_cache = [max_value(i), 0];
                    end
                    peaks_result = [peaks_result; peak_result_cache];
                end

            elseif mode == 2 %slope analysis, only peak direction will be determined
                delta_value = (recording(end,:)-recording(1,:))';
                peaks_result = [];
                for i = 1:size(delta_value,1)
                    if isnan(delta_value(i))
                        peak_result_cache = [NaN, NaN];
                    elseif delta_value(i) < 0
                        peak_result_cache = [0, -1];

                    elseif delta_value(i) > 0
                        peak_result_cache = [0, 1];
                    else
                        peak_result_cache = [0, 0];
                    end
                    peaks_result = [peaks_result; peak_result_cache];
                end

            end
        end

        function [reg_result, analysis_log_regression, outofboundaries]= Multiregression(~, sweep_single, lower_bound, upper_bound, peakreg_set, model_set) %
            %Calculating the ROIs slope or tau based on chossen regression model.
            %peakreg_set provides information about peak direction (-/+) and if the rise (1) or
            %decay (2) phase should be calculated. peak_reg = 0, if no amplitude was detected. model_set sets which regression
            %model will be used (1 = linear, 2 = single exponentiel, 3 = double
            %exponentiel, 4 = all models

            %Set amplitude to zero based on phase to analyse
            if peakreg_set == 1 || peakreg_set == -1 %if rise, normalize to first datapoint
                sweep_single(:,2) = sweep_single(:,2) - sweep_single(1,2);
            elseif peakreg_set == 2 || peakreg_set == -2  %if decay, normalize to last datapoint
                sweep_single(:,2) = sweep_single(:,2) - sweep_single(end,2);
            else %if no amplitude was detected (peak_reg = 0)
                if model_set == 1
                    analysis_log_regression = "No amplitude, slope = zero";
                    reg_result = [NaN, 0, NaN];
                elseif model_set == 2
                    analysis_log_regression = "No amplitude, tau = zero";
                    reg_result = [NaN, 0, NaN];
                elseif model_set == 3
                    analysis_log_regression = "No amplitude, tau = zero";
                    reg_result = [NaN, NaN, 0, NaN];
                elseif model_set == 4
                    analysis_log_regression = "No amplitude, slope/tau = zero";
                    reg_result = [NaN, 0, NaN, NaN, 0, NaN, NaN, NaN, 0, NaN];
                end
                outofboundaries = NaN;
                return
            end

            analysis_log_regression =[];
            amplitude_left = sweep_single(1,2);
            amplitude_right  = sweep_single(end,2);

            %set ROI amplitude limits based on lower_boundary-upper_boundary % of max amplitude
            if peakreg_set == 1 || peakreg_set == -1
                max_amplitude = amplitude_right * upper_bound/100;
                min_amplitude = amplitude_right * lower_bound/100;
            elseif peakreg_set == 2 || peakreg_set == -2
                max_amplitude = amplitude_left * upper_bound/100;
                min_amplitude = amplitude_left * lower_bound/100;
            end

            %Search for first datapoint of sweep which is larger of
            %min_amplitude or lower than max_amplitude. The search moves
            %inwards from the outer boundaries of the sweeps datapoints
            down_counter = 0;
            if peakreg_set == 1 %positive peak, rise
                while down_counter < size(sweep_single, 1)
                    rightbound_point = size(sweep_single, 1) - down_counter;
                    if sweep_single(rightbound_point, 2) <= max_amplitude
                        break
                    end
                    down_counter = down_counter + 1;
                end

                for leftbound_point = 1:size(sweep_single, 1)
                    if sweep_single(leftbound_point, 2) >= min_amplitude
                        break
                    end
                end
            elseif peakreg_set == -1 %negative peak, rise

                while down_counter < size(sweep_single, 1)
                    rightbound_point = size(sweep_single, 1) - down_counter;
                    if sweep_single(rightbound_point, 2) >= max_amplitude
                        break
                    end
                    down_counter = down_counter + 1;
                end

                for leftbound_point = 1:size(sweep_single, 1)
                    if sweep_single(leftbound_point, 2) <= min_amplitude
                        break
                    end
                end

            elseif peakreg_set == 2 %positive peak, decay
                for leftbound_point = 1:size(sweep_single, 1)
                    if sweep_single(leftbound_point, 2) <= max_amplitude
                        break
                    end
                end

                while down_counter < size(sweep_single, 1)
                    rightbound_point = size(sweep_single, 1) - down_counter;
                    if sweep_single(rightbound_point, 2) >= min_amplitude
                        break
                    end
                    down_counter = down_counter + 1;
                end

            elseif peakreg_set == -2 %negative peak, decay
                for leftbound_point = 1:size(sweep_single, 1)
                    if sweep_single(leftbound_point, 2) >= max_amplitude
                        break
                    end
                end

                while down_counter < size(sweep_single, 1)
                    rightbound_point = size(sweep_single, 1) - down_counter;
                    if sweep_single(rightbound_point, 2) <= min_amplitude
                        break
                    end
                    down_counter = down_counter + 1;
                end
            end

            reg_result =[];
            if ~(leftbound_point < rightbound_point) %in case no data points are between left and right bound
                %Create NaN vectors
                analysis_log_regression = [];
                if model_set < 3
                    reg_result = [NaN, 0, NaN];
                elseif model_set == 3
                    reg_result = [NaN, NaN, 0, NaN];
                elseif model_set == 4
                    reg_result = [NaN, 0, NaN, NaN, 0, NaN, NaN, NaN, 0, NaN];
                end
                outofboundaries = NaN;
            else %Do the regressions
                sweep_single_cut = sweep_single(leftbound_point:rightbound_point, :);
                outofboundaries = 0;
                if model_set == 1 || model_set == 4 %linear regression

                    [coefficients, reg_params] = polyfit(sweep_single_cut(:, 1),sweep_single_cut(:, 2), 1); %linear regression

                    reg_result_cache = coefficients(1); %isolate slope

                    rsquare = 1 - (reg_params.normr/norm(sweep_single(leftbound_point:rightbound_point, 2) - mean(sweep_single(leftbound_point:rightbound_point, 2))))^2; %calculate rsquare

                    %Check if the slope directions fits with the regression
                    %parameters (e.g. the rise slope of a positive peak
                    %should'nt be negative)
                    if reg_result_cache > 0 && (peakreg_set == -1 || peakreg_set == 2)
                        analysis_log_regression = "Unexpected positive slope in linear regression";
                        reg_result = [NaN, ((rightbound_point-leftbound_point) + 1), rsquare];
                    elseif   reg_result_cache < 0 && (peakreg_set == 1 || peakreg_set == -2)
                        analysis_log_regression = "Unexpected negative slope in linear regression";
                        reg_result = [NaN, ((rightbound_point-leftbound_point) + 1), rsquare];
                    else %Save results
                        reg_result = [reg_result_cache, ((rightbound_point-leftbound_point) + 1), rsquare];
                    end
                end
                if model_set == 2 || model_set == 4 %single exponential regression
                    try %to avoid error in case regression fails
                        [coefficients, GOF] = fit(sweep_single_cut(:,1),sweep_single_cut(:,2),'exp1');
                        rsquare = GOF.rsquare;
                        tau1 = -1/coefficients.b; %calculate tau
                        reg_result = [reg_result, tau1, ((rightbound_point-leftbound_point) + 1), rsquare];
                    catch
                        analysis_log_regression = "Single exponential regression failed";
                        reg_result = [reg_result, NaN, ((rightbound_point-leftbound_point) + 1), NaN];
                    end
                end
                if model_set == 3 || model_set == 4 %double exponential regression
                    try %to avoid error in case regression fails
                        [coefficients, GOF] = fit(sweep_single_cut(:,1),sweep_single_cut(:,2),'exp2');
                        rsquare = GOF.rsquare;
                        tau1 = -1/coefficients.b; %calculate tau(fast)
                        tau2 = -1/coefficients.d; %calculate tau(slow)
                        reg_result = [reg_result, tau1, tau2, ((rightbound_point-leftbound_point) + 1), rsquare];
                    catch
                        analysis_log_regression = "Double exponential regression failed";
                        reg_result = [reg_result, NaN, NaN, ((rightbound_point-leftbound_point) + 1), NaN];
                    end
                end
            end
        end

        function setListBox_analysed(app) %Set list boxes and drop down menues of results tab after analysis
            RecListBox_data_cache = app.results_analysis.RecListBox_data(:,2:end);
            RecListBox_data_cache = unique(RecListBox_data_cache, 'rows'); %Remove recording doublets, if 'Add to results' was selected
            RecListBox_data_cache_recnumber = RecListBox_data_cache(:,1); %Isolate recording name
            RecListBox_data_cache_recnumber = erase(RecListBox_data_cache_recnumber,"recording_"); %Isolate recording number...
            RecListBox_data_cache_recnumber = str2double(RecListBox_data_cache_recnumber); %...and convert string to numeric
            [~, RecListBox_data_cache_recnumber_idx] = sort(RecListBox_data_cache_recnumber); %Get index for sorting
            RecListBox_data_cache = RecListBox_data_cache(RecListBox_data_cache_recnumber_idx,:); %Sort table based on recording number

            RecListBox_data_number = string((1:size(RecListBox_data_cache,1)))';
            RecListBox_data_cache = [RecListBox_data_number, RecListBox_data_cache];
            app.results_analysis.RecListBox_data = RecListBox_data_cache;

            %Set list box of analysed recordings
            app.RecordingListBox_2.Items = RecListBox_data_cache(:,4);
            app.RecordingListBox_2.ItemsData = str2double(RecListBox_data_cache(:,1));
            app.RecordingListBox_2.Value = 1;
            app.results_analysis.RecListBox_data_set = 1;

            if app.file_type_mode == 1
                %Remove dublicates from axisDropDown_Met_list without altering
                %the order
                axisDropDown_Met_list_cache = app.results_analysis.axisDropDown_Met_list;
                axisDropDown_Met_list_cache = unique(axisDropDown_Met_list_cache, 'rows', 'stable');
                app.results_analysis.axisDropDown_Met_list = axisDropDown_Met_list_cache;

                %Set x-axis items in drop down for selection before plotting
                app.Results_xaxisDropDown.Items = axisDropDown_Met_list_cache(:,1);
                app.Results_xaxisDropDown.ItemsData = str2double(axisDropDown_Met_list_cache(:,2));

                %Set y-axis items in drop down for selection before plotting
                for i = 1:6
                    Results_yaxisDropDown_Met = sprintf('Results_yaxisDropDown_Met_%d', i);
                    Results_yaxisDropDown_Rec = sprintf('Results_yaxisDropDown_Rec_%d', i);
                    app.(Results_yaxisDropDown_Met).Items= axisDropDown_Met_list_cache(:,1);
                    app.(Results_yaxisDropDown_Met).ItemsData= str2double(axisDropDown_Met_list_cache(:,2));
                    app.(Results_yaxisDropDown_Rec).Items = app.RecordingListBox_2.Items;
                    app.(Results_yaxisDropDown_Rec).ItemsData = app.RecordingListBox_2.ItemsData;
                end
            end
            app.RecordingListBox_2ValueChanged(); %Set results table
        end

        function plot_results(app)
            %Plot selected results based on setting in Results tab
            cla(app.Results_UIAxes); %clear old plot

            %Set line and marker options
            if app.LineButton.Value == 1
                line_cache = '-';
                marker_cache = 'none';
            elseif app.MarkerButton.Value == 1
                line_cache = 'none';
                marker_cache = '.';
            elseif app.LineMarkerButton.Value == 1
                line_cache = '-';
                marker_cache = '.';
            end

            %Define x-values
            x_values_loc = app.Results_xaxisDropDown.Value;

            if x_values_loc == 2 || x_values_loc == 3 %In case a time was selected, transform to selected unit
                if app.Results_timescaleDropDown.Value == 1
                    app.Results_UIAxes.XLabel.String = "time (ms)";
                elseif app.Results_timescaleDropDown.Value == 1000
                    app.Results_UIAxes.XLabel.String = "time (s)";
                elseif app.Results_timescaleDropDown.Value == 60000
                    app.Results_UIAxes.XLabel.String = "time (min)";
                end
            else
                app.Results_UIAxes.XLabel.String = cell2mat(app.Results_xaxisDropDown.Items((app.Results_xaxisDropDown.ItemsData == x_values_loc)));
            end

            %In case absolute start time was selected, choose if the lowest start time
            %should be set to zero and the rest displayed relative to it
            x_cor = [];
            if x_values_loc == 3 && app.XCorCheckBox.Value == 1
                for i_x_cor = 1:6 %For all possible y-values
                    %Isolate start times of all sweeps
                    if i_x_cor == 1
                        Results_yaxisDropDown_Rec_cache = sprintf('Results_yaxisDropDown_Rec_%d', i_x_cor);
                        selected_cache = app.results_analysis.RecListBox_data(app.(Results_yaxisDropDown_Rec_cache).Value,2);
                        x_cor = [x_cor; double(app.results_analysis.(selected_cache).analysis_table(:,x_values_loc))]; %#ok<*AGROW>
                    else
                        CheckBox_cache = sprintf('Results_yaxisCheckBox_%d', i_x_cor);
                        if app.(CheckBox_cache).Value == 1
                            Results_yaxisDropDown_Rec_cache = sprintf('Results_yaxisDropDown_Rec_%d', i_x_cor);
                            selected_cache = app.results_analysis.RecListBox_data(app.(Results_yaxisDropDown_Rec_cache).Value,2);
                            x_cor = [x_cor; double(app.results_analysis.(selected_cache).analysis_table(:,x_values_loc))];
                        end
                    end
                end
                x_cor = min(x_cor); %Search for lowest absolute start time
            else
                x_cor = 0; %No correction
            end

            hold(app.Results_UIAxes,'off')

            for i_plot = 1:6
                %Define marker colour
                lamp_cache = sprintf('Results_yaxisLamp_%d', i_plot);
                colour_cache = app.(lamp_cache).Color;

                %Create the plot
                if i_plot == 1
                    selected_cache = app.results_analysis.RecListBox_data(app.Results_yaxisDropDown_Rec_1.Value,2);
                    %Isolate x_values. Correct time unit and set start time
                    %to zero if selected
                    x_value = ((double(app.results_analysis.(selected_cache).analysis_table(:,x_values_loc)) - x_cor) / app.Results_timescaleDropDown.Value);
                    y_value =  double(app.results_analysis.(selected_cache).analysis_table(:,app.Results_yaxisDropDown_Met_1.Value));
                    plot(app.Results_UIAxes,x_value, y_value, 'LineStyle', line_cache, 'Color', colour_cache, "Marker", marker_cache, "MarkerFaceColor",colour_cache, "MarkerSize", 20);
                    app.Results_UIAxes.YLabel.String = app.Results_yaxisDropDown_Met_1.Items{app.Results_yaxisDropDown_Met_1.ItemsData==app.Results_yaxisDropDown_Met_1.Value};
                    hold(app.Results_UIAxes,'on')
                else
                    CheckBox_cache = sprintf('Results_yaxisCheckBox_%d', i_plot);
                    if app.(CheckBox_cache).Value == 1
                        Results_yaxisDropDown_Rec_cache = sprintf('Results_yaxisDropDown_Rec_%d', i_plot);
                        Results_yaxisDropDown_Met_cache =  sprintf('Results_yaxisDropDown_Met_%d', i_plot);
                        selected_cache = app.results_analysis.RecListBox_data(app.(Results_yaxisDropDown_Rec_cache).Value,2);
                        x_value = ((double(app.results_analysis.(selected_cache).analysis_table(:,x_values_loc)) - x_cor) / app.Results_timescaleDropDown.Value);
                        y_value =  double(app.results_analysis.(selected_cache).analysis_table(:,app.(Results_yaxisDropDown_Met_cache).Value));
                        plot(app.Results_UIAxes,x_value, y_value, 'LineStyle', line_cache, 'Color', colour_cache, "Marker", marker_cache, "MarkerFaceColor",colour_cache, "MarkerSize", 20);

                    end
                end
            end
        end
        function altered_table = sample_increase(app, raw_table)
            %Digitally alter the sample rate
            alter_factor = abs(app.Analysis_SampleRateSpinner.Value) + 1; %Calculate decrease_factor. Spinner values range from -4 (for 5-fold reduction) over 0 (no change) to 4 (for 5-fold increase). Therefore the addition of 1 to the value
            if app.Analysis_SampleRateSpinner.Value > 0 %Increase sample rate  by calculating new data points based on the differences between the raw_tables datapoints
                diff_table = diff(raw_table)/alter_factor; %Calculat differences and calculate new delta between data points of altered_table
                altered_table = raw_table(1,:); %Isolate first line
                for i_alter = 1:size(diff_table,1)
                    diff_row = diff_table(i_alter,:);
                    for i_delta = 1:(alter_factor - 1) %add new data points to table
                        altered_table_cache = altered_table(end,:);
                        altered_table_cache = altered_table_cache + diff_row;
                        altered_table = [altered_table; altered_table_cache];
                    end
                    altered_table = [altered_table; raw_table(i_alter + 1,:)]; %fetch next line from raw table
                end
            elseif app.Analysis_SampleRateSpinner.Value < 0 %Decrease sample rate by skipping data points of the raw_table
                altered_table_rows = floor(size(raw_table,1)/(alter_factor));
                next_row = 1;
                altered_table = [];
                for i_alter = 1:altered_table_rows
                    altered_table = [altered_table; raw_table(next_row,:)];
                    next_row = next_row + alter_factor;
                end
            else
                altered_table = raw_table;
            end
        end

        function baseline_cor_failed_func(app) %blocks analysis button is baseline correction failed for one of the selected recordings
            failed_cache = app.loaded_files.baseline_cor_failed;
            if isempty(app.RecordingListBox.Value) %Empty is app.RecordingListBox.Value, filled one is matrix/string
                selected_recordings = [];
            else
                selected_recordings = app.RecordingListBox.Value;
            end
            if isempty(selected_recordings) || sum(ismember(failed_cache, selected_recordings)) > 0 %If No recordings are selected or the baseline correction by at least one of the selected recordings failed...
                app.StartanalysisButton.Enable = "off"; %...disable analyse button
            else
                app.StartanalysisButton.Enable = "on"; %else activate analysis button
            end
        end

        function save_var = save_load_analysis_settings(app,save_var, mode) %Save or load analysis settings

            for i = 1:6

                ROISpinnerLeft = sprintf('ROISpinnerLeft_%d', i);
                ROISpinnerRight = sprintf('ROISpinnerRight_%d', i);
                AnalysisDropDown = sprintf('AnalysisDropDown_%d', i);
                PeakDirDropDown = sprintf('PeakDirDropDown_%d', i);
                SlopeSpinner_Lower = sprintf('SlopeSpinner_Lower_%d', i);
                SlopeSpinner_Upper = sprintf('SlopeSpinner_Upper_%d', i);
                Analysis_RegressionDropDown = sprintf('Analysis_RegressionDropDown_%d', i);

                CheckBox_ROI = sprintf('CheckBox_ROI_%d', i);
                RelativetoDropDown = sprintf('RelativetoDropDown_%d', i);

                if mode == 1 %save
                    save_var.analysis_settings.(ROISpinnerLeft).Value = app.(ROISpinnerLeft).Value;
                    save_var.analysis_settings.(ROISpinnerRight).Value = app.(ROISpinnerRight).Value;
                    save_var.analysis_settings.(AnalysisDropDown).Value = app.(AnalysisDropDown).Value;
                    save_var.analysis_settings.(PeakDirDropDown).Value = app.(PeakDirDropDown).Value;
                    save_var.analysis_settings.(SlopeSpinner_Lower).Value = app.(SlopeSpinner_Lower).Value;
                    save_var.analysis_settings.(SlopeSpinner_Upper).Value = app.(SlopeSpinner_Upper).Value;
                    save_var.analysis_settings.(Analysis_RegressionDropDown).Value = app.(Analysis_RegressionDropDown).Value;

                    if i > 1
                        save_var.analysis_settings.(RelativetoDropDown).Value = app.(RelativetoDropDown).Value;
                        save_var.analysis_settings.(CheckBox_ROI).Value = app.(CheckBox_ROI).Value;
                    end
                elseif mode == 2 %load
                    app.(ROISpinnerLeft).Value = save_var.(ROISpinnerLeft).Value;
                    app.(ROISpinnerRight).Value = save_var.(ROISpinnerRight).Value;
                    app.(AnalysisDropDown).Value = save_var.(AnalysisDropDown).Value;
                    app.(PeakDirDropDown).Value = save_var.(PeakDirDropDown).Value;
                    app.(SlopeSpinner_Lower).Value = save_var.(SlopeSpinner_Lower).Value;
                    app.(SlopeSpinner_Upper).Value = save_var.(SlopeSpinner_Upper).Value;
                    app.(Analysis_RegressionDropDown).Value = save_var.(Analysis_RegressionDropDown).Value;

                    if i > 1
                        app.(RelativetoDropDown).Value = save_var.(RelativetoDropDown).Value;
                        app.(CheckBox_ROI).Value = save_var.(CheckBox_ROI).Value;
                    end
                end
            end
            app.CheckBox_ROI2ValueChanged()
        end

        function new_changes(app)
            app.save_session_done = 0;
        end

        function SendMarkerValues(app, marker_value, ROI)
            if ROI == 0 %In case "Send to..." was selected
                return
            end
            boundary = num2str(ROI);
            if boundary(2) == '2' && marker_value == app.analysis_resolution %If right boundary should be changed and value is the minimum
                marker_value = marker_value + app.analysis_resolution; %to make sure, that right ROI boundary is always higher than left one
                LeftSpinner_cache = sprintf('ROISpinnerLeft_%s', boundary(1));
                app.(LeftSpinner_cache).Value = app.analysis_resolution;
            end
            %Send marker value to specific ROI bound
            if ROI == 11
                app.ROISpinnerLeft_1.Value = marker_value;
            elseif ROI == 21
                app.ROISpinnerLeft_2.Value = marker_value;
            elseif ROI == 31
                app.ROISpinnerLeft_3.Value = marker_value;
            elseif ROI == 41
                app.ROISpinnerLeft_4.Value = marker_value;
            elseif ROI == 51
                app.ROISpinnerLeft_5.Value = marker_value;
            elseif ROI == 61
                app.ROISpinnerLeft_6.Value = marker_value;
            elseif ROI == 12
                app.ROISpinnerRight_1.Value = marker_value;
            elseif ROI == 22
                app.ROISpinnerRight_2.Value = marker_value;
            elseif ROI == 32
                app.ROISpinnerRight_3.Value = marker_value;
            elseif ROI == 42
                app.ROISpinnerRight_4.Value = marker_value;
            elseif ROI == 52
                app.ROISpinnerRight_5.Value = marker_value;
            elseif ROI == 62
                app.ROISpinnerRight_6.Value = marker_value;
            else
                return
            end

            if boundary(2) == '1' %If left boundary was changed
                app.ROISpinnerLeft_1ValueChanged();
            elseif boundary(2) == '2' %If right boundary was changed
                app.ROISpinnerRight_1ValueChanged();
            end
        end

        function Reset(app)
            app.TabGroup2.Visible = 0;
            app.RawPanel.Enable = "off"; %Disable app
            app.AnalysisPanel.Enable = "off"; %Disable app
            app.TabGroup2.SelectedTab = app.RawTab; %Switch to raw tab

            %Disable 'add file' option
            app.AddfilesfolderMenu.Enable = "off";
            app.AddfilesMenu.Enable = "off";
            app.SaveMenu.Enable = "off";
            app.save_session_done = 1;

            app.LockmanuelselectionCheckBox.Value = 0; %unlock axes boundaries
            app.AnalysisAddtoresultsCheckBox.Enable = "off";
            app.AnalysisAddtoresultsCheckBox.Value  = 0;

            %Delete Values
            addStyle(app.RecordingListBox, app.baseStyle);
            app.RecordingListBox.Items = {};
            app.RecordingListBox.ItemsData = {};
            app.GeneralcommentsTextArea.Value = "";
            app.RecordingListBox_2.Items = {};
            app.Results_UITable2.Data = {};
            app.results_analysis = [];

        end

        function set_spinner_resolution(app) %Set spinner limits and resolution
            leftboundaries = [app.spinner_limits(1), (app.spinner_limits(2)-app.spinner_resolution)];
            rightboundaries = [(app.spinner_limits(1)+ app.spinner_resolution), app.spinner_limits(2)];

            for i_spinner = 1:8
                MarkerSpinner = sprintf('MarkerSpinner_%d', i_spinner);
                app.(MarkerSpinner).Limits = app.spinner_limits;
            end

            app.xMinSpinner.Limits = leftboundaries;
            app.LeftSpinner.Limits = leftboundaries;
            app.xMaxSpinner.Limits = rightboundaries;
            app.RightSpinner.Limits = rightboundaries;
            app.xMinSpinner.Step = app.spinner_resolution;
            app.LeftSpinner.Step = app.spinner_resolution;
            app.xMaxSpinner.Step = app.spinner_resolution;
            app.RightSpinner.Step = app.spinner_resolution;

            for i_spinner = 1:6
                ROISpinnerLeft = sprintf('ROISpinnerLeft_%d', i_spinner);
                ROISpinnerRight = sprintf('ROISpinnerRight_%d', i_spinner);
                app.(ROISpinnerLeft).Limits = leftboundaries;
                app.(ROISpinnerRight).Limits = rightboundaries;
                app.(ROISpinnerLeft).Step = app.spinner_resolution;
                app.(ROISpinnerRight).Step = app.spinner_resolution;
            end

        end

        function menue_enable(app, state)
            app.DataMenu.Enable = state;
            app.OptionsMenu.Enable = state;
            app.AboutMenu.Enable = state;
        end

        function set_highlighted_sweep_label(app)
            app.SweepLabel.Value = app.SweepsListBox.Value(app.sweep_index_highlight);
        end

        function proceed = Replace_data_warning(app)
            app.menue_state =[app.RawPanel.Enable, app.AnalysisPanel.Enable];
            app.RawPanel.Enable = "off";
            app.AnalysisPanel.Enable = "off";
            save_session_cache = app.save_session_done;

            msg_on = 1;
            while msg_on == 1
                msg = sprintf('Do you want to replace the loaded data?\nUnsaved changes will be lost.');
                title = 'Replace data';
                if app.save_session_done == 0
                    selection = uiconfirm(app.UIFigure,msg,title, ...
                        'Options',{'Replace data','Save session and Replace data','Cancel'}, ...
                        'DefaultOption',3,'CancelOption',3, "Icon","warning");
                else
                    selection = uiconfirm(app.UIFigure,msg,title, ...
                        'Options',{'Replace data','Cancel'}, ...
                        'DefaultOption',2,'CancelOption',2, "Icon","warning");
                end
                if eq(selection, "Save session and Replace data")
                    save_state = app.save_session_done;
                    app.save_session_done = 0;
                    app.SaveMenuSelected()
                    if app.save_session_done == 0
                        app.save_session_done = save_state;
                    else
                        msg_on = 0;
                    end
                    proceed = 1;
                elseif eq(selection, "Replace data")
                    app.save_session_done = 1;
                    msg_on = 0;
                    proceed = 1;
                else %eq(selection, "Cancel")
                    msg_on = 0;
                    proceed = 0;
                end

            end
            app.save_session_done = save_session_cache;

            app.RawPanel.Enable = app.menue_state(1);
            app.AnalysisPanel.Enable = app.menue_state(2);
        end

        function change_sweep(app, event)
            %Recalculate the displayed data in case sweeps were
            %(de-)selected
            app.new_changes()
            %In case every sweep was de-selected and the recording was
            %marked as included in the analysis, remove them from the
            %selection
            if isempty(app.RecordingListBox.Value)
                RecordingListBox_cache = [];
            else
                RecordingListBox_cache = sort(app.RecordingListBox.Value);
            end

            if ~isempty(app.SweepsListBox.Value)
                if ~ismember(app.SweepLabel.Value, app.SweepsListBox.Value) || app.sweep_index_highlight > size(app.SweepsListBox.Value, 2)
                    if app.sweep_index_highlight > 1
                        app.sweep_index_highlight = app.sweep_index_highlight - 1;
                    end
                end

                if size(event.Value, 2) > size(event.PreviousValue, 2)
                    if event.Value(end) < app.SweepsListBox.Value(app.sweep_index_highlight)
                        app.sweep_index_highlight = app.sweep_index_highlight + 1;
                    end
                elseif size(event.Value, 2) < size(event.PreviousValue, 2) && ~isempty(event.Value)
                    if app.SweepLabel.Value < app.SweepsListBox.Value(app.sweep_index_highlight) && app.sweep_index_highlight > 1
                        app.sweep_index_highlight = app.sweep_index_highlight - 1;
                    end
                end
                app.SweepsListBox.Value = sort(app.SweepsListBox.Value);
            end

            if isempty(app.SweepsListBox.Value)
                app.sweep_index_highlight = 1;
                app.SweepLabel.Value = 0;
                app.SweepSpinner.Limits = [0, 1];
                app.SweepSpinner.Enable = "off";

            elseif size(app.SweepsListBox.Value, 2) == 1
                app.sweep_index_highlight = 1;
                app.SweepLabel.Value = app.SweepsListBox.Value(1);
                app.SweepSpinner.Limits = [0, 1];
                app.SweepSpinner.Enable = "off";
            elseif (app.sweep_index_highlight == size(app.SweepsListBox.Value, 2))
                app.SweepSpinner.Limits = [-1, 0];
                app.SweepSpinner.Enable = "on";
                app.SweepLabel.Value = app.SweepsListBox.Value(app.sweep_index_highlight);
            elseif app.sweep_index_highlight == 1
                app.SweepSpinner.Limits = [0, 1];
                app.SweepSpinner.Enable = "on";
                app.SweepLabel.Value = app.SweepsListBox.Value(app.sweep_index_highlight);
            else
                app.SweepSpinner.Limits = [-1, 1];
                app.SweepSpinner.Enable = "on";
                app.SweepLabel.Value = app.SweepsListBox.Value(app.sweep_index_highlight);
            end

            if isempty(app.SweepsListBox.Value) && ismember(app.RecordingDropDown.Items(app.RecordingDropDown.Value), app.RecordingListBox.Items(RecordingListBox_cache))
                value_temp = app.RecordingListBox.Value; %Copy selection
                value_temp(value_temp == app.RecordingDropDown.Value) = []; %Delete current recording from selection
                app.RecordingListBox.Value = value_temp;
                app.RecordingListBox_Value_BU = app.RecordingListBox.Value;
                app.SelectrecordingforanalysisButton.Value = 0;
            end

            app.SweepsListBox.Value = sort(app.SweepsListBox.Value); %Fetch value list and sort them (new selection will always be added at the end of the items proprty, which would otherwise cause problems)

            select_cache = sprintf('recording_%d', app.RecordingDropDown.Value); %Create string for struct selection

            %fetch recordings list of total no of sweeps (1: no of sweeps).
            %Will be used as index to isolate the selected sweeps from data table
            unselected_sweeps_temp = app.loaded_files.(select_cache).all_sweeps;
            if ~(isempty(app.SweepsListBox.Value))
                unselected_sweeps_temp(:,app.SweepsListBox.Value) = []; %remove selected sweeps in case other sweeps are still selected
            end
            unselected_sweeps_temp = unselected_sweeps_temp + 1; %first coloumn = x-values
            app.loaded_files.(select_cache).selected_sweeps = app.SweepsListBox.Value; %save to property
            app.loaded_files.(select_cache).unselected_sweeps = unselected_sweeps_temp; %save to property
            data_table_selected_temp = app.loaded_files.(select_cache).data; %fetch recordings data table
            data_table_selected_temp(:,unselected_sweeps_temp) = NaN; %Replace unselected sweeps with NaN to keep number of sweeps
            app.loaded_files.(select_cache).data_table_selected = data_table_selected_temp; %save to property

            %Recalculate mean and sd sweep from selection and save to
            %property
            mean_temp = mean(data_table_selected_temp(:,2:end),2,'omitnan');
            sd_temp = std(data_table_selected_temp(:,2:end),0,2,'omitnan');
            mean_sd_temp = [mean_temp, sd_temp];
            app.loaded_files.(select_cache).mean_sd(:,2:3) = mean_sd_temp;
            app.baseline_calc(select_cache) %calculate selected sweeps baselines and new mean and sd sweeps

        end
    end


    % Callbacks that handle component events
    methods (Access = private)

        % Code that executes after component creation
        function startupFcn(app)
            movegui(app.UIFigure,'center')
            app.TabGroup2.Visible = 0;
            app.set_ROISpinner; %Set ROISpinner based on preset spinner resolution
            app.selectedStyle = uistyle(FontWeight="bold");
            app.selectedStyle.Icon = 'info';
            app.baseStyle = uistyle(FontWeight="normal");
            app.baseStyle.Icon = 'none';

            %Make option panels invisible and move them into visible app area
            app.ChangefiletypemodePanel.Visible = "off";
            app.ChangefiletypemodePanel.Position = [651,436,256,107];

            app.AnalysisinprogressLabel.Visible = "off";
            app.AnalysisinprogressLabel.Position = [622,458,443,63];

            app.ExportinprogressLabel.Visible = "off";
            app.ExportinprogressLabel.Position = [622,458,442,63];

            app.Gauge.Visible = "off";
            app.Gauge.Position = [622, 418, 443, 41];

            app.SetROIsleftrightboundaryspinnerresolutionPanel.Visible = "off";
            app.SetROIsleftrightboundaryspinnerresolutionPanel.Position = [344,402,352,107];

            app.SetcommandlevelPanel.Visible = "off";
            app.SetcommandlevelPanel.Position = [651,436,352,107];

            app.AboutPanel.Visible = "off";
            app.AboutPanel.Position = [0,252,1643,621];

            app.Panel_5.Position = [570, 643,457,221];
        end

        % Close request function: UIFigure
        function UIFigureCloseRequest(app, event)
            app.menue_enable(0);
            app.menue_state =[app.RawPanel.Enable, app.AnalysisPanel.Enable];
            app.RawPanel.Enable = "off";
            app.AnalysisPanel.Enable = "off";
            save_session_cache = app.save_session_done;
            if ~isempty(app.RecordingListBox.ItemsData) && app.save_session_done == 0 %Ask if app should be closed. In case log contains data, ask if log should be saved
                while  app.save_session_done == 0
                    msg = 'Do you want to save session before closing the app?';
                    title = 'Close app';
                    selection = uiconfirm(app.UIFigure,msg,title, ...
                        'Options',{'Close and save session','Close without saving','Cancel'}, ...
                        'DefaultOption',3,'CancelOption',3);

                    if eq(selection, "Close and save session")
                        app.SaveMenuSelected();
                    elseif eq(selection, "Close without saving") || eq(selection, "Cancel")
                        app.save_session_done = 1;
                    end
                end
            else
                msg = 'Do you want to close the app?';
                title = 'Close app';
                selection = uiconfirm(app.UIFigure,msg,title, ...
                    'Options',{'Close','Cancel'}, ...
                    'DefaultOption',2,'CancelOption',2);
            end

            if eq(selection, "Cancel")
                app.save_session_done = save_session_cache;
                app.menue_enable(1);
                app.RawPanel.Enable = app.menue_state(1);
                app.AnalysisPanel.Enable = app.menue_state(2);
            else
                delete(app)
            end
        end

        % Menu selected function: Debug
        function TestStopMenuSelected(app, event)
            x = 1;
            print(num2str(x));
        end

        % Button pushed function: StartanalysisButton
        function StartanalysisButtonPushed(app, event)
            %Start analysis based on parameters
            app.StartanalysisButton.Enable = "off"; %Disable button to prevent a start of another analysis before former was finished
            app.menue_enable(0);
            app.RawPanel.Enable = "off";
            AnalysisPanel_state = app.AnalysisPanel.Enable;
            app.AnalysisPanel.Enable = "off";
            % app.AnalysisinprogressLabel.Position = [602,458,443,63]; %Move AnalysisinprogressLabel in visible area
            app.AnalysisinprogressLabel.Visible = "on";
            app.Gauge.Visible = "on";
            pause(0.1) %Pause necessary that button will be disabled in time

            if isempty(app.RecordingListBox.Value) %In case no recording was selected for analysis, stop callback
                app.menue_enable(1);
                app.RawPanel.Enable = "on";
                app.AnalysisPanel.Enable = AnalysisPanel_state;
                app.AnalysisinprogressLabel.Visible = "off"; %Move AnalysisinprogressLabel out of visible area
                app.Gauge.Visible = "off";
                app.StartanalysisButton.Enable = "on";
                return
            end

            cla(app.Results_UIAxes); %Clear results plot

            %In case no analysis was yet done or former analysis should be
            %overwritten
            if isempty(app.results_analysis) || app.AnalysisAddtoresultsCheckBox.Value == 0
                %Clear properties
                app.results_analysis = struct;
                app.results_analysis.RecListBox_data = [];
                app.results_analysis.axisDropDown_Met_list = [];
                app.results_analysis.selected_recordings = [];
            end
            selected_recordings = app.RecordingListBox.Value; %Fetch index of selected recordings for analysis

            %Index of analysed recordings as fusion between former analysis
            %and new analysis. Duplicates will be removed
            app.results_analysis.selected_recordings = unique([app.results_analysis.selected_recordings, selected_recordings]);
            gauge_step = 1/size(selected_recordings,2) * 100;
            for i_recordings = 1:size(selected_recordings,2) %For every selected recording

                select_cache = sprintf('recording_%d', selected_recordings(i_recordings)); %String to fetch and save recordings data and parameter from struct

                %Save parameters to results struct
                app.results_analysis.(select_cache).filename = app.loaded_files.(select_cache).filename;
                if app.file_type_mode == 1
                    app.results_analysis.(select_cache).channel = app.loaded_files.(select_cache).channel;
                end
                app.results_analysis.(select_cache).baseline = app.loaded_files.(select_cache).baseline;

                %Create analysis log and fill with first information
                analysis_log = app.results_analysis.(select_cache).filename;
                if app.file_type_mode == 1
                    analysis_log = [analysis_log; string(sprintf('Channel %s', num2str(app.results_analysis.(select_cache).channel)))];
                end
                analysis_log = [analysis_log; string(datetime)];

                %Create filename string and add to property
                if app.file_type_mode == 1
                    FilenameRecListBox = string(sprintf('%s_%s', app.results_analysis.(select_cache).filename, num2str(app.results_analysis.(select_cache).channel)));
                elseif app.file_type_mode == 2 || app.file_type_mode == 3
                    FilenameRecListBox = string(sprintf('%s', app.results_analysis.(select_cache).filename));
                end

                RecListBox_data_cache = [string(i_recordings), string(select_cache), string(selected_recordings(i_recordings)), FilenameRecListBox];
                app.results_analysis.RecListBox_data = [app.results_analysis.RecListBox_data; RecListBox_data_cache];

                %Create header of resultstable and drop down list for
                %analysis plot
                if app.file_type_mode == 1
                    resulttable_header = ["Sweep #", "Sweep time internally (ms)", "Sweep time absolut (ms)"];
                    axisDropDown_Met_list_cache = resulttable_header';
                    axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache, (1:3)'];

                elseif app.file_type_mode == 2 || app.file_type_mode == 3
                    resulttable_header = "Sweep #";
                    axisDropDown_Met_list_cache = [];
                end

                axisDropDown_Met_list_counter = 4; %Counter since not every results coloumn will be available for plotting
                selected_sweeps = (app.loaded_files.(select_cache).selected_sweeps); %Fetch index of recordings selected sweeps
                app.results_analysis.(select_cache).selected_sweeps = selected_sweeps; %Save to analysis struct
                if app.file_type_mode == 1
                    %Fetch absolute time when recording was started
                    sweep_time_abs = (app.loaded_files.(select_cache).header.lFileStartTime * 1000); %lFileStartTime is sweep start in s after midnight, convert in ms after midnight
                    %Calculate sweeps individuel start times, relative to start
                    %of recording
                    sweep_time_internally = app.loaded_files.(select_cache).header.sweepStartInPts;
                    sweep_time_internally = sweep_time_internally  * app.loaded_files.(select_cache).resolution;
                    sweep_time_internally = sweep_time_internally - sweep_time_internally(1);
                end

                if app.SelectedSweepsDropDown.Value == 1 %If the analysis should be done with all selected sweeps
                    app.AdditionallyunifyresultsinsingleExceltableCheckBox.Value = 0;
                    app.AdditionallyunifyresultsinsingleExceltableCheckBox.Visible = "off";
                    app.analysis_sweep_mode = 2;

                    %Set analysis plots line marker
                    app.LineButton.Value = 1;
                    app.LinestyleButtonGroup.Enable = "on";

                    raw_table = app.loaded_files.(select_cache).data_table_selected; %Fetch data table

                    if ~(app.Analysis_SampleRateSpinner.Value == 0) %If the sample rate should be digitally altered
                        raw_table = app.sample_increase(raw_table); %change sample rate
                        %Note it in the log
                        if app.Analysis_SampleRateSpinner.Value > 0
                            analysis_log = [analysis_log; string(sprintf('Sample rate digitally increased by factor %s', num2str((app.Analysis_SampleRateSpinner.Value + 1))))];
                        elseif app.Analysis_SampleRateSpinner.Value < 0
                            analysis_log = [analysis_log; string(sprintf('Sample rate digitally decreased by factor %s', num2str((abs(app.Analysis_SampleRateSpinner.Value) + 1))))];
                        end
                    end

                    if app.Button_ROIBaseline.Value == 1 && app.OffButton.Value == 0 %In case the baseline should be corrected and added to the results table

                        raw_table = raw_table - app.results_analysis.(select_cache).baseline; %Correct baseline
                        baseline = app.results_analysis.(select_cache).baseline(:,(selected_sweeps+1)); %Fetch baseline values
                        %Add entry to header and plot selection drop down
                        name_cache_1 = string(sprintf('Baseline (%s)', app.loaded_files.(select_cache).unit));
                        resulttable_header = [resulttable_header, name_cache_1];

                        axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cache_1, axisDropDown_Met_list_counter]];

                        axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                        analysis_log = [analysis_log; "Sweeps: selected"; "Baseline corrected"];

                    elseif app.Button_ROIBaseline.Value == 1 && app.OffButton.Value == 1 %In case the baseline should not be corrected but added to the results table
                        baseline = app.results_analysis.(select_cache).baseline(:,(selected_sweeps+1)); %Fetch baseline values
                        %Add entry to header and plot selection drop down
                        name_cache_1 = string(sprintf('Baseline (%s)', app.loaded_files.(select_cache).unit));

                        resulttable_header = [resulttable_header, name_cache_1];

                        axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cache_1, axisDropDown_Met_list_counter]];

                        axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                        analysis_log = [analysis_log; "Sweeps: selected"; "Baseline not corrected"];

                    elseif app.Button_ROIBaseline.Value == 0 && app.OffButton.Value == 1 %In case the baseline should neither be corrected or added to the results table
                        baseline = []; %Define baseline as empty
                        analysis_log = [analysis_log; "Sweeps: selected"; "Baseline not corrected"];

                    elseif   app.Button_ROIBaseline.Value == 0 && app.OffButton.Value == 0 %In case the baseline should be corrected but not added to the results table
                        raw_table = raw_table - app.results_analysis.(select_cache).baseline; %Correct baseline
                        baseline = []; %Define baseline as empty
                        analysis_log = [analysis_log; "Sweeps: selected"; "Baseline corrected"];
                    end

                    raw_table =[raw_table(:,1), raw_table(:,(selected_sweeps+1))]; %Remove not selected sweeps from data table
                    if app.file_type_mode == 1
                        sweep_time_internally_selected = sweep_time_internally(selected_sweeps); %Isolate sweep start times from selected sweeps
                    end
                    analysis_table = selected_sweeps'; %Generate first column of analysis table

                elseif      app.SelectedSweepsDropDown.Value == 2 %In case the analysis should be done with the mean sweep

                    if app.AnalysisAddtoresultsCheckBox.Value == 0
                        app.analysis_sweep_mode = 1;
                    end
                    if app.analysis_sweep_mode == 1
                        app.AdditionallyunifyresultsinsingleExceltableCheckBox.Value = 1;
                        app.AdditionallyunifyresultsinsingleExceltableCheckBox.Visible = "on";
                    end
                    %Disable plot marker options
                    app.MarkerButton.Value = 1;
                    app.LinestyleButtonGroup.Enable = "off";

                    if app.Button_ROIBaseline.Value == 1 && app.OffButton.Value == 0 %In case the baseline should be corrected and added to the results table
                        raw_table =  [app.loaded_files.(select_cache).mean_sd(:,1),app.loaded_files.(select_cache).mean_sd(:,4)]; %Fetch baseline corrected mean sweep
                        baseline = 0; %Since it's a mean sweep
                        %Add entry to header and plot selection drop down
                        name_cache_1 = string(sprintf('Baseline (%s)', app.loaded_files.(select_cache).unit));
                        resulttable_header = [resulttable_header, name_cache_1];

                        axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cache_1, axisDropDown_Met_list_counter]];

                        axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                        analysis_log = [analysis_log; "Sweeps: mean"; "Baseline corrected"];

                    elseif app.Button_ROIBaseline.Value == 1 && app.OffButton.Value == 1 %In case the baseline should not be corrected but added to the results table
                        raw_table =  app.loaded_files.(select_cache).mean_sd(:,1:2); %Fetch baseline uncorrected mean sweep
                        %Calculate baseline
                        if app.file_type_mode == 1
                            left_boundary = app.LeftSpinner.Value/app.loaded_files.(select_cache).resolution;
                            right_boundary = app.RightSpinner.Value/app.loaded_files.(select_cache).resolution;
                        elseif app.file_type_mode == 2 || app.file_type_mode == 3
                            left_boundary = find(raw_table(:,1) == app.LeftSpinner.Value);
                            right_boundary = find(raw_table(:,1) == app.RightSpinner.Value);
                        end
                        data_temp_baseline = raw_table(left_boundary:right_boundary, 2);
                        baseline = mean(data_temp_baseline);
                        %Add entry to header and plot selection drop down
                        name_cache_1 = string(sprintf('Baseline (%s)', app.loaded_files.(select_cache).unit));
                        resulttable_header = [resulttable_header, name_cache_1];

                        axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cache_1, axisDropDown_Met_list_counter]];

                        axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                        analysis_log = [analysis_log; "Sweeps: mean"; "Baseline not corrected"];

                    elseif app.Button_ROIBaseline.Value == 0 && app.OffButton.Value == 1 %In case the baseline should neither be corrected or added to the results table
                        raw_table =  app.loaded_files.(select_cache).mean_sd(:,1:2); %Fetch baseline uncorrected mean sweep
                        baseline = []; %Define baseline as empty
                        analysis_log = [analysis_log; "Sweeps: mean"; "Baseline not corrected"];

                    elseif   app.Button_ROIBaseline.Value == 0 && app.OffButton.Value == 0 %In case the baseline should be corrected but not added to the results table
                        raw_table =  [app.loaded_files.(select_cache).mean_sd(:,1),app.loaded_files.(select_cache).mean_sd(:,4)]; %Fetch baseline corrected mean sweep
                        baseline = []; %Define baseline as empty
                        analysis_log = [analysis_log; "Sweeps: mean"; "Baseline corrected"];
                    end

                    if ~(app.Analysis_SampleRateSpinner.Value == 0) %If the sample rate should be digitally altered
                        raw_table = app.sample_increase(raw_table); %change sample rate
                        %Note it in the log
                        if app.Analysis_SampleRateSpinner.Value > 0
                            analysis_log = [analysis_log; string(sprintf('Sample rate digitally increased by factor %s', num2str((app.Analysis_SampleRateSpinner.Value + 1))))];
                        elseif app.Analysis_SampleRateSpinner.Value < 0
                            analysis_log = [analysis_log; string(sprintf('Sample rate digitally decreased by factor %s', num2str((abs(app.Analysis_SampleRateSpinner.Value) + 1))))];
                        end
                    end

                    sweep_time_internally_selected = 0; %Since only one datapoint will be generated per recording and ROI
                    analysis_table = 0; %Generate first column of analysis table
                end
                if app.file_type_mode == 1
                    analysis_table = [analysis_table, sweep_time_internally_selected, (sweep_time_internally_selected + sweep_time_abs)]; %Add sweep times to result tables
                end
                if ~isempty(baseline) %In case the baseline correction should be added to the result table
                    analysis_table = [analysis_table, baseline']; %Add to result table

                    if app.CursorsButton.Value == 1 %Fetch boundaries based on cursor.
                        left_boundary = app.LeftSpinner.Value;
                        right_boundary = app.RightSpinner.Value;
                    elseif app.EpochButton.Value == 1 %Fetch boundaries based on selected episode and convert in ms
                        selected_epoch = app.EpisodeSpinner.Value + 1;
                        left_boundary = app.loaded_files.(select_cache).epoch.baseline(selected_epoch,1) * app.loaded_files.(select_cache).resolution;
                        right_boundary = app.loaded_files.(select_cache).epoch.baseline(selected_epoch,2) * app.loaded_files.(select_cache).resolution;
                    end
                    if app.OffButton == 0 %If a baseline correction was selected
                        analysis_log = [analysis_log; string(sprintf('Baseline: left boundary: %s ms, right boundary: %s ms', num2str(left_boundary), num2str(right_boundary)))];
                    end
                end

                if app.IncludecommandlevelButton.Value == 1
                    commandLevel = app.loaded_files.(select_cache).epoch.commandLevel_complete(:,2:end); %Fetch command level matrix without data point column;
                    commandLevel_unit = app.loaded_files.(select_cache).epoch.unit; %Fetch command level unit;
                end

                ROI_selected_cache = app.ROI_selected; %Fetch list of selected ROIs
                gauge_step_small = 1/size(ROI_selected_cache,2) * gauge_step;
                gauge_state = app.Gauge.Value;
                for i_ROI = 1:size(ROI_selected_cache,2) %Do the analysis for each ROI

                    ROI = ROI_selected_cache(i_ROI); %Fetch current ROI
                    raw_table_cut = raw_table; %Copy data table

                    %Define name strings for dynamic access to values or
                    %properties
                    ROISpinnerLeft = sprintf('ROISpinnerLeft_%d', ROI);
                    ROISpinnerRight = sprintf('ROISpinnerRight_%d', ROI);
                    AnalysisDropDown = sprintf('AnalysisDropDown_%d', ROI);
                    SlopeSpinner_Lower = sprintf('SlopeSpinner_Lower_%d', ROI);
                    SlopeSpinner_Upper = sprintf('SlopeSpinner_Upper_%d', ROI);
                    PeakDirDropDown = sprintf('PeakDirDropDown_%d', ROI);
                    RelativetoDropDown = sprintf('RelativetoDropDown_%d', ROI);
                    Relativeto_leftboundary = sprintf('ROI_%d', ROI);
                    Analysis_RegressionDropDown = sprintf('Analysis_RegressionDropDown_%d', ROI);

                    isi = raw_table_cut(2,1)-raw_table_cut(1,1); %Fetch inter sample intervall
                    outofboundaries = []; %Analysis failure string
                    analysis_log = [analysis_log; "---"; string(sprintf('ROI_%d', ROI))]; %ROI section in log

                    %Get first and last time point of data table
                    sweep_end = raw_table_cut(end,1);
                    sweep_start = raw_table_cut(1,1);

                    %Define first and last datapoint of ROI
                    if ROI == 1 || app.(RelativetoDropDown).Value == 0 %If first ROI or ROI shouldn't based on time of another ROI
                        %Define boundaries by spinner value
                        leftboundary = app.(ROISpinnerLeft).Value;
                        rightboundary = app.(ROISpinnerRight).Value;
                        app.results_analysis.(select_cache).Relativeto.(Relativeto_leftboundary) = leftboundary; %save leftbound to property
                    else %If ROI is based on time of another ROI
                        %Fetch time of relative ROI
                        select_cache_relativeto = sprintf('ROI_%d', app.(RelativetoDropDown).Value);
                        relative_leftboundary = app.results_analysis.(select_cache).Relativeto.(select_cache_relativeto); %Has more than one data point. Important for further discrimination
                        %Set boundaries, double -> single conversion necessary
                        %to avoid calculation errors by double format.
                        %Cause unknown
                        left_shift = single(app.(ROISpinnerLeft).Value);
                        delta_boundary = single(app.(ROISpinnerRight).Value) - left_shift;
                        leftboundary = single(relative_leftboundary) + left_shift;
                        % leftbound = relative_leftbound + app.(ROISpinnerLeft).Value;
                        rightboundary =  leftboundary + delta_boundary;
                        % rightbound = relative_leftbound + app.(ROISpinnerRight).Value;
                        app.results_analysis.(select_cache).Relativeto.(Relativeto_leftboundary) = leftboundary; %save leftbound to property
                    end
                    %Calculate times of left and right boundaries, in case boundary points
                    %are not part of time column due to difference between boundary time and sample
                    %rate. E.g. a 3 Hz recording doesn't have a 0.5 s data point. In this case
                    %the boundaries will be rounded to possible values, whereas the ROI becomes
                    %smaller.
                    leftbound_datapoint_cache = ceil(double((leftboundary)/isi));
                    leftboundary = isi * leftbound_datapoint_cache;
                    leftbound_datapoint = leftbound_datapoint_cache - (raw_table(1,1) /isi) + 1;
                    rightbound_datapoint_cache = floor(double((rightboundary) /isi));
                    rightboundary = isi * rightbound_datapoint_cache;
                    rightbound_datapoint = rightbound_datapoint_cache - (raw_table(1,1) /isi) + 1;

                    %Calculate Datapoints included in analysis and create
                    %placeholder in case analysis fails
                    no_of_dp_ROI = rightbound_datapoint(1) - leftbound_datapoint(1) + 1;
                    NaN_placeholder = NaN(int32(no_of_dp_ROI),1);

                    %Add information to log based on left and right bound
                    if size(leftboundary,1) > 1 %In case ROI is relative to another
                        if app.(ROISpinnerLeft).Value < 0 %In case ROI starts before relative ROI
                            left_placeholder = string(sprintf(' - %d ms', abs(app.(ROISpinnerLeft).Value)));
                        elseif app.(ROISpinnerLeft).Value == 0
                            left_placeholder = [];
                        else %In case ROI starts after relative ROI
                            left_placeholder = string(sprintf(' + %d ms', abs(app.(ROISpinnerLeft).Value)));
                        end
                        right_placeholder = rightboundary(1) - leftboundary(1);
                        analysis_log_cache_1 = string(sprintf('Left boundary: time of ROI_%s%s' , num2str(app.(RelativetoDropDown).Value), left_placeholder));
                        analysis_log_cache_2 = string(sprintf('Right boundary: left boundary + %d ms' , right_placeholder));
                        analysis_log_cache = string(sprintf('%s, %s', analysis_log_cache_1, analysis_log_cache_2));
                    else
                        analysis_log_cache =  string(sprintf('Left boundary: %s ms, right boundary: %s ms', num2str(leftboundary), num2str(rightboundary)));
                    end
                    analysis_log = [analysis_log;analysis_log_cache];

                    if size(leftboundary,1) > 1 %If ROI is relative to another
                        raw_table_cut_data = [];
                        raw_table_cut_time = [];
                        %Cut data table to the ROI (leftboundary:rightboundary)
                        %and generate a table with the times and one with
                        %the values
                        for i_cut = 2:size(raw_table, 2)
                            i_boundary = i_cut - 1;

                            if rightboundary(i_boundary) > sweep_end || leftboundary(i_boundary) < sweep_start %In case one of the boundaries are out of the datas bound
                                raw_table_cut_data = [raw_table_cut_data, NaN_placeholder]; %Add NaN
                                raw_table_cut_time = [raw_table_cut_time, NaN_placeholder];
                            else %Cut the data table
                                raw_table_cut_data_cache = raw_table(leftbound_datapoint(i_boundary):rightbound_datapoint(i_boundary),i_cut);
                                raw_table_cut_time_cache = raw_table(leftbound_datapoint(i_boundary):rightbound_datapoint(i_boundary),1);
                                raw_table_cut_data = [raw_table_cut_data, raw_table_cut_data_cache];
                                raw_table_cut_time = [raw_table_cut_time, raw_table_cut_time_cache];
                            end
                        end
                    else %If ROI is not relative to another
                        if rightboundary > sweep_end %In case rightbound is out of datas boundaries
                            analysis_log_outofboundary = string(sprintf('Right boundary out of sweep. Set to max %d',sweep_end));
                        else %Cut the tables
                            raw_table_cut_cache = raw_table(int32(leftbound_datapoint):int32(rightbound_datapoint),:);
                            raw_table_cut_data = raw_table_cut_cache(:,2:end);
                            raw_table_cut_time = [];
                            for i_cut = 1:size(raw_table_cut_data,2) %Generate a table with the times. The columns are identical but step necessary for the codes flow
                                raw_table_cut_time = [raw_table_cut_time, raw_table_cut_cache(:,1)];
                            end
                            analysis_log_outofboundary = [];
                        end
                    end
                    if app.file_type_mode == 1
                        %determine ROIs command level
                        if app.IncludecommandlevelButton.Value == 1

                            % if app.SelectedSweepsDropDown.Value == 1 %If analysis will be done with single sweeps
                            commandLevel_cache = commandLevel(int32(leftbound_datapoint):int32(rightbound_datapoint),:); %Cut commandLevel matrix to ROI
                            commandLevel_ROI = [];
                            for i_command = 1:size(analysis_table,1)
                                if app.SelectedSweepsDropDown.Value == 1 %If analysis will be done with single sweeps
                                    command_index = analysis_table(i_command,1);
                                else %If analysis will be done with mean sweep
                                    command_index = ':';
                                end
                                commandLevel_ROI_cache = commandLevel_cache(:,command_index);
                                commandLevel_ROI_cache = unique(commandLevel_ROI_cache);
                                if size(commandLevel_ROI_cache,1) == 1
                                    commandLevel_ROI = [commandLevel_ROI; commandLevel_ROI_cache];
                                else
                                    commandLevel_ROI = [commandLevel_ROI; NaN];
                                end
                            end
                            if sum(isnan(commandLevel_ROI)) > 0 %In case no clear command value couldn't be determined for all sweeps
                                commandLevel_ROI(:) = NaN;
                            end

                            analysis_table = [analysis_table, commandLevel_ROI]; %Add command level to analysis table

                            %Generat drop down, header and log information if command level is included
                            if isnan(commandLevel_ROI)
                                analysis_log = [analysis_log; "No unique command level in ROI"];
                            end
                            name_cache_1 = string(sprintf('Command level (%s) ROI_%d', commandLevel_unit, ROI));
                            resulttable_header = [resulttable_header, name_cache_1];
                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cache_1, axisDropDown_Met_list_counter]];
                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                        end
                    end
                    %Generat drop down, header and log information for the selected
                    %method
                    if app.(AnalysisDropDown).Value == 1 %Method mean
                        analysis_log = [analysis_log; "Method: mean"];
                        name_cache_1 = string(sprintf('Mean (%s) ROI_%d', app.loaded_files.(select_cache).unit, ROI));
                        resulttable_header = [resulttable_header, name_cache_1];
                        if app.file_type_mode == 1
                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cache_1, axisDropDown_Met_list_counter]];
                        end
                        axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;

                    elseif app.(AnalysisDropDown).Value == 2 %Method amplitude
                        analysis_log = [analysis_log; "Method: amplitude"];
                        name_cache_1 = string(sprintf('Amplitude (%s) ROI_%d', app.loaded_files.(select_cache).unit, ROI));
                        name_cache_2 = string(sprintf('Time(Amplitude) (ms) ROI_%d', ROI));
                        resulttable_header = [resulttable_header, name_cache_1, name_cache_2];

                        axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cache_1, axisDropDown_Met_list_counter]];

                        axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 2;
                    elseif app.(AnalysisDropDown).Value == 3 || app.(AnalysisDropDown).Value == 4 %Slope analysis
                        %Generate name strings for the variables, since
                        %multiple combinations are possible
                        name_cacheRise = string(sprintf('Rise slope (%s/ms) ROI_%d', app.loaded_files.(select_cache).unit, ROI));
                        name_cacheDecay = string(sprintf('Decay slope (%s/ms) ROI_%d', app.loaded_files.(select_cache).unit, ROI));
                        name_cacheRiseTau_1 = string(sprintf('Rise tau_1 (ms) ROI_%d', ROI));
                        name_cacheRiseTau_2 = string(sprintf('Rise tau_2 (ms) ROI_%d', ROI));
                        name_cacheDecayTau_1 = string(sprintf('Decay tau_1 (ms) ROI_%d', ROI));
                        name_cacheDecayTau_2 = string(sprintf('Decay tau_2 (ms) ROI_%d', ROI));
                        if app.(Analysis_RegressionDropDown).Value == 4 %Necessary to avoid column with same names
                            name_cacheROI_mod1 = string(sprintf('Datapoints for linear regression (#) ROI_%d', ROI));
                            name_cacheRSquare_mod1 = string(sprintf('RSquare of linear regression ROI_%d', ROI));
                            name_cacheROI_mod2 = string(sprintf('Datapoints for 1x exp regression (#) ROI_%d', ROI));
                            name_cacheRSquare_mod2 = string(sprintf('RSquare of 1x exp regression ROI_%d', ROI));
                            name_cacheROI_mod3 = string(sprintf('Datapoints for 2x exp regression (#) ROI_%d', ROI));
                            name_cacheRSquare_mod3 = string(sprintf('RSquare of 2x exp regression ROI_%d', ROI));
                        else
                            name_cacheROI = string(sprintf('Datapoints for regression (#) ROI_%d', ROI));
                            name_cacheRSquare = string(sprintf('RSquare of regression ROI_%d', ROI));
                        end

                        if app.(AnalysisDropDown).Value == 3 && app.(Analysis_RegressionDropDown).Value == 1 %Rise slope, linear regression
                            analysis_log = [analysis_log; "Method: rise slope (linear regression)"];
                            resulttable_header = [resulttable_header, name_cacheRise, name_cacheROI, name_cacheRSquare];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheRise, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                        elseif app.(AnalysisDropDown).Value == 3  && app.(Analysis_RegressionDropDown).Value == 2 %Rise slope, 1x exponential regression
                            analysis_log = [analysis_log; "Method: rise slope (1x exp regression)"];
                            resulttable_header = [resulttable_header, name_cacheRiseTau_1, name_cacheROI, name_cacheRSquare];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheRiseTau_1, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                        elseif app.(AnalysisDropDown).Value == 3  && app.(Analysis_RegressionDropDown).Value == 3 %Rise slope, 2x exponential regression
                            analysis_log = [analysis_log; "Method: rise slope (2x exp regression)"];
                            resulttable_header = [resulttable_header, name_cacheRiseTau_1];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheRiseTau_1, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                            resulttable_header = [resulttable_header, name_cacheRiseTau_2, name_cacheROI, name_cacheRSquare];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheRiseTau_2, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                        elseif app.(AnalysisDropDown).Value == 3  && app.(Analysis_RegressionDropDown).Value == 4 %Rise slope, all regression methods
                            analysis_log = [analysis_log; "Method: rise slope (all regression)"];
                            name_cacheRise_cache = string(sprintf('%s (lin)', name_cacheRise));
                            resulttable_header = [resulttable_header, name_cacheRise_cache, name_cacheROI_mod1, name_cacheRSquare_mod1];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheRise_cache, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                            name_cacheRiseTau_1_cache = string(sprintf('%s (1x exp)', name_cacheDecayTau_1));
                            resulttable_header = [resulttable_header, name_cacheRiseTau_1_cache, name_cacheROI_mod2, name_cacheRSquare_mod2];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheRiseTau_1_cache, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                            name_cacheRiseTau_1_cache = string(sprintf('%s (2x exp)', name_cacheRiseTau_1));
                            name_cacheRiseTau_2_cache = string(sprintf('%s (2x exp)', name_cacheRiseTau_2));
                            resulttable_header = [resulttable_header, name_cacheRiseTau_1_cache];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheRiseTau_1_cache, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                            resulttable_header = [resulttable_header, name_cacheRiseTau_2_cache, name_cacheROI_mod3, name_cacheRSquare_mod3];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheRiseTau_2_cache, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;

                        elseif app.(AnalysisDropDown).Value == 4  && app.(Analysis_RegressionDropDown).Value == 1 %Decay slope, linear regression
                            analysis_log = [analysis_log; "Method: decay slope (linear regression)"];
                            resulttable_header = [resulttable_header, name_cacheDecay, name_cacheROI, name_cacheRSquare];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheDecay, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                        elseif app.(AnalysisDropDown).Value == 4  && app.(Analysis_RegressionDropDown).Value == 2 %Decay slope, 1x exponential regression
                            analysis_log = [analysis_log; "Method: decay slope (1x exp regression)"];
                            resulttable_header = [resulttable_header, name_cacheDecayTau_1, name_cacheROI, name_cacheRSquare];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheDecayTau_1, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                        elseif app.(AnalysisDropDown).Value == 4  && app.(Analysis_RegressionDropDown).Value == 3 %Decay slope, 2x exponential regression
                            analysis_log = [analysis_log; "Method: decay slope (2x exp regression)"];
                            resulttable_header = [resulttable_header, name_cacheDecayTau_1];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheDecayTau_1, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                            resulttable_header = [resulttable_header, name_cacheDecayTau_2, name_cacheROI, name_cacheRSquare];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheDecayTau_2, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                        elseif app.(AnalysisDropDown).Value == 4  && app.(Analysis_RegressionDropDown).Value == 4 %Decay slope, all regression methods
                            analysis_log = [analysis_log; "Method: decay slope (all regression)"];
                            name_cacheDecay_cache = string(sprintf('%s (lin)', name_cacheDecay));
                            resulttable_header = [resulttable_header, name_cacheDecay_cache, name_cacheROI_mod1, name_cacheRSquare_mod1];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheDecay_cache, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                            name_cacheTau_1_cache = string(sprintf('%s (1x exp)', name_cacheDecayTau_1));
                            resulttable_header = [resulttable_header, name_cacheTau_1_cache, name_cacheROI_mod2, name_cacheRSquare_mod2];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheTau_1_cache, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                            name_cacheTau_1_cache = string(sprintf('%s (2x exp)', name_cacheDecayTau_1));
                            name_cacheTau_2_cache = string(sprintf('%s (2x exp)', name_cacheDecayTau_2));
                            resulttable_header = [resulttable_header, name_cacheTau_1_cache];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheTau_1_cache, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                            resulttable_header = [resulttable_header, name_cacheTau_2_cache, name_cacheROI_mod3, name_cacheRSquare_mod3];

                            axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cacheTau_2_cache, axisDropDown_Met_list_counter]];

                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 3;
                        end
                        %Add slope boundaries to log
                        name_Regboundaries = string(sprintf('%d%%-%d%% of ROIs amplitude used for regression', app.(SlopeSpinner_Lower).Value, app.(SlopeSpinner_Upper).Value));
                        analysis_log = [analysis_log; name_Regboundaries];
                    elseif app.(AnalysisDropDown).Value == 5 %Method AUC
                        analysis_log = [analysis_log; "Method: AUC"];
                        name_cache_1 = string(sprintf('AUC (%s*ms) ROI_%d', app.loaded_files.(select_cache).unit, ROI));
                        name_cache_2 = string(sprintf('Correction function ROI_%d', ROI));
                        resulttable_header = [resulttable_header, name_cache_1, name_cache_2];
                        axisDropDown_Met_list_cache = [axisDropDown_Met_list_cache;[name_cache_1, axisDropDown_Met_list_counter]];
                        axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 2;
                    end

                    if ~isempty(analysis_log_outofboundary) && size(leftboundary,1) == 1 %In case rightbound is out of datas boundaries and ROI is not relative to another
                        analysis_log = [analysis_log;  analysis_log_outofboundary]; %write error to log
                        ana_result(1:size(analysis_table, 2)) = NaN; %add NaN to result
                        analysis_table = [analysis_table, ana_result];
                        continue %with next ROI
                    end

                    %Analysis
                    if app.(AnalysisDropDown).Value == 1 %Mean method
                        ana_result = mean(raw_table_cut_data(:,:))';

                    elseif app.(AnalysisDropDown).Value == 2 %Amplitude
                        if app.(PeakDirDropDown).Value == 1 %positive peak
                            ana_result_amp = max( raw_table_cut_data(:,:)); %Search for ROIs max
                            ana_result_time_index = raw_table_cut_data(:,:) == ana_result_amp; %Search for time point of ROIs max
                            ana_result_time = [];
                            for i_time = 1: size(ana_result_amp,2)
                                ana_result_time_cache = raw_table_cut_time(ana_result_time_index(:,i_time), i_time); %Isolate ROIs max time points
                                ana_result_time = [ana_result_time; ana_result_time_cache(1)]; %Add first time point to results
                            end
                            ana_result = [ana_result_amp', ana_result_time];
                            analysis_log = [analysis_log; string(sprintf('Peak direction: positive'))];
                        elseif app.(PeakDirDropDown).Value == 2 %Negative peak
                            ana_result_amp = min( raw_table_cut_data(:,:)); %Search for ROIs min
                            ana_result_time_index = raw_table_cut_data(:,:) == ana_result_amp; %Search for time point of ROIs min
                            ana_result_time = [];
                            for i_time = 1: size(ana_result_amp,2)
                                ana_result_time_cache = raw_table_cut_time(ana_result_time_index(:,i_time), i_time); %Isolate ROIs min time points
                                ana_result_time = [ana_result_time; ana_result_time_cache(1)]; %Add first time point to results
                            end
                            ana_result = [ana_result_amp', ana_result_time];
                            analysis_log = [analysis_log; string(sprintf('Peak direction: negative'))];

                        else %Auto peak direction or abs amplitude
                            ana_result = app.peakdirection_abs(raw_table_cut_data(:,:),1); %Calculate peak direction and amplitude
                            ana_result_amp = ana_result(:,1)'; %Isolate each sweeps amplitude
                            ana_result_time_index = raw_table_cut_data(:,:) == ana_result_amp; %Search for amplitudes time points
                            ana_result_time = [];
                            for i_time = 1: size(ana_result_amp,2)
                                ana_result_time_cache = raw_table_cut_time(ana_result_time_index(:,i_time), i_time); %Isolate ROIs amplitude time points
                                ana_result_time = [ana_result_time; ana_result_time_cache(1)]; %Add first time point to results
                            end
                            resulttable_header = [resulttable_header, string(sprintf('Peak direction ROI_%d', ROI))];
                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                            if app.(PeakDirDropDown).Value == 4 %In case result should be abs amplitude
                                ana_result(:,1) = abs(ana_result(:,1));
                                analysis_log = [analysis_log; "Peak direction: absolute"];
                            else
                                analysis_log = [analysis_log; "Peak direction: auto"];
                            end
                            ana_result = [ana_result(:,1), ana_result_time, ana_result(:,2)]; %Save to results

                        end
                        app.results_analysis.(select_cache).Relativeto.(Relativeto_leftboundary) = ana_result_time; %Save results time

                    elseif app.(AnalysisDropDown).Value == 3 ||  app.(AnalysisDropDown).Value == 4 %Slope analysis
                        %Set mode variable based on rise/decay slope
                        if app.(AnalysisDropDown).Value == 3
                            slope_direction = 1;
                        elseif app.(AnalysisDropDown).Value == 4
                            slope_direction = 2;
                        end

                        %Set peak direction variable
                        if app.(PeakDirDropDown).Value == 1 %Positive peak
                            peak_direction = 1;
                            analysis_log = [analysis_log; "Peak direction: positive"];
                        elseif app.(PeakDirDropDown).Value == 2 %Negative peak
                            peak_direction = -1;
                            analysis_log = [analysis_log; "Peak direction: negative"];
                        else %Auto peak direction determination
                            peak_direction = app.peakdirection_abs(raw_table_cut_data(:,:),2); %Determine peak direction
                            peak_direction = peak_direction(:,2);
                            if app.(AnalysisDropDown).Value == 4
                                %In case decay will be analysed, peak direction must be inverted
                                %(Calculation: last data point - first data
                                %point). For a positive peak: peak
                                %direction based on rise phase would be
                                %positive, for the decay phase negative.
                                peak_direction = peak_direction * -1;
                            end
                            %Set header, drop down and log information
                            resulttable_header = [resulttable_header, string(sprintf('Peak direction ROI_%d', ROI))];
                            axisDropDown_Met_list_counter = axisDropDown_Met_list_counter + 1;
                            if app.(PeakDirDropDown).Value == 3
                                analysis_log = [analysis_log; "Peak direction: auto"];
                            elseif app.(PeakDirDropDown).Value == 4
                                analysis_log = [analysis_log; "Peak direction: absolute"];
                            end
                        end

                        %Isolate variables for slope analysis
                        lower_boundary = app.(SlopeSpinner_Lower).Value;
                        upper_boundary = app.(SlopeSpinner_Upper).Value;
                        result_cache = [];
                        analysis_log_regression = [];
                        model_set = app.(Analysis_RegressionDropDown).Value; %1= linear, 2= 1x exp, 3= 2x exp, 4 = all)
                        for i_sweep = 1:size(raw_table_cut_data,2) %For every sweep of recording

                            if size(peak_direction,1) > 1 %In cause auto peak detection was used
                                peak_direction_cut = peak_direction((i_sweep),1); %Fetch peak direction
                            else
                                peak_direction_cut = peak_direction;  %Fetch peak direction
                            end
                            peakreg_set = peak_direction_cut * slope_direction; %combine setting variables
                            sweep_single = [raw_table_cut_time(:,i_sweep), raw_table_cut_data(:,i_sweep)]; %Isolate and kombine sweeps time and value data
                            if ~isnan(sweep_single(1,1)) %If sweep contains data
                                %Calculate slope
                                [result_regression, analysis_log_regression_cache, outofboundaries_cache] = app.Multiregression(sweep_single, lower_boundary, upper_boundary, peakreg_set, model_set);
                                outofboundaries = [outofboundaries; outofboundaries_cache]; %Collect regression failures

                            else %No data present for analysis, fill result with NaN
                                if model_set < 3
                                    result_regression = [NaN, NaN, NaN];
                                elseif model_set == 3
                                    result_regression = [NaN, NaN, NaN, NaN];
                                elseif model_set == 4
                                    result_regression = [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, Nan];
                                end
                                analysis_log_regression_cache = [];
                            end
                            if ~isempty(analysis_log_regression_cache) %In case a refression failure occured
                                analysis_log_regression = [analysis_log_regression; string(sprintf('Sweep_%d: %s', selected_sweeps(i_sweep), analysis_log_regression_cache))];
                            end
                            if   app.(PeakDirDropDown).Value == 3 || app.(PeakDirDropDown).Value == 4 %In case auto peak direction detection was used
                                result_regression = [result_regression, peak_direction_cut]; %Add peak direction to results
                            end
                            result_cache = [result_cache; result_regression]; %Save results
                        end

                        if app.(PeakDirDropDown).Value == 4 %In case absolute slope should be determined
                            result_cache(:,1) = abs(result_cache(:,1));
                        end

                        analysis_log = [analysis_log; analysis_log_regression];
                        ana_result = result_cache;

                    elseif app.(AnalysisDropDown).Value == 5 %AUC
                        %Calculate correction linear function
                        if app.(PeakDirDropDown).Value == 1 %positive peak
                            analysis_log = [analysis_log; string(sprintf('Peak direction: positive'))];
                        elseif app.(PeakDirDropDown).Value == 2 %negative peak
                            analysis_log = [analysis_log; string(sprintf('Peak direction: negative'))];
                        elseif app.(PeakDirDropDown).Value == 3 %auto peak
                            analysis_log = [analysis_log; string(sprintf('Peak direction: auto'))];
                            resulttable_header = [resulttable_header, string(sprintf('Peak direction ROI_%d', ROI))];
                        elseif app.(PeakDirDropDown).Value == 4 %abs
                            analysis_log = [analysis_log; string(sprintf('Peak direction: absolute'))];
                        end

                        x = [raw_table_cut_time(1), raw_table_cut_time(end)];
                        ana_result = [];
                        for i_sweep = 1:size(raw_table_cut_data,2)
                            y = [raw_table_cut_data(1, i_sweep), raw_table_cut_data(end, i_sweep)];
                            a = (y(2)-y(1))/(x(2)-x(1));
                            b = y(1) - a*x(1);
                            y_correction = (raw_table_cut_time(:,1).*a) + b;
                            raw_table_cut_data_corrected =  raw_table_cut_data(:, i_sweep) - y_correction;

                            if app.(PeakDirDropDown).Value == 1 %positive peak
                                raw_table_cut_data_corrected(raw_table_cut_data_corrected < 0) = 0;
                            elseif app.(PeakDirDropDown).Value == 2 %negative peak
                                raw_table_cut_data_corrected(raw_table_cut_data_corrected > 0) = 0;
                            elseif app.(PeakDirDropDown).Value == 3 %auto peak
                                if abs(max(raw_table_cut_data_corrected)) > abs(min(raw_table_cut_data_corrected))
                                    peak_dir = 1;
                                    raw_table_cut_data_corrected(raw_table_cut_data_corrected < 0) = 0;
                                elseif abs(max(raw_table_cut_data_corrected)) < abs(min(raw_table_cut_data_corrected))
                                    peak_dir = -1;
                                    raw_table_cut_data_corrected(raw_table_cut_data_corrected < 0) = 0;
                                else
                                    peak_dir = 0;
                                end

                            elseif app.(PeakDirDropDown).Value == 4 %abs
                                raw_table_cut_data_corrected = abs(raw_table_cut_data_corrected);
                            end
                            AUC_result = abs(trapz(raw_table_cut_time(:,1),raw_table_cut_data_corrected)); %Calculate AUC
                            correction_function = string(sprintf('y = %.5f * x + %.5f', a, b)); %Show correction linear function in results
                            ana_result_cache = [AUC_result, correction_function];
                            if app.(PeakDirDropDown).Value == 3 %auto peak
                                ana_result_cache = [ana_result_cache, peak_dir];
                            end
                            ana_result = [ana_result; ana_result_cache];
                        end
                    end

                    %Determine sweeps with failed regression
                    analysis_log_NaN_counter = [];
                    for i_outofboundary = 1:size(outofboundaries,1)
                        if isnan(outofboundaries(i_outofboundary,1))%Create string which list sweeps with
                            %regression failure
                            analysis_log_NaN_counter = sprintf('%s, %d', analysis_log_NaN_counter, selected_sweeps(i_outofboundary));
                        end
                    end
                    if ~isempty(analysis_log_NaN_counter) %In case failures occured, add to log
                        analysis_log_NaN_counter(1) = [];
                        analysis_log = [analysis_log;string(sprintf('Sweeps out of boundary:%s', analysis_log_NaN_counter))];
                    end

                    analysis_table = [analysis_table, ana_result];
                    app.Gauge.Value = gauge_state + gauge_step_small * i_ROI;
                end

                %Save results to struct
                app.results_analysis.(select_cache).analysis_table = analysis_table;
                app.results_analysis.(select_cache).analysis_table_header = resulttable_header;
                app.results_analysis.(select_cache).analysis_log = analysis_log;
                app.Gauge.Value = gauge_step * i_recordings;
            end
            %Set Results tab items and activate result tab
            if app.file_type_mode == 1
                app.results_analysis.axisDropDown_Met_list = axisDropDown_Met_list_cache;
            end
            app.setListBox_analysed();

            % app.AnalysisinprogressLabel.Position = [602,-112,443,63]; %Move AnalysisinprogressLabel out of visible area
            app.AnalysisinprogressLabel.Visible = "off";
            app.Gauge.Visible = "off";
            app.Gauge.Value = 0;
            app.menue_enable(1);
            app.RawPanel.Enable = "on";
            app.AnalysisPanel.Enable = "on";

            app.AnalysisAddtoresultsCheckBox.Enable = "on"; %Enable add to results button
            if app.Analysis_AutoSwitchCheckBox.Value == 1 %If activated, switch to result tab
                app.TabGroup2.SelectedTab = app.ResultsTab;
            end

            app.StartanalysisButton.Enable = "on"; %Enable analysis button
        end

        % Button pushed function: AutoyButton
        function AutoyButtonPushed(app, event)
            %Set y-min and y-max spinner based und RawUIAxes auto axis
            %limit selection
            app.RawUIAxes.YLimMode = 'auto';
            app.yMinSpinner.Value = app.RawUIAxes.YLim(1);
            app.yMaxSpinner.Value = app.RawUIAxes.YLim(2);
        end

        % Value changed function: yMinSpinner
        function yMinSpinnerValueChanged(app, event)
            %Set y-axis limits based on y-min value
            if app.yMinSpinner.Value < app.yMaxSpinner.Value
                app.RawUIAxes.YLim = [app.yMinSpinner.Value, app.yMaxSpinner.Value];
            else %If new y-min would be equal to y-max
                app.yMaxSpinner.Value = app.yMinSpinner.Value + 1; %increase value of y-max spinner  by one
                app.RawUIAxes.YLim = [app.yMinSpinner.Value, app.yMaxSpinner.Value];
            end
        end

        % Value changed function: yMaxSpinner
        function yMaxSpinnerValueChanged(app, event)
            %Set y-axis limits based on y-max value
            if app.yMinSpinner.Value < app.yMaxSpinner.Value
                app.RawUIAxes.YLim = [app.yMinSpinner.Value, app.yMaxSpinner.Value];
            else %If new y-max would be equal to y-min
                app.yMinSpinner.Value = app.yMaxSpinner.Value - 1; %decrease value of y-min spinner  by one
                app.RawUIAxes.YLim = [app.yMinSpinner.Value, app.yMaxSpinner.Value];
            end
        end

        % Button pushed function: AutoxButton
        function AutoxButtonPushed(app, event)
            %Set x-min and x-max spinner based und RawUIAxes auto axis
            %limit selection
            app.RawUIAxes.XLimMode = 'auto';
            app.xMinSpinner.Value = app.spinner_limits(1);
            app.xMaxSpinner.Value = app.spinner_limits(2);
        end

        % Value changed function: xMinSpinner
        function xMinSpinnerValueChanged(app, event)
            %Set x-axis limits based on x-min value
            if app.xMinSpinner.Value < app.xMaxSpinner.Value
                app.RawUIAxes.XLim = [app.xMinSpinner.Value, app.xMaxSpinner.Value];
            else %If new x-min would be equal to x-max
                app.xMaxSpinner.Value = app.xMinSpinner.Value + 1; %increase value of x-max spinner  by one
                app.RawUIAxes.XLim = [app.xMinSpinner.Value, app.xMaxSpinner.Value];
            end
        end

        % Value changed function: xMaxSpinner
        function xMaxSpinnerValueChanged(app, event)
            %Set x-axis limits based on x-max value
            if app.xMinSpinner.Value < app.xMaxSpinner.Value
                app.RawUIAxes.XLim = [app.xMinSpinner.Value, app.xMaxSpinner.Value];
            else %If new x-max would be equal to x-min
                app.xMinSpinner.Value = app.xMaxSpinner.Value - 1; %decrease value of x-min spinner  by one
                app.RawUIAxes.XLim = [app.xMinSpinner.Value, app.xMaxSpinner.Value];
            end
        end

        % Value changed function: HighlightsweepButton, SweepSpinner
        function SweepSpinnerValueChanged(app, event)
            if app.SweepLabel.Value ~= 0
                sweep_index_new = app.sweep_index_highlight + app.SweepSpinner.Value;
                % end
                if sweep_index_new == size(app.SweepsListBox.Value, 2)
                    app.SweepSpinner.Limits = [-1, 0];
                elseif sweep_index_new == 1
                    app.SweepSpinner.Limits = [0, 1];
                else
                    app.SweepSpinner.Limits = [-1, 1];
                end

                app.sweep_index_highlight = sweep_index_new;
                app.SweepLabel.Value = app.SweepsListBox.Value(app.sweep_index_highlight);
                app.SweepSpinner.Value = 0;

                select_cache = sprintf('recording_%d', app.RecordingDropDown.Value);
                app.plot_selected(select_cache, 2); %mode 2 since other sweep of same recording was selected
            end
        end

        % Value changed function: DisplayallButton, RecordingDropDown
        function RecordingDropDownValueChanged(app, event)
            %Plot new since recording was changed or all/mean/sd sweep(s)
            %should (not) be shown
            app.RecordingSpinner.Value = app.RecordingDropDown.Value;
            addStyle(app.RecordingListBox, app.baseStyle);
            addStyle(app.RecordingListBox, app.selectedStyle, "item", app.RecordingDropDown.Value);
            app.change_recording();
        end

        % Value changed function: DisplaymeanButton
        function DisplaymeanButtonValueChanged(app, event)
            %Deaktive display of all/ highlightet sweeps, if mean sweep
            %will be displayed. (can be redisplayed by activating their
            %buttons again. Reaktivate display all button if show mean
            %sweep button is deactivated
            if app.DisplaymeanButton.Value == 1
                app.DisplayallButton.Value = 0;
                app.HighlightsweepButton.Value = 0;
            else
                app.DisplayallButton.Value = 1;
                app.DisplaySDButton.Value = 0;
            end
            app.RecordingDropDownValueChanged()
        end

        % Value changed function: DisplaySDButton
        function DisplaySDButtonValueChanged(app, event)
            %Deaktive display of all/ highlightet sweeps, if mean sweep
            %will be displayed. (can be redisplayed by activating their
            %buttons again. Activate display of mean sweep, if not already activated.
            %Reaktivate display all button if show mean
            %sweep button is deactivated
            if app.DisplaySDButton.Value == 1
                app.DisplayallButton.Value = 0;
                app.HighlightsweepButton.Value = 0;
                app.DisplaymeanButton.Value = 1;
            end
            app.RecordingDropDownValueChanged()
        end

        % Value changed function: Marker1Button, Marker2Button, 
        % ...and 14 other components
        function Marker1ButtonValueChanged(app, event)
            %Set marker based on selection
            app.set_marker();
        end

        % Value changed function: RecordingSpinner
        function RecordingSpinnerValueChanged(app, event)
            %Change recording by spinner selection
            %Improve for spinner direction
            app.RecordingDropDown.Value = app.RecordingSpinner.Value;
            addStyle(app.RecordingListBox, app.baseStyle);
            addStyle(app.RecordingListBox, app.selectedStyle, "item", app.RecordingDropDown.Value);
            app.change_recording();
        end

        % Callback function: ButtonGroup, EpisodeSpinner, LeftSpinner
        function LeftSpinnerValueChanged(app, event)
            app.LeftSpinner.Enable = "off";
            app.RightSpinner.Enable = "off";
            app.new_changes()
            try %#ok<TRYNC>
                %Limit LeftSpinner value to recordings x-min and max values
                if event.Value < app.LeftSpinner.Limits(1)
                    app.LeftSpinner.Value = app.LeftSpinner.Limits(1);
                elseif event.Value > app.LeftSpinner.Limits(2)
                    app.LeftSpinner.Value = app.LeftSpinner.Limits(2);
                end
            end

            if app.OffButton.Value == 1 %No baseline correction
                for i_reg = 1:6 %Limit slope analysis to linear regression
                    Analysis_RegressionDropDown = sprintf('Analysis_RegressionDropDown_%d', i_reg);
                    app.(Analysis_RegressionDropDown).Items = "Linear";
                    app.(Analysis_RegressionDropDown).ItemsData = 1;
                end
            elseif app.CursorsButton.Value == 0 %Baseline correction on
                for i_reg = 1:6 %Allow all regression types
                    Analysis_RegressionDropDown = sprintf('Analysis_RegressionDropDown_%d', i_reg);
                    app.(Analysis_RegressionDropDown).Items = ["Linear", "1x exp", "2x exp", "All"];
                    app.(Analysis_RegressionDropDown).ItemsData = 1:4;
                end
            end

            select_cache = sprintf('recording_%d', app.RecordingDropDown.Value);
            if app.LeftSpinner.Value >= app.RightSpinner.Value %In case new LeftSpinner would be larger than RightSpinner value
                app.RightSpinner.Value = app.LeftSpinner.Value + app.loaded_files.(select_cache).resolution;%Increase RightSpinner value by one resolution unit
            end

            app.baseline_calc(select_cache) %calculate new baseline and mean and sd sweeps

            if app.CursorsButton.Value == 1
                app.LeftSpinner.Enable = "on";
                app.RightSpinner.Enable = "on";
            end
        end

        % Value changed function: RightSpinner
        function RightSpinnerValueChanged(app, event)
            try %#ok<TRYNC>
                %Limit RightSpinner value to recordings x-min and max values
                if event.Value < app.RightSpinner.Limits(1)
                    app.RightSpinner.Value = app.RightSpinner.Limits(1);
                elseif event.Value > app.RightSpinner.Limits(2)
                    app.RightSpinner.Value = app.RightSpinner.Limits(2);
                end
            end
            select_cache = sprintf('recording_%d', app.RecordingDropDown.Value);
            if app.LeftSpinner.Value >= app.RightSpinner.Value %In case new RightSpinner would be smaller than LeftSpinner value
                app.LeftSpinner.Value = app.RightSpinner.Value - app.loaded_files.(select_cache).resolution; %Decrease LeftSpinner value by one resolution unit
            end
            app.baseline_calc(select_cache) %calculate new baseline and mean and sd sweeps
        end

        % Button pushed function: SelectallsweepsButton
        function SelectallsweepsButtonPushed(app, event)
            %Select all sweeps for analysis
            alteration.PreviousValue = app.SweepsListBox.Value;
            app.SweepsListBox.Value = app.SweepsListBox.ItemsData;
            alteration.Value = app.SweepsListBox.Value;
            alteration.manual = 1;
            app.change_sweep(alteration) %Plot all sweeps and recalculate mean and sd sweeps
        end

        % Value changed function: SelectrecordingforanalysisButton
        function SelectrecordingforanalysisButtonValueChanged(app, event)
            %Include or remove selected recording from analysis
            app.new_changes()
            if isempty(app.SweepsListBox.Value) %No sweeps are selected
                app.SelectrecordingforanalysisButton.Value = 0; %Set button value to 0
            else
                if app.SelectrecordingforanalysisButton.Value == 1 %If recording should be included
                    if isempty(app.RecordingListBox.Value) %empty app.RecordingListBox.Value is a cell, filled one is a matrix/string
                        value_temp = [];
                    else
                        value_temp = app.RecordingListBox.Value; %Formerlly cell2mat()
                    end
                    value_temp = sort([value_temp, app.RecordingDropDown.Value]); %add recording to selection
                    app.StartanalysisButton.Enable = "on"; %Enable start analysis button
                    app.RecordingListBox.Value = value_temp;
                    app.baseline_cor_failed_func() %Check if baseline correction worked for all selected recordings
                else %If recording should be excluded
                    value_temp = app.RecordingListBox.Value;
                    value_temp(value_temp == app.RecordingDropDown.Value) = []; %remove recording to selection
                    if isempty(value_temp)
                        app.StartanalysisButton.Enable = "off"; %Disable start analysis button
                    end
                    app.RecordingListBox.Value = value_temp;
                end
                app.RecordingListBox_Value_BU = app.RecordingListBox.Value;
            end
        end

        % Value changed function: Button_ROIBaseline, CheckBox_ROI_2, 
        % ...and 4 other components
        function CheckBox_ROI2ValueChanged(app, event)
            %enables/disables editable analysis settings based on selected
            %check boxes
            app.new_changes()
            app.analysis_ROI_selection;
        end

        % Value changed function: AnalysisDropDown_1, AnalysisDropDown_2, 
        % ...and 4 other components
        function AnalysisDropDown_1ValueChanged(app, event)
            %Enable and disable configuration settings based on selected
            %analysis method
            app.new_changes()
            for i = 1:6 %For every analysis method slot
                %Create name strings for dynamic access to properties
                AnalysisDropDown = sprintf('AnalysisDropDown_%d', i);
                PeakDirDropDown = sprintf('PeakDirDropDown_%d', i);
                SlopeSpinner_Lower = sprintf('SlopeSpinner_Lower_%d', i);
                SlopeSpinner_Upper = sprintf('SlopeSpinner_Upper_%d', i);
                CheckBox_ROI = sprintf('CheckBox_ROI_%d', i);
                Analysis_RegressionDropDown = sprintf('Analysis_RegressionDropDown_%d', i);
                %Fetch ROIs check box value (0 (off) or 1 (on))
                if i == 1 %For ROI CheckBox_value must be defined manually, since no checkbox is present
                    CheckBox_value = 1;
                else
                    CheckBox_value = app.(CheckBox_ROI).Value;
                end
                %Disable each setting field
                app.(PeakDirDropDown).Enable = "off";
                app.(SlopeSpinner_Lower).Enable = "off";
                app.(SlopeSpinner_Upper).Enable = "off";
                app.(Analysis_RegressionDropDown).Enable = "off";

                %Enable necessary setting fields
                if CheckBox_value == 1 && (app.(AnalysisDropDown).Value == 2 || app.(AnalysisDropDown).Value == 5) %Amplitude or AUC analysis
                    app.(PeakDirDropDown).Enable = "on";
                elseif CheckBox_value == 1 && (app.(AnalysisDropDown).Value == 3 || app.(AnalysisDropDown).Value == 4) %Slope analysis
                    app.(PeakDirDropDown).Enable = "on";
                    app.(SlopeSpinner_Lower).Enable = "on";
                    app.(SlopeSpinner_Upper).Enable = "on";
                    app.(Analysis_RegressionDropDown).Enable = "on";
                end
            end
        end

        % Value changed function: ROISpinnerLeft_1, ROISpinnerLeft_2, 
        % ...and 4 other components
        function ROISpinnerLeft_1ValueChanged(app, event)
            app.new_changes()
            %Keeps the spinner for ROIs lower boundary always smaller as the
            %spinner for the upper boundary
            for i = 1:6
                ROISpinnerLeft = sprintf('ROISpinnerLeft_%d', i);
                ROISpinnerRight = sprintf('ROISpinnerRight_%d', i);
                if app.(ROISpinnerLeft).Value >= app.(ROISpinnerRight).Value %If value of left spinner would'nt be smaller than value of right spinner...
                    app.(ROISpinnerRight).Value = app.(ROISpinnerLeft).Value + app.analysis_resolution; %Increase right spinner value by the set resolution
                end
            end
        end

        % Value changed function: ROISpinnerRight_1, ROISpinnerRight_2, 
        % ...and 4 other components
        function ROISpinnerRight_1ValueChanged(app, event)
            %Keeps the spinner for ROIs upper boundary always higher as the
            %spinner for the lower boundary
            app.new_changes()
            for i = 1:6
                ROISpinnerLeft = sprintf('ROISpinnerLeft_%d', i);
                ROISpinnerRight = sprintf('ROISpinnerRight_%d', i);
                if app.(ROISpinnerLeft).Value >= app.(ROISpinnerRight).Value %If value of left spinner wouldn't be smaller than value of right spinner...
                    app.(ROISpinnerLeft).Value = app.(ROISpinnerRight).Value - app.analysis_resolution; %Decrease left spinner value by the set resolution
                end
            end
        end

        % Value changed function: RecordingListBox_2
        function RecordingListBox_2ValueChanged(app, event)
            %Fill results table with data from selected recording
            select_cache = char(app.results_analysis.RecListBox_data(app.RecordingListBox_2.Value,2));
            app.Results_UITable2.ColumnName =  app.results_analysis.(select_cache).analysis_table_header;
            app.Results_UITable2.Data = app.results_analysis.(select_cache).analysis_table;
            app.Results_AnalysislogTextArea.Value = app.results_analysis.(select_cache).analysis_log;
        end

        % Value changed function: Results_yaxisCheckBox_2, 
        % ...and 4 other components
        function Results_yaxisCheckBox_2ValueChanged(app, event)
            %Enable or disable drop down fields for results of recordings,
            %when associated check box was selected
            for i = 2:6
                Results_yaxisCheckBox = sprintf('Results_yaxisCheckBox_%d', i);
                Results_yaxisDropDown_Rec = sprintf('Results_yaxisDropDown_Rec_%d', i);
                Results_yaxisDropDown_Met = sprintf('Results_yaxisDropDown_Met_%d', i);
                if app.(Results_yaxisCheckBox).Value == 1
                    app.(Results_yaxisDropDown_Rec).Enable = "on";
                    app.(Results_yaxisDropDown_Met).Enable = "on";
                else
                    app.(Results_yaxisDropDown_Rec).Enable = "off";
                    app.(Results_yaxisDropDown_Met).Enable = "off";
                end
            end
        end

        % Callback function: LinestyleButtonGroup, PlotButton
        function PlotButtonPushed(app, event)
            app.plot_results() %Refresh the results plot, when a different marker style was selected
        end

        % Value changed function: Results_xaxisDropDown
        function Results_xaxisDropDownValueChanged(app, event)
            %Enables time unit drop down and normalization check box, if a
            %result column with time values was selected
            if app.Results_xaxisDropDown.Value == 2 %Internally Sweep start times, allow time unit change
                app.Results_timescaleDropDown.Enable = "on";
                app.mintime0Label.Enable = "off";
                app.XCorCheckBox.Enable = "off";
            elseif app.Results_xaxisDropDown.Value == 3 %Absolute sweep start times, allow time unit change and normalization
                app.Results_timescaleDropDown.Enable = "on";
                app.mintime0Label.Enable = "on";
                app.XCorCheckBox.Enable = "on";
            else %No time values were selected, disable fields
                app.Results_timescaleDropDown.Enable = "off";
                app.mintime0Label.Enable = "off";
                app.XCorCheckBox.Enable = "off";
            end
        end

        % Button pushed function: Export_SetsavepathButton
        function Export_SetsavepathButtonPushed(app, event)
            %Select export folder
            if isempty(app.Export_Label.Text) %In case no file path was already selected
                userProfile = getenv('USERPROFILE'); %Fetch users default folder...
                myDocsFolder = sprintf('%s\\My Documents', userProfile); %...and suggest documents folder by default
                selpath = uigetdir(myDocsFolder,'Select save folder'); %Ask for directory
            else
                myDocsFolder = app.Export_Label.Text; %Fetch previously selected path as starting point for browsing
                selpath = uigetdir(myDocsFolder,'Select save folder'); %Ask for directory
            end
            figure(app.UIFigure) %Necessary to move app window back to foreground after use of 'uigetfile'
            if selpath == 0 %if no path was selected
                return
            end
            app.Export_Label.Text = selpath; %save and display selected folder
        end

        % Button pushed function: Export_resultsButton
        function Export_resultsButtonPushed(app, event)
            %Export result table, log file and optional mean and sd data table in selected format

            %Disable export button to prevent
            app.Export_resultsButton.Enable = "off";
            app.menue_enable(0);
            app.RawPanel.Enable = "off";
            app.AnalysisPanel.Enable = "off";
            % app.ExportinprogressLabel.Position = [622,458,402,63]; %Move ExportinprogressLabel in visible area
            app.ExportinprogressLabel.Visible = "on";
            app.Gauge.Visible = "on";
            pause(0.1) %Allow button to be disabled

            convert_error = 0;

            %Fetch export directory, in case it wasn't yet defined
            if isempty(app.Export_Label.Text)
                app.Export_SetsavepathButtonPushed
            end
            if isempty(app.Export_Label.Text) %Stop function if user didn't select a directory
                % app.ExportinprogressLabel.Position = [622,-112,402,63]; %Move ExportinprogressLabel out of visible area
                app.ExportinprogressLabel.Visible = "off";
                app.menue_enable(1);
                app.RawPanel.Enable = "on";
                app.AnalysisPanel.Enable = "on";
                app.Export_resultsButton.Enable = "on";
                return
            end
            selpath = app.Export_Label.Text; %Fetch selected directory

            if ~isempty(app.AddpostfixEditField.Value) %In case postfix should be added
                postfix = sprintf('_%s',app.AddpostfixEditField.Value);
            else
                postfix = "";
            end
            datename = string(datetime('now','Format','uuMMdd''_''HHmmss'));

            %Prepare general comments data;
            general_comments_header = "General comments";
            general_comments = [datename; ""; app.GeneralcommentsTextArea.Value]; %Fetch comment
            %Determine loaded but not analysed recordings
            Loaded_cache = string(app.RecordingListBox.Items);
            for i = 1:size(app.RecordingListBox_2.Items, 2)
                value_temp = string(app.RecordingListBox_2.Items{i});
                Loaded_cache(Loaded_cache == value_temp)  = [];
            end
            if ~isempty(Loaded_cache)
                general_comments = [general_comments; ""; "Excluded recordings:"; Loaded_cache'];
            end

            if app.Export_FormatDropDown.Value == 1 %In case results should be exportet as tab separated text files
                %For every result table, a separate fill will be generated
                exportformat = '.txt'; %.tsv not yet (easily) supported in matlab

                %Generate export folder in selected directory
                foldername = sprintf('%s_Analysis%s', datename, postfix);
                newfolder = fullfile(selpath,foldername);
                mkdir(newfolder)
                %Save general comments
                general_comments_name = sprintf('_%s%s_general_log%s', datename, postfix, exportformat); %Create log files file name...
                general_comments_path = fullfile(newfolder,general_comments_name); %...and prepare export path
                T_comments = array2table(general_comments); %Convert log matrix to table
                T_comments.Properties.VariableNames = general_comments_header; %Ad column name to log table
                %Save tables as tsv text files
                writetable(T_comments,general_comments_path,'Delimiter','\t');

                T_convert = table();
                recording = [];

                RecListBox_cache = app.results_analysis.RecListBox_data; %Fetch list of analysed recordings
                gauge_step = 1/str2double(RecListBox_cache(end,1)) * 100;
                for i_save = 1:str2double(RecListBox_cache(end,1)) %For every result
                    select_cache = RecListBox_cache(i_save,2); %Fetch recording name
                    recording_cache = string(app.results_analysis.(select_cache).filename); %Fetch recordings file name
                    log_name = sprintf('%s_%s%s_log%s', datename, recording_cache, postfix, exportformat); %Create log files file name...
                    log_path = fullfile(newfolder,log_name); %...and prepare export path
                    results_name = sprintf('%s_%s%s_results%s', datename, recording_cache, postfix, exportformat); %Create result tables file name...
                    results_path = fullfile(newfolder,results_name); %...and prepare export path
                    baseline_corrected = sum(app.results_analysis.(select_cache).analysis_log == "Baseline corrected"); %Check if baseline was corrected

                    recording_log = app.results_analysis.(select_cache).analysis_log;
                    recording_log = [recording_log; ""; "Comments:"];
                    if ~isempty(app.loaded_files.(select_cache).comment)
                        recording_log = [recording_log; app.loaded_files.(select_cache).comment];
                    end
                    excluded_sweeps = setdiff(app.loaded_files.(select_cache).all_sweeps, app.loaded_files.(select_cache).selected_sweeps);
                    recording_log = [recording_log; ""; "Excluded sweeps:"];
                    if ~isempty(excluded_sweeps)
                        app.loaded_files.(select_cache).all_sweeps;
                        app.loaded_files.(select_cache).selected_sweeps;
                        excluded_sweeps = num2str(excluded_sweeps);
                        excluded_sweeps = regexprep(excluded_sweeps, ' +', ' ');
                        excluded_sweeps = string(strrep(excluded_sweeps, ' ', ', '));

                        recording_log = [recording_log; excluded_sweeps];
                    end

                    T_log = array2table(recording_log); %Convert log matrix to table
                    T_log.Properties.VariableNames = "Analysis log"; %Ad column name to log table
                    T_results = array2table(app.results_analysis.(select_cache).analysis_table); %Convert result matrix to table
                    T_results.Properties.VariableNames = app.results_analysis.(select_cache).analysis_table_header; %Ad column names to result table
                    %Save tables as tsv text files
                    writetable(T_log,log_path,'Delimiter','\t');
                    writetable(T_results,results_path,'Delimiter','\t');

                    if app.Export_meansweepwithSDCheckBox.Value == 1 %In case calculated mean and standard deviation sweeps should be exportet
                        mean_name = sprintf('%s_%s%s_mean_SD%s', datename, recording_cache, postfix, exportformat); %Create file name...
                        mean_path = fullfile(newfolder,mean_name); %...and path
                        if baseline_corrected %If the baseline corrected sweeps should be exportet
                            % if eq(app.results_analysis.(select_cache).analysis_log(4), "Baseline corrected") %If the baseline corrected sweeps should be exportet
                            mean_cache = [app.loaded_files.(select_cache).mean_sd(:,1), app.loaded_files.(select_cache).mean_sd(:,4:5)]; %Fetch data columns
                            T_mean = array2table(mean_cache); %Convert to table
                            %Create and add coloumn names to table
                            mean_header_cache = ["time (ms)", string(sprintf('Mean amplitude (%s, baseline corrected)', app.loaded_files.(select_cache).unit)), string(sprintf('SD of mean amplitude (%s, baseline corrected)', app.loaded_files.(select_cache).unit))];
                            T_mean.Properties.VariableNames =   mean_header_cache;
                        else %Export the baseline uncorrected sweeps
                            mean_cache = app.loaded_files.(select_cache).mean_sd(:,1:3); %Fetch data columns
                            T_mean = array2table(mean_cache); %Convert to table
                            %Create and add coloumn names to table
                            mean_header_cache = ["time (ms)", string(sprintf('Mean amplitude (%s)', app.loaded_files.(select_cache).unit)), string(sprintf('SD of mean amplitude (%s)', app.loaded_files.(select_cache).unit))];
                            T_mean.Properties.VariableNames =   mean_header_cache;
                        end
                        writetable(T_mean,mean_path,'Delimiter','\t'); %Save as tsv text files
                    end

                    %Prepare data for combined Excel result table
                    try
                        T_convert = [T_convert; T_results];
                    catch %In case tables don't match, e.g. results are based on different analysis
                        convert_error = 1;
                    end
                    recording = [recording; recording_cache];
                    app.Gauge.Value = gauge_step * i_save;
                end

                if app.AdditionallyunifyresultsinsingleExceltableCheckBox.Value == 1 && convert_error == 0
                    recording = table(recording);
                    export_data = [recording, T_convert];

                    filename = sprintf('%s%s_converted.xlsx', datename, postfix);
                    filepath = fullfile(newfolder,filename);
                    writetable(export_data,filepath)
                end

            elseif app.Export_FormatDropDown.Value == 2 %Export as Excel file
                %Every result table will be a sheet in the same file. The
                %log information will be included in the results sheet
                exportformat = '.xlsx';

                %Generate file name and path in selected directory
                datename = sprintf('%s%s_Analysis_all_%s', datename, postfix, exportformat);
                filepath = fullfile(selpath,datename);
                if app.Export_meansweepwithSDCheckBox.Value == 1 %In case calculated mean and standard deviation sweeps should be exportet
                    %Generate file name and path in selected directory for
                    %mean and sd table
                    filename_mean = datetime('now','Format','uuMMdd''_''HHmmss');
                    filename_mean = sprintf('%s%s_mean_sd%s', filename_mean, postfix, exportformat);
                    filepath_mean = fullfile(selpath,filename_mean);
                end
                %Generate general comment sheet
                sheetname = "_General_analysis_comments";
                writematrix([general_comments_header; general_comments],filepath,'Sheet',sheetname,'Range','A1')

                RecListBox_cache = app.results_analysis.RecListBox_data; %Fetch list of ranalysed recordings
                gauge_step = 1/str2double(RecListBox_cache(end,1)) * 100;
                for i_save = 1:str2double(RecListBox_cache(end,1)) %For every result
                    select_cache = RecListBox_cache(i_save,2); %Fetch recording name
                    header_cache = ["Log", app.results_analysis.(select_cache).analysis_table_header]; %Generate header for excel sheet
                    log_cache = app.results_analysis.(select_cache).analysis_log; %Fetch analysis log
                    log_cache = [log_cache; ""; "Comments:"];
                    if ~isempty(app.loaded_files.(select_cache).comment)
                        log_cache = [log_cache; app.loaded_files.(select_cache).comment];
                    end
                    excluded_sweeps = setdiff(app.loaded_files.(select_cache).all_sweeps, app.loaded_files.(select_cache).selected_sweeps);
                    log_cache = [log_cache; ""; "Excluded sweeps:"];
                    if ~isempty(excluded_sweeps)
                        app.loaded_files.(select_cache).all_sweeps;
                        app.loaded_files.(select_cache).selected_sweeps;
                        excluded_sweeps = num2str(excluded_sweeps);
                        excluded_sweeps = regexprep(excluded_sweeps, ' +', ' ');
                        excluded_sweeps = string(strrep(excluded_sweeps, ' ', ', '));

                        log_cache = [log_cache; excluded_sweeps];
                    end

                    result_cache_raw = app.results_analysis.(select_cache).analysis_table; %Fetch result table...
                    result_cache = num2cell(result_cache_raw);%...convert to cell...
                    if ~(isstring(result_cache{1})) %In case cell already contains string values
                        result_cache(isnan(result_cache_raw)) ={'NaN'}; %...and replace numeric NaN to char 'NaN' (Otherwise cells with NaN values would be empty in excel sheet
                    end
                    sheetname = sprintf('%d_%s', i_save, app.results_analysis.(select_cache).filename); %Fetch file name and add a number in front to generate the sheets name
                    if length(sheetname) > 30 %In case the file name would be to long as a sheet name in Excel...
                        sheetname = sheetname(1:30); %use only the first 30 characters
                    end
                    %Write results in Excel sheet, 'Range' defines top left
                    %cell in Excel were the result table will be included
                    %in accordance to their size
                    writematrix(header_cache,filepath,'Sheet',sheetname,'Range','A1') %Column names in first row
                    writematrix(log_cache,filepath,'Sheet',sheetname,'Range','A2') %Log in second row+, first coloumn
                    writecell(result_cache,filepath,'Sheet',sheetname,'Range','B2') %Results in in second row, second coloumn+
                    if app.Export_meansweepwithSDCheckBox.Value == 1 %In case calculated mean and standard deviation sweeps should be exportet
                        baseline_corrected = sum(app.results_analysis.(select_cache).analysis_log == "Baseline corrected"); %Check if baseline was corrected
                        if baseline_corrected %If the baseline corrected sweeps should be exportet
                            % if eq(app.results_analysis.(select_cache).analysis_log(4), "Baseline corrected") %If the baseline corrected sweeps should be exportet
                            mean_cache = [app.loaded_files.(select_cache).mean_sd(:,1), app.loaded_files.(select_cache).mean_sd(:,4:5)]; %Fetch data columns
                            mean_header_cache = ["time (ms)", string(sprintf('Mean amplitude (%s, baseline corrected)', ...
                                app.loaded_files.(select_cache).unit)), string(sprintf('SD of mean amplitude (%s, baseline corrected)', ...
                                app.loaded_files.(select_cache).unit))]; %Prepare column names
                        else %Export the baseline uncorrected sweeps
                            mean_cache = app.loaded_files.(select_cache).mean_sd(:,1:3); %Fetch data columns
                            mean_header_cache = ["time (ms)", string(sprintf('Mean amplitude (%s)', ...
                                app.loaded_files.(select_cache).unit)), string(sprintf('SD of mean amplitude (%s)', ...
                                app.loaded_files.(select_cache).unit))]; %Prepare column names
                        end
                        writematrix(mean_header_cache, filepath_mean, 'Sheet',sheetname,'Range','A1'); %Write column names to excel sheet
                        writematrix(mean_cache, filepath_mean, 'Sheet',sheetname,'Range','A2'); %write data
                    end
                    app.Gauge.Value = gauge_step * i_save;
                end
            end
            if convert_error == 1
                msg = sprintf('Results could not be unified in a single Excel file.\nPlease check if all recordings were analysed using the same settings.');
                title = 'Error unifying results';
                waitfor(msgbox(msg,title));
            end

            % app.ExportinprogressLabel.Position = [622,-112,402,63]; %Move ExportinprogressLabel out of visible area
            app.ExportinprogressLabel.Visible = "off";
            app.Gauge.Visible = "off";
            app.Gauge.Value = 0;
            app.menue_enable(1);
            app.RawPanel.Enable = "on";
            app.AnalysisPanel.Enable = "on";
            app.Export_resultsButton.Enable = "on";
        end

        % Button pushed function: SelectallrecordingsButton
        function SelectallrecordingsButtonPushed(app, event)
            %Select all recordings for analysis
            app.new_changes()
            app.RecordingListBox.Value = app.RecordingListBox.ItemsData;
            app.RecordingListBox_Value_BU = app.RecordingListBox.Value;
            app.SelectrecordingforanalysisButton.Value = 1;
            app.StartanalysisButton.Enable = "on"; %Enable start analysis button
            app.baseline_cor_failed_func() % Check if baseline correction worked for all selected recordings
        end

        % Button pushed function: UnselectallrecordingsButton
        function UnselectallrecordingsButtonPushed(app, event)
            %Unselect all recordings
            app.new_changes()
            app.RecordingListBox.Value = {};
            app.RecordingListBox_Value_BU = app.RecordingListBox.Value;
            app.SelectrecordingforanalysisButton.Value = 0;
            app.StartanalysisButton.Enable = "off"; %Disable start analysis button
        end

        % Value changed function: RelativetoDropDown_2, 
        % ...and 4 other components
        function RelativetoDropDown_2ValueChanged(app, event)
            app.new_changes()
            %Change lower limit of ROI spinner to -inf, in case ROI is
            %relative to another ROI. Normally negative values are not
            %allowed
            for i_ROISpinner = 2:6
                ROISpinnerLeft = sprintf('ROISpinnerLeft_%d', i_ROISpinner);
                ROISpinnerRight = sprintf('ROISpinnerRight_%d', i_ROISpinner);
                RelativetoDropDown = sprintf('RelativetoDropDown_%d', i_ROISpinner);
                if app.(RelativetoDropDown).Value > 0 %If ROI is relative to another
                    app.(ROISpinnerLeft).Limits(1) = "-inf";
                    app.(ROISpinnerRight).Limits(1) = "-inf";
                else %If spinner values are negative after changing ROI as independent,
                    %set them to positive values
                    if app.(ROISpinnerLeft).Value < app.analysis_resolution
                        app.(ROISpinnerLeft).Value = app.analysis_resolution;
                    end
                    if app.(ROISpinnerRight).Value < (app.analysis_resolution * 2)
                        app.(ROISpinnerRight).Value = (app.analysis_resolution * 2);
                    end
                    %Set spinner lower limit based on rset resolution
                    app.(ROISpinnerLeft).Limits(1) = app.analysis_resolution;
                    app.(ROISpinnerRight).Limits(1) = app.analysis_resolution * 2;
                end
            end
        end

        % Value changed function: SlopeSpinner_Lower_1, 
        % ...and 5 other components
        function SlopeSpinner_Lower_1ValueChanged(app, event)
            %Keep value of lower slope spinner always smaller than value of
            %upper slope spinner
            app.new_changes()
            for i = 1:6
                SlopeSpinner_Lower = sprintf('SlopeSpinner_Lower_%d', i);
                SlopeSpinner_Upper = sprintf('SlopeSpinner_Upper_%d', i);
                if app.(SlopeSpinner_Lower).Value >= app.(SlopeSpinner_Upper).Value %if value of lower slope spinner isn't smaller than that of upper slope spinner...
                    app.(SlopeSpinner_Upper).Value = app.(SlopeSpinner_Lower).Value + 1; %...increase upper slope spinners value to lower slope spinners value + 1
                end
            end
        end

        % Value changed function: SlopeSpinner_Upper_1, 
        % ...and 5 other components
        function SlopeSpinner_Upper_1ValueChanged(app, event)
            %Keep value of lower slope spinner always smaller than value of
            %upper slope spinner
            app.new_changes()
            for i = 1:6
                SlopeSpinner_Lower = sprintf('SlopeSpinner_Lower_%d', i);
                SlopeSpinner_Upper = sprintf('SlopeSpinner_Upper_%d', i);
                if app.(SlopeSpinner_Lower).Value >= app.(SlopeSpinner_Upper).Value %if value of lower slope spinner isn't smaller than that of upper slope spinner...
                    app.(SlopeSpinner_Lower).Value = app.(SlopeSpinner_Upper).Value - 1; %...decrease lower slope spinners value to upper slope spinners value - 1
                end
            end
        end

        % Value changed function: Analysis_SampleRateSpinner, 
        % ...and 1 other component
        function SampleRateEditFieldValueChanged(app, event)
            %Calculate and display digitally sample rate change
            %Spinner range from -4 to 4 (up to 5-fold increase or decrease
            %of sample frequency)
            app.new_changes()
            if app.Analysis_SampleRateSpinner.Value == 0 %If no sample rate modification should be down
                app.SampleRateEditField.Value = 1;
            elseif app.Analysis_SampleRateSpinner.Value > 0 %If sample rate should be increased
                app.SampleRateEditField.Value = app.Analysis_SampleRateSpinner.Value + 1;
            elseif app.Analysis_SampleRateSpinner.Value < 0 %If sample rate should be decreased
                app.SampleRateEditField.Value = 1/(abs(app.Analysis_SampleRateSpinner.Value) + 1);
            end
        end

        % Menu selected function: ROIboundsspinnerresolutionMenu
        function ROIboundsspinnerresolutionMenuSelected(app, event)
            app.menue_state =[app.RawPanel.Enable, app.AnalysisPanel.Enable];
            app.menue_enable(0);
            %Allow user to set ROI left/ right boundary spinner resolution
            %Disable Panels
            app.RawPanel.Enable = "off";
            app.AnalysisPanel.Enable = "off";
            % app.SetROIsleftrightboundaryspinnerresolutionPanel.Position = [344,402,352,107]; %Move setting panel in visible area
            app.SetROIsleftrightboundaryspinnerresolutionPanel.Visible = "on";
        end

        % Button pushed function: CancelButton
        function CancelButtonPushed(app, event)
            %If change of spinner resolution was canceled
            app.SpinnerresolutionmsEditField.Value = app.analysis_resolution; %Reset preset resolution in input field
            %Enable Panels
            app.RawPanel.Enable = app.menue_state(1);
            app.AnalysisPanel.Enable = app.menue_state(2);
            % app.SetROIsleftrightboundaryspinnerresolutionPanel.Position = [344,-119,352,107]; %Move setting panel out of visible area
            app.SetROIsleftrightboundaryspinnerresolutionPanel.Visible = "off";
            app.menue_enable(1);
        end

        % Button pushed function: OKButton
        function OKButtonPushed(app, event)
            app.analysis_resolution = app.SpinnerresolutionmsEditField.Value; %Set field value to property
            app.set_ROISpinner(); %change properties of ROI boundary spinners

            %Enable Panels
            app.RawPanel.Enable = app.menue_state(1);
            app.AnalysisPanel.Enable = app.menue_state(2);
            % app.SetROIsleftrightboundaryspinnerresolutionPanel.Position = [344,-119,352,107]; %Move setting panel out of visible area
            app.SetROIsleftrightboundaryspinnerresolutionPanel.Visible = "off";
            app.menue_enable(1);
        end

        % Button pushed function: Default01msButton
        function Default01msButtonPushed(app, event)
            %Reset ROI left/ right boundary spinner resolution to 0.1
            app.SpinnerresolutionmsEditField.Value = 0.1;
            app.OKButtonPushed(app);
        end

        % Menu selected function: SetholdingcommandMenu
        function SetholdingcommandMenuSelected(app, event)
            app.menue_state =[app.RawPanel.Enable, app.AnalysisPanel.Enable];
            app.menue_enable(0);
            %Allow user to set holding command level and command level unit
            %Disable Panels
            app.RawPanel.Enable = "off";
            app.AnalysisPanel.Enable = "off";
            % app.SetcommandlevelPanel.Position = [651,436,352,107]; %Move setting panel in visible area
            app.SetcommandlevelPanel.Visible = "on";
        end

        % Button pushed function: CancelButton_Level
        function CancelButton_LevelPushed(app, event)
            %Enable Panels
            app.RawPanel.Enable = app.menue_state(1);
            app.AnalysisPanel.Enable = app.menue_state(2);
            % app.SetcommandlevelPanel.Position = [20,-119,345,107]; %Move setting panel out of visible area
            app.SetcommandlevelPanel.Visible = "off";

            if app.holding_command_set == 0 %In case user hasn't added holding command level
                app.IncludecommandlevelButton.Value = 0; %Unset include command level in analysis button
            end
            app.menue_enable(1);
        end

        % Value changed function: IncludecommandlevelButton
        function IncludecommandlevelButtonValueChanged(app, event)
            app.new_changes()
            if app.holding_command_set == 0 %In case user hasn't added holding command level
                app.SetholdingcommandMenuSelected() %Open menue for user to add it
            end
        end

        % Button pushed function: OKButton_Level
        function OKButton_LevelPushed(app, event)
            app.new_changes()
            selected_recordings = app.RecordingListBox.ItemsData; %Fetch index of recordings
            holdingLevel = app.HoldinglevelEditField.Value;
            for i_recordings = 1:size(selected_recordings,2) %For every recording
                select_cache = sprintf('recording_%d', selected_recordings(i_recordings)); %String to fetch and save recordings data and parameter from struct
                commandLevel_cache = app.loaded_files.(select_cache).epoch.commandLevel; %Fetch commanLevel matrix with unset holding command level (=NaN)
                commandLevel_cache(isnan(commandLevel_cache)) = holdingLevel; %Replace NaN with holdingLevel
                app.loaded_files.(select_cache).epoch.commandLevel_complete = commandLevel_cache; %Save commanLevel matrix with set holding command level
                app.loaded_files.(select_cache).epoch.unit = app.LevelDropDown.Value; %Save command level unit
                %Update header info
                headerinfo_cache = app.loaded_files.(select_cache).headerinfo;
                headerinfo_cache(7) = string(sprintf('Holding command set to %s %s', num2str(holdingLevel), app.LevelDropDown.Value));
                app.loaded_files.(select_cache).headerinfo = headerinfo_cache;
                if i_recordings == app.RecordingDropDown.Value %Update header info text field if displayed recording is reached in loop
                    app.Raw_RecordingDataText.Value = headerinfo_cache;
                end
            end
            app.holding_command_set = 1; %Note that holding command level was set
            app.RawPanel.Enable = app.menue_state(1);
            app.AnalysisPanel.Enable = app.menue_state(2);
            app.SetcommandlevelPanel.Visible = "off";
            app.menue_enable(1);
        end

        % Menu selected function: NewfilesfolderMenu
        function NewfilesfolderMenuSelected(app, event)
            app.menue_enable(0);
            if ~(isempty(app.RecordingListBox.Items))
                proceed = app.Replace_data_warning();
                if proceed == 0
                    app.menue_enable(1);
                    return
                end
            end
            mode = 1; %Replace already loaded files
            dir_type = 1; %Load full folder
            save_var = [];
            app.load_files_type(mode, dir_type, save_var);
            app.NewfilesMenu.Text = 'Replace loaded files';
            app.NewfilesfolderMenu.Text = 'Replace loaded files';
            app.menue_enable(1);
        end

        % Menu selected function: AddfilesfolderMenu
        function AddfilesfolderMenuSelected(app, event)
            app.menue_enable(0);
            mode = 2;%Add to already loaded files
            dir_type = 1; %Load full folder
            save_var = [];
            app.load_files_type(mode, dir_type, save_var);
            app.menue_enable(1);
        end

        % Menu selected function: NewfilesMenu
        function NewfilesMenuSelected(app, event)
            app.menue_enable(0);
            if ~(isempty(app.RecordingListBox.Items))
                proceed = app.Replace_data_warning();
                if proceed == 0
                    app.menue_enable(1);
                    return
                end
            end
            mode = 1; %Replace already loaded files
            dir_type = 2; %Load selected files
            save_var = [];
            app.load_files_type(mode, dir_type, save_var);
            app.NewfilesMenu.Text = 'Replace loaded files';
            app.NewfilesfolderMenu.Text = 'Replace loaded files';
            app.menue_enable(1);
        end

        % Menu selected function: AddfilesMenu
        function AddfilesMenuSelected(app, event)
            app.menue_enable(0);
            mode = 2;%Add to already loaded files
            dir_type = 2; %Load selected files
            save_var = [];
            app.load_files_type(mode, dir_type, save_var);
            app.menue_enable(1);
        end

        % Menu selected function: SaveMenu
        function SaveMenuSelected(app, event)
            app.menue_enable(0);
            %Select export folder
            if isempty(app.save_load_path) %In case no file path was already selected
                userProfile = getenv('USERPROFILE'); %Fetch users default folder...
                myDocsFolder = sprintf('%s\\My Documents', userProfile); %...and suggest documents folder by default
                selpath = uigetdir(myDocsFolder,'Select save folder'); %Ask for directory
            else
                myDocsFolder = app.Export_Label.Text; %Fetch previously selected path as starting point for browsing
                selpath = uigetdir(myDocsFolder,'Select save folder'); %Ask for directory
            end
            figure(app.UIFigure) %Necessary to move app window back to foreground after use of 'uigetfile'
            if selpath == 0 %if no path was selected
                app.menue_enable(1);
                return
            end

            figure(app.UIFigure) %Necessary to move app window back to foreground after use of 'uigetfile'

            %Ask for filename
            prompt = {'Enter file name'};
            dlgtitle = 'Save as';
            dims = [1 35];
            definput  = {char(app.save_name)};
            answer = char(inputdlg(prompt,dlgtitle,dims,definput));
            if isempty(answer) %if no file name was added or cancel was selected
                app.menue_enable(1);
                return
            end
            answer = strrep(answer, ' ', '_');
            datename = datetime('now','Format','uuMMdd''_''HHmmss');
            filename = sprintf('%s_%s.mat', answer, datename);
            saveas = fullfile(selpath, filename);

            save_var = struct();

            save_var.RecordingListBox.Value = app.RecordingListBox.Value;
            save_var.RecordingListBox.Items = app.RecordingListBox.Items;
            save_var.RecordingListBox.ItemsData = app.RecordingListBox.ItemsData;
            save_var.loaded_files = app.loaded_files;
            save_var.HoldinglevelEditField.Value = app.HoldinglevelEditField.Value;
            save_var.holding_command_set = app.holding_command_set;

            save_var.OffButton.Value = app.OffButton.Value;
            save_var.EpisodeButton.Value = app.EpochButton.Value;
            save_var.CursorsButton.Value = app.CursorsButton.Value;
            save_var.LeftSpinner.Value = app.LeftSpinner.Value;
            save_var.RightSpinner.Value = app.RightSpinner.Value;
            save_var.EpisodeSpinner.Value = app.EpisodeSpinner.Value;

            save_var.analysis_settings.SelectedSweepsDropDown.Value = app.SelectedSweepsDropDown.Value;
            save_var.analysis_settings.Button_ROIBaseline.Value = app.Button_ROIBaseline.Value;
            save_var.analysis_settings.IncludecommandlevelButton.Value = app.IncludecommandlevelButton.Value;
            save_var.analysis_settings.SampleRateEditField.Value = app.SampleRateEditField.Value;
            save_var.analysis_settings.Analysis_SampleRateSpinner.Value = app.Analysis_SampleRateSpinner.Value;

            save_var.file_type_mode = app.file_type_mode;

            save_var = app.save_load_analysis_settings(save_var, 1);
            save(saveas, 'save_var');
            app.save_session_done = 1;

            app.menue_enable(1);
        end

        % Menu selected function: LoadMenu
        function LoadMenuSelected(app, event)
            app.menue_enable(0);

            if ~(isempty(app.RecordingListBox.Items))
                proceed = app.Replace_data_warning();
                if proceed == 0
                    app.menue_enable(1);
                    return
                end
            end

            [matfile,selpath] = uigetfile({'*.mat','All Files'},...
                'Select saved mat file', ...
                'MultiSelect', 'off');
            figure(app.UIFigure) %Necessary to move app window back to foreground after use of 'uigetfile'
            if selpath == 0 %In case no files were selected
                app.menue_enable(1);
                return
            end
            try %In case wrong mat file was selected
                cd (selpath)
                load(matfile, 'save_var');


                if isfield(save_var,'file_type_mode')
                    if save_var.file_type_mode == 1
                        type = 1;
                        app.FilemodeLabel.Text = "ABF mode";
                        app.FilemodeLabel.BackgroundColor = [0.39,0.83,0.07];
                        app.file_type_mode = 1;
                        app.abfButton_2.Value = 1;
                    elseif save_var.file_type_mode == 2
                        type = 2;
                        app.FilemodeLabel.Text = "Labchart txt mode";
                        app.FilemodeLabel.BackgroundColor = [0.93,0.69,0.13];
                        app.file_type_mode = 2;
                        app.LabcharttxtButton_2.Value = 1;
                    elseif save_var.file_type_mode == 3
                        type = 3;
                        app.FilemodeLabel.Text = "Eventer files mode";
                        app.FilemodeLabel.BackgroundColor = [0.30,0.75,0.93];
                        app.file_type_mode = 3;
                        app.EventerfilesButton_2.Value = 1;
                    else
                        error('')
                    end

                else %Compatibility mode for saved sessions <v6

                    if isfield(save_var.loaded_files,'recording_1')
                        if isfield(save_var.loaded_files.recording_1,'header')
                            type = 1;
                            app.FilemodeLabel.Text = "ABF mode";
                            app.FilemodeLabel.BackgroundColor = [0.39,0.83,0.07];
                        else
                            type = 2;
                            app.FilemodeLabel.Text = "Labchart txt mode";
                            app.FilemodeLabel.BackgroundColor = [0.93,0.69,0.13];
                        end

                        app.save_load_path = selpath;
                    else
                        error('')
                    end
                end
            catch
                msg = sprintf('%s could not be loaded.\nPlease check if matfile is a saved session.', matfile);
                title = 'Session could not be loaded';
                waitfor(msgbox(msg,title));
                app.menue_enable(1);
                return
            end

            try
                app.save_name = matfile(1:end-20); %Remove automatically added date and time from file name
            catch
                app.save_name = matfile; %In case file was renamed
            end

            if ~(type == app.file_type_mode)
                app.load_active = 1;
                app.OKButton_2Pushed();
                app.load_active = 0;
            end

            mode = 1; %Load files, overwrites already loaded data
            dir_type = 3; %Load from previous session
            app.load_files_type(mode, dir_type, save_var);
            app.NewfilesMenu.Text = 'Replace loaded files';
            app.NewfilesfolderMenu.Text = 'Replace loaded files';
            app.menue_enable(1);
            app.TabGroup2.Visible = 1;
        end

        % Value changed function: Analysis_RegressionDropDown_1, 
        % ...and 12 other components
        function SelectedSweepsDropDownValueChanged(app, event)
            app.new_changes()
        end

        % Value changed function: Marker1_SendvaluetoDropDown, 
        % ...and 7 other components
        function Marker1_SendvaluetoDropDownValueChanged(app, event)
            for i_MarkerSpinner = 1:8
                Marker_SendvaluetoDropDown = sprintf('Marker%d_SendvaluetoDropDown', i_MarkerSpinner);
                SendvaluetoDropDown = app.(Marker_SendvaluetoDropDown).Value;
                if ~(SendvaluetoDropDown == 0)
                    MarkerSpinner = sprintf('MarkerSpinner_%d', i_MarkerSpinner);
                    app.SendMarkerValues(app.(MarkerSpinner).Value, SendvaluetoDropDown);
                    app.(Marker_SendvaluetoDropDown).Value = 0;
                end
            end
        end

        % Value changed function: GeneralcommentsTextArea
        function GeneralcommentsTextAreaValueChanged(app, event)
            app.loaded_files.general_comment = app.GeneralcommentsTextArea.Value;
        end

        % Value changed function: RecordingspecificcommentsTextArea
        function RecordingspecificcommentsTextAreaValueChanged(app, event)
            select_cache = sprintf('recording_%d', app.RecordingDropDown.Value);
            app.loaded_files.(select_cache).comment = app.RecordingspecificcommentsTextArea.Value;
        end

        % Value changed function: Export_FormatDropDown
        function Export_FormatDropDownValueChanged(app, event)
            if app.Export_FormatDropDown.Value == 1 && app.analysis_sweep_mode == 1
                app.AdditionallyunifyresultsinsingleExceltableCheckBox.Visible = "on";
            else
                app.AdditionallyunifyresultsinsingleExceltableCheckBox.Visible = "off";
            end
        end

        % Callback function: ManualpdfButton, OpenManualpdfMenu
        function OpenManualpdfMenuSelected(app, event)
            %Adapted from: edit(fullfile(matlabroot, 'toolbox\matlab\general\private\openpdf.m'))

            % import matlab.internal.lang.capability.Capability;
            manual = app.manual; %#ok<*ADPROPLC>
            if ispc
                winopen(manual)
            elseif ismac
                matlab.system.internal.executeCommand(['open "' manual '" &']);
            else
                web(manual, '-browser');
            end
        end

        % Menu selected function: EmergencysaveMenu
        function EmergencysaveMenuSelected(app, event)
            if ~isempty(app.loaded_files)
                try
                    app.SaveMenuSelected()
                    msg = sprintf('Session succesfully saved.');
                    title = 'Emergency save';
                    waitfor(msgbox(msg,title));
                catch
                    app.SaveMenuSelected()
                    msg = sprintf('Emergency save failed.');
                    title = 'Emergency save';
                    waitfor(msgbox(msg,title));
                end
            else
                msg = sprintf('No recordings loaded.\nNo session saved.');
                title = 'Emergency save';
                waitfor(msgbox(msg,title));
            end
        end

        % Value changed function: RecordingListBox
        function RecordingListBoxValueChanged(app, event)
            app.RecordingListBox.Value = app.RecordingListBox_Value_BU;
        end

        % Clicked callback: RecordingListBox
        function RecordingListBoxClicked(app, event)
            selected_value = event.InteractionInformation.Item;
            if ~isempty(selected_value)
                app.RecordingListBox.Enable = "off";
                addStyle(app.RecordingListBox, app.baseStyle);
                addStyle(app.RecordingListBox, app.selectedStyle, "item", selected_value);
                app.RecordingDropDown.Value = selected_value;
                app.RecordingListBox.Value = app.RecordingListBox_Value_BU;
                app.RecordingDropDownValueChanged();
                app.RecordingListBox.Enable = "on";
            end
        end

        % Button pushed function: InvertsweepselectionButton
        function InvertsweepselectionButtonPushed(app, event)
            %Invert sweep selection for analysis
            alteration.PreviousValue = app.SweepsListBox.Value;
            inverted_values = ~ismember(app.SweepsListBox.ItemsData, app.SweepsListBox.Value);
            app.SweepsListBox.Value = app.SweepsListBox.ItemsData(inverted_values);
            app.sweep_index_highlight = 1;
            alteration.Value = app.SweepsListBox.Value;
            alteration.manual = 1;
            app.change_sweep(alteration) %Plot all sweeps and recalculate mean and sd sweeps
        end

        % Menu selected function: ChangefilemodeMenu
        function ChangefilemodeMenuSelected(app, event)
            app.menue_state =[app.RawPanel.Enable, app.AnalysisPanel.Enable];
            if app.file_type_mode == 1
                app.abfButton_2.Value = 1;
            elseif app.file_type_mode == 2
                app.LabcharttxtButton_2.Value = 1;
            else
                app.EventerfilesButton_2.Value = 1;
            end
            app.menue_enable(0);
            %Disable Panels
            app.RawPanel.Enable = "off";
            app.AnalysisPanel.Enable = "off";
            app.ChangefiletypemodePanel.Visible = "on";
        end

        % Value changed function: FileselectionButton, FullfolderButton
        function FileselectionButtonPushed(app, event)
            app.Panel_5.Enable = "off";
            if app.LabcharttxtButton.Value == 1 && ~(app.file_type_mode == 2)
                app.file_type_mode = 2;
                app.OKButton_2Pushed()
            elseif app.abfButton.Value == 1 && ~(app.file_type_mode == 1)
                app.file_type_mode = 1;
                app.OKButton_2Pushed()
            elseif app.EventerfilesButton.Value == 1 && ~(app.file_type_mode == 3)
                app.file_type_mode = 3;
                app.OKButton_2Pushed()
            end
            if app.FullfolderButton.Value == 1
                app.NewfilesfolderMenuSelected()
            elseif app.FileselectionButton.Value == 1
                app.NewfilesMenuSelected()
            end

            if isempty(app.RecordingListBox.Items)
                app.TabGroup2.Visible = "off";
                app.Panel_5.Enable = "on";
            else
                app.Panel_5.Visible = 0;
                % app.Panel_5.Position = [879,-357,457,221]; %out
                app.TabGroup2.Visible = 1;
                app.DataMenu.Visible = 1;
                app.OptionsMenu.Visible = 1;
                app.HelpMenu.Visible = 1;
            end
            app.FullfolderButton.Value = 0;
            app.FileselectionButton.Value = 0;
        end

        % Button pushed function: LoadsessionButton
        function LoadsessionButtonPushed(app, event)
            app.Panel_5.Enable = "off";
            app.LoadMenuSelected()
            if isempty(app.RecordingListBox.Items)
                app.Panel_5.Enable = "on";
            else
                app.Panel_5.Visible = 0;
                % app.Panel_5.Position = [879,-357,457,221]; %out
                app.TabGroup2.Visible = 1;
                app.DataMenu.Visible = 1;
                app.OptionsMenu.Visible = 1;
                app.HelpMenu.Visible = 1;
            end
        end

        % Selection changed function: ButtonGroup_2
        function ButtonGroup_2SelectionChanged(app, event)
            if app.abfButton.Value == 1
                app.FilemodeLabel.Text = "ABF mode";
                app.FilemodeLabel.BackgroundColor = [0.39,0.83,0.07];
                app.UnitEditField.Visible = "off";
                app.UnitLabel.Visible = "off";
                app.CSVConverterButton.Visible = "off";
                app.FileselectionButton.Visible = "on";
                app.abfButton_2.Value = 1;
            elseif app.LabcharttxtButton.Value == 1
                app.FilemodeLabel.Text = "Labchart txt mode";
                app.FilemodeLabel.BackgroundColor = [0.93,0.69,0.13];
                app.UnitEditField.Visible = "on";
                app.UnitLabel.Visible = "on";
                app.CSVConverterButton.Visible = "on";
                app.FileselectionButton.Visible = "on";
                app.LabcharttxtButton_2.Value = 1;
            elseif app.EventerfilesButton.Value == 1
                app.FilemodeLabel.Text = "Eventer files mode";
                app.FilemodeLabel.BackgroundColor = [0.30,0.75,0.93];
                app.UnitEditField.Visible = "off";
                app.UnitLabel.Visible = "off";
                app.CSVConverterButton.Visible = "off";
                app.FileselectionButton.Visible = "off";
                app.EventerfilesButton_2.Value = 1;
            end
        end

        % Button pushed function: ExcludesweepButton
        function ExcludesweepButtonPushed(app, event)
            if ~isempty(app.SweepsListBox.Value)
                alteration.PreviousValue = app.SweepsListBox.Value;
                app.SweepsListBox.Value(find(app.SweepsListBox.Value == app.SweepLabel.Value)) = [];
                alteration.Value = app.SweepsListBox.Value;
                alteration.manual = 1;
                app.change_sweep(alteration)
            end
        end

        % Button pushed function: RemoverecordingButton
        function RemoverecordingButtonPushed(app, event)
            app.menue_state =[app.RawPanel.Enable, app.AnalysisPanel.Enable];
            app.RawPanel.Enable = "off";
            app.AnalysisPanel.Enable = "off";
            app.menue_enable(0);
            save_session_cache = app.save_session_done;

            msg = sprintf('Do you want to remove the selected recording from session?');
            title = 'Remove recording';
            selection = uiconfirm(app.UIFigure,msg,title, ...
                'Options',{'Yes','Cancel'}, ...
                'DefaultOption',2,'CancelOption',2, "Icon","warning");
            if eq(selection, "Yes")
                app.AnalysisPanel.Enable = "off";
                loaded_files_new = struct();

                app.loaded_files.(app.selected_recording) = [];
                if numel(fieldnames(app.loaded_files)) < 4 %Reset app in case the only loaded recording should be removed
                    Reset(app)
                    app.Panel_5.Enable = "on";
                    app.Panel_5.Visible = 1;
                    app.TabGroup2.Visible = 0;
                    % app.Panel_5.Position = [570, 643,457,221]; %in
                    app.Panel_5.Visible = "on";
                else
                    loaded_recordings_cleaned = fieldnames(app.loaded_files); %Get internal recording names
                    %Remove selected recording from struct
                    loaded_recordings_cleaned(loaded_recordings_cleaned == "general_comment") = [];
                    loaded_recordings_cleaned(loaded_recordings_cleaned == "baseline_cor_failed") = [];
                    indx_remove = strcmp(loaded_recordings_cleaned, app.selected_recording);
                    loaded_recordings_cleaned(indx_remove) = [];
                    %Remove selected recording from ListBox
                    RecordingListBox_Items_cache = app.RecordingListBox.Items;
                    RecordingListBox_Items_cache(indx_remove) = [];
                    %Change the internal name of the still loaded data
                    for i_clean = 1: size(loaded_recordings_cleaned, 1)
                        recording_cache = sprintf('recording_%d', i_clean);
                        loaded_files_new.(recording_cache) = app.loaded_files.(loaded_recordings_cleaned{i_clean});
                    end

                    %Renew RecordingListBox, DropDownList and
                    %RecordingSpinner
                    RecordingListBox_Value_cache = app.RecordingListBox.Value;
                    RecordingListBox_Value_new = RecordingListBox_Value_cache(RecordingListBox_Value_cache < find(indx_remove));
                    RecordingListBox_Value_cache = RecordingListBox_Value_cache - 1;
                    RecordingListBox_Value_cache = RecordingListBox_Value_cache(RecordingListBox_Value_cache >= find(indx_remove));
                    RecordingListBox_Value_new = [RecordingListBox_Value_new, RecordingListBox_Value_cache];
                    app.RecordingListBox.Items = RecordingListBox_Items_cache;
                    ItemsListBox = 1:size(app.RecordingListBox.Items,2);
                    app.RecordingListBox.ItemsData = ItemsListBox;
                    addStyle(app.RecordingListBox, app.selectedStyle, "item", 1);
                    app.RecordingListBox.Value = RecordingListBox_Value_new;
                    app.RecordingListBox_Value_BU = app.RecordingListBox.Value;

                    if app.RecordingDropDown.Value == 1
                        RecordingDropDown_Value_cache = 1;
                    elseif app.RecordingDropDown.Value == size(app.RecordingDropDown.Items, 2)
                        RecordingDropDown_Value_cache = app.RecordingDropDown.Value - 1;
                    else
                        RecordingDropDown_Value_cache = app.RecordingDropDown.Value;
                    end

                    app.RecordingDropDown.ItemsData = app.RecordingListBox.ItemsData;
                    app.RecordingDropDown.Value = 1;
                    app.RecordingDropDown.Items = app.RecordingListBox.Items;
                    app.RecordingDropDown.Value = RecordingDropDown_Value_cache;
                    if app.RecordingDropDown.ItemsData(end)>1 %More than one recording was loaded
                        app.RecordingSpinner.Limits = [1, app.RecordingDropDown.ItemsData(end)];
                        app.RecordingSpinner.Value = RecordingDropDown_Value_cache;
                        app.RecordingSpinner.Enable = "on";
                    else %Fix spinner at value 1
                        app.RecordingSpinner.Limits = [0, app.RecordingDropDown.ItemsData(end)];
                        app.RecordingSpinner.Value = RecordingDropDown_Value_cache;
                        app.RecordingSpinner.Enable = "off";
                    end
                    app.selected_recording = sprintf('recording_%d', app.RecordingDropDown.Value);

                    %Renew loaded_files property
                    loaded_files_new.general_comment = app.loaded_files.general_comment;
                    loaded_files_new.baseline_cor_failed = app.loaded_files.baseline_cor_failed;
                    app.loaded_files = loaded_files_new;

                    app.RecordingDropDownValueChanged(); %Start setting the uifigure controls

                    app.menue_enable(1);
                    app.save_session_done = 0;
                    app.RawPanel.Enable = app.menue_state(1);
                end
            elseif eq(selection, "Cancel")
                app.menue_enable(1);
                app.save_session_done = save_session_cache;
                app.RawPanel.Enable = app.menue_state(1);
                app.AnalysisPanel.Enable = app.menue_state(2);

                return
            end
        end

        % Value changed function: SweepsListBox
        function SweepsListBoxValueChanged(app, event)
            %Handle interactions with SweepListBox
            if any(ismember(event.PreviousValue, event.Value)) && size(event.Value, 2) == 1
                app.SweepsListBox.Value = event.PreviousValue;
                app.sweep_index_highlight = find(app.SweepsListBox.Value == event.Value);
            elseif size(event.Value, 2) == (size(event.PreviousValue, 2) - 1)
                app.SweepsListBox.Value = event.PreviousValue;
                app.sweep_index_highlight = find(~ismember(event.PreviousValue, event.Value));
                % app.sweep_index_highlight = event.PreviousValue(~ismember(event.PreviousValue, event.Value));
            elseif size(event.Value, 2) == 1
                app.SweepsListBox.Value = sort([event.PreviousValue, event.Value]);
                app.sweep_index_highlight = find(app.SweepsListBox.Value == event.Value);
            else
                app.SweepsListBox.Value = sort(event.Value);
                app.sweep_index_highlight = find(~ismember(event.Value, event.PreviousValue));
                % app.sweep_index_highlight = event.Value(~ismember(event.Value, event.PreviousValue));
            end

            alteration.Value = app.SweepsListBox.Value;
            alteration.PreviousValue = event.PreviousValue;

            app.SweepSpinnerValueChanged(alteration);
            app.change_sweep(alteration);
        end

        % Menu selected function: SetsignalunitMenu
        function SetsignalunitMenuSelected(app, event)
            app.menue_state =[app.RawPanel.Enable, app.AnalysisPanel.Enable];
            app.menue_enable(0);
            %Allow user to set ROI left/ right boundary spinner resolution
            %Disable Panels
            app.RawPanel.Enable = "off";
            app.AnalysisPanel.Enable = "off";

            prompt = {'Set signal unit'};
            dlgtitle = 'Set signal unit';
            fieldsize = [1 45];
            definput = {char(app.UnitEditField.Value)};
            answer = inputdlg(prompt,dlgtitle,fieldsize,definput);
            figure(app.UIFigure) %Necessary to move app window back to foreground after use of 'inputdlg'
            if ~isempty(answer)
                answer = answer{1};
                if isempty(answer)
                    answer = 'Units';
                end
                app.UnitEditField.Value = answer;
                no_of_recordings = app.RecordingListBox.ItemsData(end);
                for i_recording = 1:no_of_recordings
                    recording_cache = sprintf('recording_%d', i_recording);
                    app.loaded_files.(recording_cache).unit = string(answer);
                end

                select_cache = sprintf('recording_%d', app.RecordingDropDown.Value);
                app.plot_selected(select_cache, 1) %plot
            end

            %Enable Panels
            app.RawPanel.Enable = app.menue_state(1);
            app.AnalysisPanel.Enable = app.menue_state(2);
            app.menue_enable(1);
        end

        % Callback function: CSVConverterButton, CSVConverterMenu
        function CSVConverterButtonPushed(app, event)
            CSV_Converter_Episodic_ABF_analysis
        end

        % Selection changed function: ButtonGroup_3
        function ButtonGroup_3SelectionChanged(app, event)
            current_mode = app.file_type_mode;
            if app.abfButton_2.Value == 1 && current_mode == 1
                app.OKButton_2.Enable = "off";
            elseif app.LabcharttxtButton_2.Value == 1 && current_mode == 2
                app.OKButton_2.Enable = "off";
            elseif app.EventerfilesButton_2.Value == 1 && current_mode == 3
                app.OKButton_2.Enable = "off";
            else
                app.OKButton_2.Enable = "on";
            end
        end

        % Button pushed function: CancelButton_2
        function CancelButton_2Pushed(app, event)
            %Enable Panels
            app.RawPanel.Enable = app.menue_state(1);
            app.AnalysisPanel.Enable = app.menue_state(2);
            app.ChangefiletypemodePanel.Visible = "off";
            app.menue_enable(1);
        end

        % Button pushed function: OKButton_2
        function OKButton_2Pushed(app, event)
            app.ChangefiletypemodePanel.Enable = "off";
            save_session_cache = app.save_session_done;

            if app.abfButton_2.Value == 1
                file_type_mode_cache = 1;
                changeto =  "ABF";
            elseif app.LabcharttxtButton_2.Value == 1
                file_type_mode_cache = 2;
                changeto =  "LabChart txt";
            elseif app.EventerfilesButton_2.Value == 1
                file_type_mode_cache = 3;
                changeto =  "Eventer file";
            end

            if app.load_active == 1 || isempty(app.RecordingListBox.Items) %Skip dialog during loading
                selection =  "Yes";
            else
                msg_on = 1;
                while msg_on == 1
                    msg = sprintf('Do you want to change to %s mode?\nThis will reset session.', changeto);
                    title = 'Change file mode';

                    if app.save_session_done == 0 && ~isempty(app.RecordingListBox.Items)
                        selection = uiconfirm(app.UIFigure,msg,title, ...
                            'Options',{'Yes', 'Save session and proceed', 'Cancel'}, ...
                            'DefaultOption',3,'CancelOption',3,...
                            "Icon","warning");
                    else
                        selection = uiconfirm(app.UIFigure,msg,title, ...
                            'Options',{'Yes', 'Cancel'}, ...
                            'DefaultOption',2,'CancelOption',2,...
                            "Icon","warning");
                    end

                    if eq(selection, "Save session and proceed")
                        save_state = app.save_session_done;
                        app.save_session_done = 0;
                        app.SaveMenuSelected()
                        if app.save_session_done == 0
                            app.save_session_done = save_state;
                        else
                            msg_on = 0;
                        end
                    elseif eq(selection, "Cancel")
                        app.ChangefiletypemodePanel.Enable = "on";
                        return
                    else
                        msg_on = 0;
                    end

                end


            end
            app.file_type_mode = file_type_mode_cache;
            if eq(selection, "Yes") || eq(selection, "Save session and proceed")
                app.Reset();
                if app.file_type_mode == 2
                    app.SetholdingcommandMenu.Visible =  "off";
                    app.xvaluePanel.Visible =  "off";
                    app.yvaluePanel.Visible =  "off";
                    app.LinestyleButtonGroup.Visible =  "off";
                    app.PlotButton.Visible =  "off";
                    app.Results_UIAxes.Visible =  "off";
                    app.IncludecommandlevelButton.Visible = "off";
                    app.IncludecommandlevelButton.Value = 0;
                    app.FilemodeLabel.Text = "Labchart txt mode";
                    app.FilemodeLabel.BackgroundColor = [0.93,0.69,0.13];
                    app.LabcharttxtButton.Value = 1;
                    app.SetsignalunitMenu.Visible = "on";
                    app.ImportrawfilesMenu.Enable = "on";
                elseif app.file_type_mode == 1
                    app.SetholdingcommandMenu.Visible =  "on";
                    app.xvaluePanel.Visible =  "on";
                    app.yvaluePanel.Visible =  "on";
                    app.LinestyleButtonGroup.Visible =  "on";
                    app.PlotButton.Visible =  "on";
                    app.Results_UIAxes.Visible =  "on";
                    app.IncludecommandlevelButton.Visible = "on";
                    app.FilemodeLabel.Text = "ABF mode";
                    app.FilemodeLabel.BackgroundColor = [0.39,0.83,0.07];
                    app.abfButton.Value = 1;
                    app.SetsignalunitMenu.Visible = "off";
                    app.ImportrawfilesMenu.Enable = "on";
                elseif app.file_type_mode == 3
                    app.SetholdingcommandMenu.Visible =  "off";
                    app.xvaluePanel.Visible =  "off";
                    app.yvaluePanel.Visible =  "off";
                    app.LinestyleButtonGroup.Visible =  "off";
                    app.PlotButton.Visible =  "off";
                    app.Results_UIAxes.Visible =  "off";
                    app.IncludecommandlevelButton.Visible = "off";
                    app.IncludecommandlevelButton.Value = 0;
                    app.FilemodeLabel.Text = "Eventer files mode";
                    app.FilemodeLabel.BackgroundColor = [0.30,0.75,0.93];
                    app.EventerfilesButton.Value = 1;
                    app.SetsignalunitMenu.Visible = "on";
                    app.ImportrawfilesMenu.Enable = "off";
                end
                app.TabGroup2.SelectedTab = app.RawTab;
            else
                app.save_session_done = save_session_cache;
                app.RawPanel.Enable = app.menue_state(1);
                app.AnalysisPanel.Enable = app.menue_state(2);
                app.menue_enable(1);
                return
            end
            % app.ChangefiletypemodePanel.Position = [-297,-158,256,107]; %Move setting panel out of visible area
            app.ChangefiletypemodePanel.Visible = "off";
            app.ChangefiletypemodePanel.Enable = "on";
            app.menue_enable(1);
        end

        % Callback function: AboutButton, AboutMenu
        function AboutMenuSelected(app, event)
            if app.Panel_5.Visible == 1 %Start window visible
                app.AboutPanel.Visible = "on";
            else
                app.menue_state =[app.RawPanel.Enable, app.AnalysisPanel.Enable];
                app.menue_enable(0);
                app.RawPanel.Enable = "off";
                app.AnalysisPanel.Enable = "off";
                app.AboutPanel.Visible = "on";
            end
        end

        % Button pushed function: CloseAboutButton
        function CloseAboutButtonPushed(app, event)
            if app.Panel_5.Visible == 1 %Start window visible
                app.AboutPanel.Visible = "off";
            else
                app.RawPanel.Enable = app.menue_state(1);
                app.AnalysisPanel.Enable = app.menue_state(2);
                app.AboutPanel.Visible = "off";
                app.menue_enable(1);
            end
        end
    end

    % Component initialization
    methods (Access = private)

        % Create UIFigure and components
        function createComponents(app)

            % Create UIFigure and hide until all components are created
            app.UIFigure = uifigure('Visible', 'off');
            app.UIFigure.Position = [100 100 1643 972];
            app.UIFigure.Name = 'MATLAB App';
            app.UIFigure.Resize = 'off';
            app.UIFigure.CloseRequestFcn = createCallbackFcn(app, @UIFigureCloseRequest, true);
            app.UIFigure.Scrollable = 'on';

            % Create DataMenu
            app.DataMenu = uimenu(app.UIFigure);
            app.DataMenu.Visible = 'off';
            app.DataMenu.Text = 'Data';

            % Create ImportrawfolderMenu
            app.ImportrawfolderMenu = uimenu(app.DataMenu);
            app.ImportrawfolderMenu.Text = 'Import raw (folder)';

            % Create NewfilesfolderMenu
            app.NewfilesfolderMenu = uimenu(app.ImportrawfolderMenu);
            app.NewfilesfolderMenu.MenuSelectedFcn = createCallbackFcn(app, @NewfilesfolderMenuSelected, true);
            app.NewfilesfolderMenu.Text = 'New files (folder)';
            app.NewfilesfolderMenu.BusyAction = 'cancel';

            % Create AddfilesfolderMenu
            app.AddfilesfolderMenu = uimenu(app.ImportrawfolderMenu);
            app.AddfilesfolderMenu.MenuSelectedFcn = createCallbackFcn(app, @AddfilesfolderMenuSelected, true);
            app.AddfilesfolderMenu.Enable = 'off';
            app.AddfilesfolderMenu.Text = 'Add files (folder)';
            app.AddfilesfolderMenu.BusyAction = 'cancel';

            % Create ImportrawfilesMenu
            app.ImportrawfilesMenu = uimenu(app.DataMenu);
            app.ImportrawfilesMenu.Text = 'Import raw (files)';

            % Create NewfilesMenu
            app.NewfilesMenu = uimenu(app.ImportrawfilesMenu);
            app.NewfilesMenu.MenuSelectedFcn = createCallbackFcn(app, @NewfilesMenuSelected, true);
            app.NewfilesMenu.Text = 'New files';
            app.NewfilesMenu.BusyAction = 'cancel';

            % Create AddfilesMenu
            app.AddfilesMenu = uimenu(app.ImportrawfilesMenu);
            app.AddfilesMenu.MenuSelectedFcn = createCallbackFcn(app, @AddfilesMenuSelected, true);
            app.AddfilesMenu.Enable = 'off';
            app.AddfilesMenu.Text = 'Add files';
            app.AddfilesMenu.BusyAction = 'cancel';

            % Create SaveMenu
            app.SaveMenu = uimenu(app.DataMenu);
            app.SaveMenu.MenuSelectedFcn = createCallbackFcn(app, @SaveMenuSelected, true);
            app.SaveMenu.Enable = 'off';
            app.SaveMenu.Text = 'Save';
            app.SaveMenu.BusyAction = 'cancel';

            % Create LoadMenu
            app.LoadMenu = uimenu(app.DataMenu);
            app.LoadMenu.MenuSelectedFcn = createCallbackFcn(app, @LoadMenuSelected, true);
            app.LoadMenu.Text = 'Load';
            app.LoadMenu.BusyAction = 'cancel';

            % Create ChangefilemodeMenu
            app.ChangefilemodeMenu = uimenu(app.DataMenu);
            app.ChangefilemodeMenu.MenuSelectedFcn = createCallbackFcn(app, @ChangefilemodeMenuSelected, true);
            app.ChangefilemodeMenu.Text = 'Change file mode';
            app.ChangefilemodeMenu.BusyAction = 'cancel';

            % Create CSVConverterMenu
            app.CSVConverterMenu = uimenu(app.DataMenu);
            app.CSVConverterMenu.MenuSelectedFcn = createCallbackFcn(app, @CSVConverterButtonPushed, true);
            app.CSVConverterMenu.Text = 'CSV Converter';

            % Create OptionsMenu
            app.OptionsMenu = uimenu(app.UIFigure);
            app.OptionsMenu.Visible = 'off';
            app.OptionsMenu.Text = 'Options';

            % Create ROIboundsspinnerresolutionMenu
            app.ROIboundsspinnerresolutionMenu = uimenu(app.OptionsMenu);
            app.ROIboundsspinnerresolutionMenu.MenuSelectedFcn = createCallbackFcn(app, @ROIboundsspinnerresolutionMenuSelected, true);
            app.ROIboundsspinnerresolutionMenu.Visible = 'off';
            app.ROIboundsspinnerresolutionMenu.Enable = 'off';
            app.ROIboundsspinnerresolutionMenu.Text = 'ROI bounds spinner resolution';
            app.ROIboundsspinnerresolutionMenu.BusyAction = 'cancel';

            % Create SetholdingcommandMenu
            app.SetholdingcommandMenu = uimenu(app.OptionsMenu);
            app.SetholdingcommandMenu.MenuSelectedFcn = createCallbackFcn(app, @SetholdingcommandMenuSelected, true);
            app.SetholdingcommandMenu.Text = 'Set holding command';
            app.SetholdingcommandMenu.BusyAction = 'cancel';

            % Create SetsignalunitMenu
            app.SetsignalunitMenu = uimenu(app.OptionsMenu);
            app.SetsignalunitMenu.MenuSelectedFcn = createCallbackFcn(app, @SetsignalunitMenuSelected, true);
            app.SetsignalunitMenu.Text = 'Set signal unit';

            % Create HelpMenu
            app.HelpMenu = uimenu(app.UIFigure);
            app.HelpMenu.Visible = 'off';
            app.HelpMenu.Text = 'Help';

            % Create OpenManualpdfMenu
            app.OpenManualpdfMenu = uimenu(app.HelpMenu);
            app.OpenManualpdfMenu.MenuSelectedFcn = createCallbackFcn(app, @OpenManualpdfMenuSelected, true);
            app.OpenManualpdfMenu.Text = 'Open Manual (pdf)';

            % Create AboutMenu
            app.AboutMenu = uimenu(app.HelpMenu);
            app.AboutMenu.MenuSelectedFcn = createCallbackFcn(app, @AboutMenuSelected, true);
            app.AboutMenu.Text = 'About';

            % Create EmergencysaveMenu
            app.EmergencysaveMenu = uimenu(app.HelpMenu);
            app.EmergencysaveMenu.MenuSelectedFcn = createCallbackFcn(app, @EmergencysaveMenuSelected, true);
            app.EmergencysaveMenu.Text = 'Emergency save';

            % Create TestStop
            app.TestStop = uimenu(app.UIFigure);
            app.TestStop.Visible = 'off';
            app.TestStop.Text = 'TestStop';

            % Create Debug
            app.Debug = uimenu(app.TestStop);
            app.Debug.MenuSelectedFcn = createCallbackFcn(app, @TestStopMenuSelected, true);
            app.Debug.Text = 'Debug';

            % Create TabGroup2
            app.TabGroup2 = uitabgroup(app.UIFigure);
            app.TabGroup2.Position = [1 -3 1643 976];

            % Create RawTab
            app.RawTab = uitab(app.TabGroup2);
            app.RawTab.Title = 'Raw';

            % Create RawPanel
            app.RawPanel = uipanel(app.RawTab);
            app.RawPanel.Enable = 'off';
            app.RawPanel.BorderType = 'none';
            app.RawPanel.BackgroundColor = [0.9412 0.9412 0.9412];
            app.RawPanel.Position = [3 1 1640 947];

            % Create RawUIAxes
            app.RawUIAxes = uiaxes(app.RawPanel);
            xlabel(app.RawUIAxes, 'Time (ms)')
            ylabel(app.RawUIAxes, 'Y')
            zlabel(app.RawUIAxes, 'Z')
            app.RawUIAxes.YLim = [-1 1];
            app.RawUIAxes.YGrid = 'on';
            app.RawUIAxes.ColorOrder = [0 0.4471 0.7412;0.851 0.3255 0.098;0.9294 0.6941 0.1255;0.4941 0.1843 0.5569;0.4667 0.6745 0.1882;0.302 0.749 0.9294;0.6353 0.0784 0.1843];
            app.RawUIAxes.Position = [544 532 867 401];

            % Create RecordingListBoxLabel
            app.RecordingListBoxLabel = uilabel(app.RawPanel);
            app.RecordingListBoxLabel.HorizontalAlignment = 'right';
            app.RecordingListBoxLabel.Position = [8 917 60 22];
            app.RecordingListBoxLabel.Text = 'Recording';

            % Create RecordingListBox
            app.RecordingListBox = uilistbox(app.RawPanel);
            app.RecordingListBox.Items = {};
            app.RecordingListBox.Multiselect = 'on';
            app.RecordingListBox.ValueChangedFcn = createCallbackFcn(app, @RecordingListBoxValueChanged, true);
            app.RecordingListBox.BusyAction = 'cancel';
            app.RecordingListBox.ClickedFcn = createCallbackFcn(app, @RecordingListBoxClicked, true);
            app.RecordingListBox.Position = [9 107 208 811];
            app.RecordingListBox.Value = {};

            % Create AnalysisoptionsPanel
            app.AnalysisoptionsPanel = uipanel(app.RawPanel);
            app.AnalysisoptionsPanel.Title = 'Analysis options';
            app.AnalysisoptionsPanel.Position = [671 11 820 310];

            % Create ROI1SpinnerLabel
            app.ROI1SpinnerLabel = uilabel(app.AnalysisoptionsPanel);
            app.ROI1SpinnerLabel.HorizontalAlignment = 'right';
            app.ROI1SpinnerLabel.Position = [47 182 37 22];
            app.ROI1SpinnerLabel.Text = 'ROI 1';

            % Create ROISpinnerLeft_1
            app.ROISpinnerLeft_1 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerLeft_1.Step = 0.1;
            app.ROISpinnerLeft_1.Limits = [0 Inf];
            app.ROISpinnerLeft_1.ValueDisplayFormat = '%.1f';
            app.ROISpinnerLeft_1.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerLeft_1ValueChanged, true);
            app.ROISpinnerLeft_1.BusyAction = 'cancel';
            app.ROISpinnerLeft_1.Position = [188 182 100 22];
            app.ROISpinnerLeft_1.Value = 0.1;

            % Create CheckBox_ROI_2
            app.CheckBox_ROI_2 = uicheckbox(app.AnalysisoptionsPanel);
            app.CheckBox_ROI_2.ValueChangedFcn = createCallbackFcn(app, @CheckBox_ROI2ValueChanged, true);
            app.CheckBox_ROI_2.BusyAction = 'cancel';
            app.CheckBox_ROI_2.Text = '';
            app.CheckBox_ROI_2.Position = [21 148 25 22];

            % Create CheckBox_ROI_3
            app.CheckBox_ROI_3 = uicheckbox(app.AnalysisoptionsPanel);
            app.CheckBox_ROI_3.ValueChangedFcn = createCallbackFcn(app, @CheckBox_ROI2ValueChanged, true);
            app.CheckBox_ROI_3.BusyAction = 'cancel';
            app.CheckBox_ROI_3.Text = '';
            app.CheckBox_ROI_3.Position = [21 115 25 22];

            % Create ROISpinnerRight_1
            app.ROISpinnerRight_1 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerRight_1.Step = 0.1;
            app.ROISpinnerRight_1.Limits = [0 Inf];
            app.ROISpinnerRight_1.ValueDisplayFormat = '%.1f';
            app.ROISpinnerRight_1.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerRight_1ValueChanged, true);
            app.ROISpinnerRight_1.BusyAction = 'cancel';
            app.ROISpinnerRight_1.Position = [293 182 100 22];
            app.ROISpinnerRight_1.Value = 0.2;

            % Create ROISpinnerRight_2
            app.ROISpinnerRight_2 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerRight_2.Step = 0.1;
            app.ROISpinnerRight_2.Limits = [0 Inf];
            app.ROISpinnerRight_2.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerRight_1ValueChanged, true);
            app.ROISpinnerRight_2.BusyAction = 'cancel';
            app.ROISpinnerRight_2.Enable = 'off';
            app.ROISpinnerRight_2.Position = [293 148 100 22];
            app.ROISpinnerRight_2.Value = 0.2;

            % Create ROI2Label
            app.ROI2Label = uilabel(app.AnalysisoptionsPanel);
            app.ROI2Label.HorizontalAlignment = 'right';
            app.ROI2Label.Position = [47 148 37 22];
            app.ROI2Label.Text = 'ROI 2';

            % Create ROISpinnerLeft_2
            app.ROISpinnerLeft_2 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerLeft_2.Step = 0.1;
            app.ROISpinnerLeft_2.Limits = [0 Inf];
            app.ROISpinnerLeft_2.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerLeft_1ValueChanged, true);
            app.ROISpinnerLeft_2.BusyAction = 'cancel';
            app.ROISpinnerLeft_2.Enable = 'off';
            app.ROISpinnerLeft_2.Position = [188 148 100 22];
            app.ROISpinnerLeft_2.Value = 0.1;

            % Create ROISpinnerRight_3
            app.ROISpinnerRight_3 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerRight_3.Step = 0.1;
            app.ROISpinnerRight_3.Limits = [0 Inf];
            app.ROISpinnerRight_3.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerRight_1ValueChanged, true);
            app.ROISpinnerRight_3.BusyAction = 'cancel';
            app.ROISpinnerRight_3.Enable = 'off';
            app.ROISpinnerRight_3.Position = [293 115 100 22];
            app.ROISpinnerRight_3.Value = 0.2;

            % Create ROI3Label
            app.ROI3Label = uilabel(app.AnalysisoptionsPanel);
            app.ROI3Label.HorizontalAlignment = 'right';
            app.ROI3Label.Position = [47 115 37 22];
            app.ROI3Label.Text = 'ROI 3';

            % Create ROISpinnerLeft_3
            app.ROISpinnerLeft_3 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerLeft_3.Step = 0.1;
            app.ROISpinnerLeft_3.Limits = [0 Inf];
            app.ROISpinnerLeft_3.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerLeft_1ValueChanged, true);
            app.ROISpinnerLeft_3.BusyAction = 'cancel';
            app.ROISpinnerLeft_3.Enable = 'off';
            app.ROISpinnerLeft_3.Position = [188 115 100 22];
            app.ROISpinnerLeft_3.Value = 0.1;

            % Create CheckBox_ROI_4
            app.CheckBox_ROI_4 = uicheckbox(app.AnalysisoptionsPanel);
            app.CheckBox_ROI_4.ValueChangedFcn = createCallbackFcn(app, @CheckBox_ROI2ValueChanged, true);
            app.CheckBox_ROI_4.BusyAction = 'cancel';
            app.CheckBox_ROI_4.Text = '';
            app.CheckBox_ROI_4.Position = [21 80 25 22];

            % Create ROISpinnerRight_4
            app.ROISpinnerRight_4 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerRight_4.Step = 0.1;
            app.ROISpinnerRight_4.Limits = [0 Inf];
            app.ROISpinnerRight_4.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerRight_1ValueChanged, true);
            app.ROISpinnerRight_4.BusyAction = 'cancel';
            app.ROISpinnerRight_4.Enable = 'off';
            app.ROISpinnerRight_4.Position = [293 80 100 22];
            app.ROISpinnerRight_4.Value = 0.2;

            % Create ROI4Label
            app.ROI4Label = uilabel(app.AnalysisoptionsPanel);
            app.ROI4Label.HorizontalAlignment = 'right';
            app.ROI4Label.Position = [47 80 37 22];
            app.ROI4Label.Text = 'ROI 4';

            % Create ROISpinnerLeft_4
            app.ROISpinnerLeft_4 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerLeft_4.Step = 0.1;
            app.ROISpinnerLeft_4.Limits = [0 Inf];
            app.ROISpinnerLeft_4.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerLeft_1ValueChanged, true);
            app.ROISpinnerLeft_4.BusyAction = 'cancel';
            app.ROISpinnerLeft_4.Enable = 'off';
            app.ROISpinnerLeft_4.Position = [188 80 100 22];
            app.ROISpinnerLeft_4.Value = 0.1;

            % Create ApplytoLabel
            app.ApplytoLabel = uilabel(app.AnalysisoptionsPanel);
            app.ApplytoLabel.Position = [4 258 49 22];
            app.ApplytoLabel.Text = 'Apply to';

            % Create SelectedSweepsDropDown
            app.SelectedSweepsDropDown = uidropdown(app.AnalysisoptionsPanel);
            app.SelectedSweepsDropDown.Items = {'Selected sweeps', 'Mean sweep'};
            app.SelectedSweepsDropDown.ItemsData = [1 2];
            app.SelectedSweepsDropDown.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.SelectedSweepsDropDown.BusyAction = 'cancel';
            app.SelectedSweepsDropDown.Position = [52 259 132 22];
            app.SelectedSweepsDropDown.Value = 2;

            % Create StartanalysisButton
            app.StartanalysisButton = uibutton(app.AnalysisoptionsPanel, 'push');
            app.StartanalysisButton.ButtonPushedFcn = createCallbackFcn(app, @StartanalysisButtonPushed, true);
            app.StartanalysisButton.BusyAction = 'cancel';
            app.StartanalysisButton.Position = [606 258 100 22];
            app.StartanalysisButton.Text = 'Start analysis';

            % Create AnalysisDropDown_1
            app.AnalysisDropDown_1 = uidropdown(app.AnalysisoptionsPanel);
            app.AnalysisDropDown_1.Items = {'Mean', 'Amplitude', 'Rise Slope', 'Decay Slope', 'AUC'};
            app.AnalysisDropDown_1.ItemsData = [1 2 3 4 5];
            app.AnalysisDropDown_1.ValueChangedFcn = createCallbackFcn(app, @AnalysisDropDown_1ValueChanged, true);
            app.AnalysisDropDown_1.BusyAction = 'cancel';
            app.AnalysisDropDown_1.Position = [405 182 100 22];
            app.AnalysisDropDown_1.Value = 1;

            % Create AnalysisDropDown_2
            app.AnalysisDropDown_2 = uidropdown(app.AnalysisoptionsPanel);
            app.AnalysisDropDown_2.Items = {'Mean', 'Amplitude', 'Rise Slope', 'Decay Slope', 'AUC'};
            app.AnalysisDropDown_2.ItemsData = [1 2 3 4 5];
            app.AnalysisDropDown_2.ValueChangedFcn = createCallbackFcn(app, @AnalysisDropDown_1ValueChanged, true);
            app.AnalysisDropDown_2.BusyAction = 'cancel';
            app.AnalysisDropDown_2.Enable = 'off';
            app.AnalysisDropDown_2.Position = [405 148 100 22];
            app.AnalysisDropDown_2.Value = 1;

            % Create AnalysisDropDown_3
            app.AnalysisDropDown_3 = uidropdown(app.AnalysisoptionsPanel);
            app.AnalysisDropDown_3.Items = {'Mean', 'Amplitude', 'Rise Slope', 'Decay Slope', 'AUC'};
            app.AnalysisDropDown_3.ItemsData = [1 2 3 4 5];
            app.AnalysisDropDown_3.ValueChangedFcn = createCallbackFcn(app, @AnalysisDropDown_1ValueChanged, true);
            app.AnalysisDropDown_3.BusyAction = 'cancel';
            app.AnalysisDropDown_3.Enable = 'off';
            app.AnalysisDropDown_3.Position = [405 115 100 22];
            app.AnalysisDropDown_3.Value = 1;

            % Create AnalysisDropDown_4
            app.AnalysisDropDown_4 = uidropdown(app.AnalysisoptionsPanel);
            app.AnalysisDropDown_4.Items = {'Mean', 'Amplitude', 'Rise Slope', 'Decay Slope', 'AUC'};
            app.AnalysisDropDown_4.ItemsData = [1 2 3 4 5];
            app.AnalysisDropDown_4.ValueChangedFcn = createCallbackFcn(app, @AnalysisDropDown_1ValueChanged, true);
            app.AnalysisDropDown_4.BusyAction = 'cancel';
            app.AnalysisDropDown_4.Enable = 'off';
            app.AnalysisDropDown_4.Position = [405 80 100 22];
            app.AnalysisDropDown_4.Value = 1;

            % Create PeakdirectionLabel
            app.PeakdirectionLabel = uilabel(app.AnalysisoptionsPanel);
            app.PeakdirectionLabel.Position = [509 201 82 22];
            app.PeakdirectionLabel.Text = 'Peak direction';

            % Create SlopeamplitudeLabel
            app.SlopeamplitudeLabel = uilabel(app.AnalysisoptionsPanel);
            app.SlopeamplitudeLabel.Position = [593 201 114 22];
            app.SlopeamplitudeLabel.Text = 'Slope (% amplitude)';

            % Create SlopeSpinner_Lower_1
            app.SlopeSpinner_Lower_1 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Lower_1.Limits = [0 99];
            app.SlopeSpinner_Lower_1.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Lower_1ValueChanged, true);
            app.SlopeSpinner_Lower_1.BusyAction = 'cancel';
            app.SlopeSpinner_Lower_1.Enable = 'off';
            app.SlopeSpinner_Lower_1.Position = [590 180 56 22];
            app.SlopeSpinner_Lower_1.Value = 20;

            % Create SlopeSpinner_Upper_1
            app.SlopeSpinner_Upper_1 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Upper_1.Limits = [1 100];
            app.SlopeSpinner_Upper_1.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Upper_1ValueChanged, true);
            app.SlopeSpinner_Upper_1.BusyAction = 'cancel';
            app.SlopeSpinner_Upper_1.Enable = 'off';
            app.SlopeSpinner_Upper_1.Position = [651 180 57 22];
            app.SlopeSpinner_Upper_1.Value = 80;

            % Create SlopeSpinner_Lower_2
            app.SlopeSpinner_Lower_2 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Lower_2.Limits = [0 99];
            app.SlopeSpinner_Lower_2.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Lower_1ValueChanged, true);
            app.SlopeSpinner_Lower_2.BusyAction = 'cancel';
            app.SlopeSpinner_Lower_2.Enable = 'off';
            app.SlopeSpinner_Lower_2.Position = [590 147 56 22];
            app.SlopeSpinner_Lower_2.Value = 20;

            % Create SlopeSpinner_Upper_2
            app.SlopeSpinner_Upper_2 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Upper_2.Limits = [1 100];
            app.SlopeSpinner_Upper_2.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Upper_1ValueChanged, true);
            app.SlopeSpinner_Upper_2.BusyAction = 'cancel';
            app.SlopeSpinner_Upper_2.Enable = 'off';
            app.SlopeSpinner_Upper_2.Position = [651 147 57 22];
            app.SlopeSpinner_Upper_2.Value = 80;

            % Create SlopeSpinner_Lower_3
            app.SlopeSpinner_Lower_3 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Lower_3.Limits = [0 99];
            app.SlopeSpinner_Lower_3.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Lower_1ValueChanged, true);
            app.SlopeSpinner_Lower_3.BusyAction = 'cancel';
            app.SlopeSpinner_Lower_3.Enable = 'off';
            app.SlopeSpinner_Lower_3.Position = [590 113 56 22];
            app.SlopeSpinner_Lower_3.Value = 20;

            % Create SlopeSpinner_Upper_3
            app.SlopeSpinner_Upper_3 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Upper_3.Limits = [1 100];
            app.SlopeSpinner_Upper_3.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Upper_1ValueChanged, true);
            app.SlopeSpinner_Upper_3.BusyAction = 'cancel';
            app.SlopeSpinner_Upper_3.Enable = 'off';
            app.SlopeSpinner_Upper_3.Position = [651 113 57 22];
            app.SlopeSpinner_Upper_3.Value = 80;

            % Create SlopeSpinner_Lower_4
            app.SlopeSpinner_Lower_4 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Lower_4.Limits = [0 99];
            app.SlopeSpinner_Lower_4.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Lower_1ValueChanged, true);
            app.SlopeSpinner_Lower_4.BusyAction = 'cancel';
            app.SlopeSpinner_Lower_4.Enable = 'off';
            app.SlopeSpinner_Lower_4.Position = [589 78 56 22];
            app.SlopeSpinner_Lower_4.Value = 20;

            % Create SlopeSpinner_Upper_4
            app.SlopeSpinner_Upper_4 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Upper_4.Limits = [1 100];
            app.SlopeSpinner_Upper_4.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Upper_1ValueChanged, true);
            app.SlopeSpinner_Upper_4.BusyAction = 'cancel';
            app.SlopeSpinner_Upper_4.Enable = 'off';
            app.SlopeSpinner_Upper_4.Position = [650 78 57 22];
            app.SlopeSpinner_Upper_4.Value = 80;

            % Create LeftboundaryLabel
            app.LeftboundaryLabel = uilabel(app.AnalysisoptionsPanel);
            app.LeftboundaryLabel.Position = [198 200 78 22];
            app.LeftboundaryLabel.Text = 'Left boundary';

            % Create RightboundaryLabel
            app.RightboundaryLabel = uilabel(app.AnalysisoptionsPanel);
            app.RightboundaryLabel.Position = [304 200 86 22];
            app.RightboundaryLabel.Text = 'Right boundary';

            % Create MethodLabel
            app.MethodLabel = uilabel(app.AnalysisoptionsPanel);
            app.MethodLabel.Position = [432 201 46 22];
            app.MethodLabel.Text = 'Method';

            % Create CheckBox_ROI_5
            app.CheckBox_ROI_5 = uicheckbox(app.AnalysisoptionsPanel);
            app.CheckBox_ROI_5.ValueChangedFcn = createCallbackFcn(app, @CheckBox_ROI2ValueChanged, true);
            app.CheckBox_ROI_5.BusyAction = 'cancel';
            app.CheckBox_ROI_5.Text = '';
            app.CheckBox_ROI_5.Position = [21 46 25 22];

            % Create ROISpinnerRight_5
            app.ROISpinnerRight_5 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerRight_5.Step = 0.1;
            app.ROISpinnerRight_5.Limits = [0 Inf];
            app.ROISpinnerRight_5.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerRight_1ValueChanged, true);
            app.ROISpinnerRight_5.BusyAction = 'cancel';
            app.ROISpinnerRight_5.Enable = 'off';
            app.ROISpinnerRight_5.Position = [293 46 100 22];
            app.ROISpinnerRight_5.Value = 0.2;

            % Create AnalysisDropDown_5
            app.AnalysisDropDown_5 = uidropdown(app.AnalysisoptionsPanel);
            app.AnalysisDropDown_5.Items = {'Mean', 'Amplitude', 'Rise Slope', 'Decay Slope', 'AUC'};
            app.AnalysisDropDown_5.ItemsData = [1 2 3 4 5];
            app.AnalysisDropDown_5.ValueChangedFcn = createCallbackFcn(app, @AnalysisDropDown_1ValueChanged, true);
            app.AnalysisDropDown_5.BusyAction = 'cancel';
            app.AnalysisDropDown_5.Enable = 'off';
            app.AnalysisDropDown_5.Position = [405 46 100 22];
            app.AnalysisDropDown_5.Value = 1;

            % Create SlopeSpinner_Lower_5
            app.SlopeSpinner_Lower_5 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Lower_5.Limits = [0 99];
            app.SlopeSpinner_Lower_5.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Lower_1ValueChanged, true);
            app.SlopeSpinner_Lower_5.BusyAction = 'cancel';
            app.SlopeSpinner_Lower_5.Enable = 'off';
            app.SlopeSpinner_Lower_5.Position = [589 44 56 22];
            app.SlopeSpinner_Lower_5.Value = 20;

            % Create SlopeSpinner_Upper_5
            app.SlopeSpinner_Upper_5 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Upper_5.Limits = [1 100];
            app.SlopeSpinner_Upper_5.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Upper_1ValueChanged, true);
            app.SlopeSpinner_Upper_5.BusyAction = 'cancel';
            app.SlopeSpinner_Upper_5.Enable = 'off';
            app.SlopeSpinner_Upper_5.Position = [650 44 57 22];
            app.SlopeSpinner_Upper_5.Value = 80;

            % Create ROI5Label
            app.ROI5Label = uilabel(app.AnalysisoptionsPanel);
            app.ROI5Label.HorizontalAlignment = 'right';
            app.ROI5Label.Position = [47 46 37 22];
            app.ROI5Label.Text = 'ROI 5';

            % Create ROISpinnerLeft_5
            app.ROISpinnerLeft_5 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerLeft_5.Step = 0.1;
            app.ROISpinnerLeft_5.Limits = [0 Inf];
            app.ROISpinnerLeft_5.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerLeft_1ValueChanged, true);
            app.ROISpinnerLeft_5.BusyAction = 'cancel';
            app.ROISpinnerLeft_5.Enable = 'off';
            app.ROISpinnerLeft_5.Position = [188 46 100 22];
            app.ROISpinnerLeft_5.Value = 0.1;

            % Create CheckBox_ROI_6
            app.CheckBox_ROI_6 = uicheckbox(app.AnalysisoptionsPanel);
            app.CheckBox_ROI_6.ValueChangedFcn = createCallbackFcn(app, @CheckBox_ROI2ValueChanged, true);
            app.CheckBox_ROI_6.BusyAction = 'cancel';
            app.CheckBox_ROI_6.Text = '';
            app.CheckBox_ROI_6.Position = [21 13 25 22];

            % Create ROISpinnerRight_6
            app.ROISpinnerRight_6 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerRight_6.Step = 0.1;
            app.ROISpinnerRight_6.Limits = [0 Inf];
            app.ROISpinnerRight_6.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerRight_1ValueChanged, true);
            app.ROISpinnerRight_6.BusyAction = 'cancel';
            app.ROISpinnerRight_6.Enable = 'off';
            app.ROISpinnerRight_6.Position = [293 13 100 22];
            app.ROISpinnerRight_6.Value = 0.2;

            % Create AnalysisDropDown_6
            app.AnalysisDropDown_6 = uidropdown(app.AnalysisoptionsPanel);
            app.AnalysisDropDown_6.Items = {'Mean', 'Amplitude', 'Rise Slope', 'Decay Slope', 'AUC'};
            app.AnalysisDropDown_6.ItemsData = [1 2 3 4 5];
            app.AnalysisDropDown_6.ValueChangedFcn = createCallbackFcn(app, @AnalysisDropDown_1ValueChanged, true);
            app.AnalysisDropDown_6.BusyAction = 'cancel';
            app.AnalysisDropDown_6.Enable = 'off';
            app.AnalysisDropDown_6.Position = [405 13 100 22];
            app.AnalysisDropDown_6.Value = 1;

            % Create SlopeSpinner_Lower_6
            app.SlopeSpinner_Lower_6 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Lower_6.Limits = [0 99];
            app.SlopeSpinner_Lower_6.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Lower_1ValueChanged, true);
            app.SlopeSpinner_Lower_6.BusyAction = 'cancel';
            app.SlopeSpinner_Lower_6.Enable = 'off';
            app.SlopeSpinner_Lower_6.Position = [589 11 56 22];
            app.SlopeSpinner_Lower_6.Value = 20;

            % Create SlopeSpinner_Upper_6
            app.SlopeSpinner_Upper_6 = uispinner(app.AnalysisoptionsPanel);
            app.SlopeSpinner_Upper_6.Limits = [1 100];
            app.SlopeSpinner_Upper_6.ValueChangedFcn = createCallbackFcn(app, @SlopeSpinner_Upper_1ValueChanged, true);
            app.SlopeSpinner_Upper_6.BusyAction = 'cancel';
            app.SlopeSpinner_Upper_6.Enable = 'off';
            app.SlopeSpinner_Upper_6.Position = [650 11 57 22];
            app.SlopeSpinner_Upper_6.Value = 80;

            % Create ROI6Label
            app.ROI6Label = uilabel(app.AnalysisoptionsPanel);
            app.ROI6Label.HorizontalAlignment = 'right';
            app.ROI6Label.Position = [47 13 37 22];
            app.ROI6Label.Text = 'ROI 6';

            % Create ROISpinnerLeft_6
            app.ROISpinnerLeft_6 = uispinner(app.AnalysisoptionsPanel);
            app.ROISpinnerLeft_6.Step = 0.1;
            app.ROISpinnerLeft_6.Limits = [0 Inf];
            app.ROISpinnerLeft_6.ValueChangedFcn = createCallbackFcn(app, @ROISpinnerLeft_1ValueChanged, true);
            app.ROISpinnerLeft_6.BusyAction = 'cancel';
            app.ROISpinnerLeft_6.Enable = 'off';
            app.ROISpinnerLeft_6.Position = [188 13 100 22];
            app.ROISpinnerLeft_6.Value = 0.1;

            % Create PeakDirDropDown_1
            app.PeakDirDropDown_1 = uidropdown(app.AnalysisoptionsPanel);
            app.PeakDirDropDown_1.Items = {'+', '-', 'auto', 'absolute'};
            app.PeakDirDropDown_1.ItemsData = [1 2 3 4];
            app.PeakDirDropDown_1.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.PeakDirDropDown_1.BusyAction = 'cancel';
            app.PeakDirDropDown_1.Enable = 'off';
            app.PeakDirDropDown_1.Position = [519 180 61 22];
            app.PeakDirDropDown_1.Value = 3;

            % Create PeakDirDropDown_2
            app.PeakDirDropDown_2 = uidropdown(app.AnalysisoptionsPanel);
            app.PeakDirDropDown_2.Items = {'+', '-', 'auto', 'absolute'};
            app.PeakDirDropDown_2.ItemsData = [1 2 3 4];
            app.PeakDirDropDown_2.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.PeakDirDropDown_2.BusyAction = 'cancel';
            app.PeakDirDropDown_2.Enable = 'off';
            app.PeakDirDropDown_2.Position = [519 147 61 22];
            app.PeakDirDropDown_2.Value = 3;

            % Create PeakDirDropDown_3
            app.PeakDirDropDown_3 = uidropdown(app.AnalysisoptionsPanel);
            app.PeakDirDropDown_3.Items = {'+', '-', 'auto', 'absolute'};
            app.PeakDirDropDown_3.ItemsData = [1 2 3 4];
            app.PeakDirDropDown_3.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.PeakDirDropDown_3.BusyAction = 'cancel';
            app.PeakDirDropDown_3.Enable = 'off';
            app.PeakDirDropDown_3.Position = [519 113 61 22];
            app.PeakDirDropDown_3.Value = 3;

            % Create PeakDirDropDown_4
            app.PeakDirDropDown_4 = uidropdown(app.AnalysisoptionsPanel);
            app.PeakDirDropDown_4.Items = {'+', '-', 'auto', 'absolute'};
            app.PeakDirDropDown_4.ItemsData = [1 2 3 4];
            app.PeakDirDropDown_4.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.PeakDirDropDown_4.BusyAction = 'cancel';
            app.PeakDirDropDown_4.Enable = 'off';
            app.PeakDirDropDown_4.Position = [519 78 61 22];
            app.PeakDirDropDown_4.Value = 3;

            % Create PeakDirDropDown_5
            app.PeakDirDropDown_5 = uidropdown(app.AnalysisoptionsPanel);
            app.PeakDirDropDown_5.Items = {'+', '-', 'auto', 'absolute'};
            app.PeakDirDropDown_5.ItemsData = [1 2 3 4];
            app.PeakDirDropDown_5.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.PeakDirDropDown_5.BusyAction = 'cancel';
            app.PeakDirDropDown_5.Enable = 'off';
            app.PeakDirDropDown_5.Position = [519 44 61 22];
            app.PeakDirDropDown_5.Value = 3;

            % Create PeakDirDropDown_6
            app.PeakDirDropDown_6 = uidropdown(app.AnalysisoptionsPanel);
            app.PeakDirDropDown_6.Items = {'+', '-', 'auto', 'absolute'};
            app.PeakDirDropDown_6.ItemsData = [1 2 3 4];
            app.PeakDirDropDown_6.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.PeakDirDropDown_6.BusyAction = 'cancel';
            app.PeakDirDropDown_6.Enable = 'off';
            app.PeakDirDropDown_6.Position = [519 11 61 22];
            app.PeakDirDropDown_6.Value = 4;

            % Create AnalysisAddtoresultsCheckBox
            app.AnalysisAddtoresultsCheckBox = uicheckbox(app.AnalysisoptionsPanel);
            app.AnalysisAddtoresultsCheckBox.Enable = 'off';
            app.AnalysisAddtoresultsCheckBox.Text = 'Add to results';
            app.AnalysisAddtoresultsCheckBox.Position = [609 235 95 22];

            % Create RelativetoDropDown_2
            app.RelativetoDropDown_2 = uidropdown(app.AnalysisoptionsPanel);
            app.RelativetoDropDown_2.Items = {'None', 'ROI 1'};
            app.RelativetoDropDown_2.ItemsData = [0 1];
            app.RelativetoDropDown_2.ValueChangedFcn = createCallbackFcn(app, @RelativetoDropDown_2ValueChanged, true);
            app.RelativetoDropDown_2.BusyAction = 'cancel';
            app.RelativetoDropDown_2.Enable = 'off';
            app.RelativetoDropDown_2.Position = [94 148 88 22];
            app.RelativetoDropDown_2.Value = 0;

            % Create RelativetoDropDown_3
            app.RelativetoDropDown_3 = uidropdown(app.AnalysisoptionsPanel);
            app.RelativetoDropDown_3.Items = {'None', 'ROI 1', 'ROI 2'};
            app.RelativetoDropDown_3.ItemsData = [0 1 2];
            app.RelativetoDropDown_3.ValueChangedFcn = createCallbackFcn(app, @RelativetoDropDown_2ValueChanged, true);
            app.RelativetoDropDown_3.BusyAction = 'cancel';
            app.RelativetoDropDown_3.Enable = 'off';
            app.RelativetoDropDown_3.Position = [94 115 88 22];
            app.RelativetoDropDown_3.Value = 0;

            % Create RelativetoDropDown_4
            app.RelativetoDropDown_4 = uidropdown(app.AnalysisoptionsPanel);
            app.RelativetoDropDown_4.Items = {'None', 'ROI 1', 'ROI 2', 'ROI 3'};
            app.RelativetoDropDown_4.ItemsData = [0 1 2 3];
            app.RelativetoDropDown_4.ValueChangedFcn = createCallbackFcn(app, @RelativetoDropDown_2ValueChanged, true);
            app.RelativetoDropDown_4.BusyAction = 'cancel';
            app.RelativetoDropDown_4.Enable = 'off';
            app.RelativetoDropDown_4.Position = [94 80 88 22];
            app.RelativetoDropDown_4.Value = 0;

            % Create RelativetoDropDown_5
            app.RelativetoDropDown_5 = uidropdown(app.AnalysisoptionsPanel);
            app.RelativetoDropDown_5.Items = {'None', 'ROI 1', 'ROI 2', 'ROI 3', 'ROI 4'};
            app.RelativetoDropDown_5.ItemsData = [0 1 2 3 4];
            app.RelativetoDropDown_5.ValueChangedFcn = createCallbackFcn(app, @RelativetoDropDown_2ValueChanged, true);
            app.RelativetoDropDown_5.BusyAction = 'cancel';
            app.RelativetoDropDown_5.Enable = 'off';
            app.RelativetoDropDown_5.Position = [94 46 88 22];
            app.RelativetoDropDown_5.Value = 0;

            % Create RelativetoDropDown_6
            app.RelativetoDropDown_6 = uidropdown(app.AnalysisoptionsPanel);
            app.RelativetoDropDown_6.Items = {'None', 'ROI 1', 'ROI 2', 'ROI 3', 'ROI 4', 'ROI 5'};
            app.RelativetoDropDown_6.ItemsData = [0 1 2 3 4 5];
            app.RelativetoDropDown_6.ValueChangedFcn = createCallbackFcn(app, @RelativetoDropDown_2ValueChanged, true);
            app.RelativetoDropDown_6.BusyAction = 'cancel';
            app.RelativetoDropDown_6.Enable = 'off';
            app.RelativetoDropDown_6.Position = [94 13 88 22];
            app.RelativetoDropDown_6.Value = 0;

            % Create ROIrelativtoresultofLabel
            app.ROIrelativtoresultofLabel = uilabel(app.AnalysisoptionsPanel);
            app.ROIrelativtoresultofLabel.HorizontalAlignment = 'center';
            app.ROIrelativtoresultofLabel.WordWrap = 'on';
            app.ROIrelativtoresultofLabel.Position = [104 197 69 29];
            app.ROIrelativtoresultofLabel.Text = 'ROI relativ to result of';

            % Create Analysis_AutoSwitchCheckBox
            app.Analysis_AutoSwitchCheckBox = uicheckbox(app.AnalysisoptionsPanel);
            app.Analysis_AutoSwitchCheckBox.BusyAction = 'cancel';
            app.Analysis_AutoSwitchCheckBox.Text = '';
            app.Analysis_AutoSwitchCheckBox.WordWrap = 'on';
            app.Analysis_AutoSwitchCheckBox.Position = [718 257 25 22];
            app.Analysis_AutoSwitchCheckBox.Value = true;

            % Create AutoswitchtoresulttabLabel
            app.AutoswitchtoresulttabLabel = uilabel(app.AnalysisoptionsPanel);
            app.AutoswitchtoresulttabLabel.HorizontalAlignment = 'center';
            app.AutoswitchtoresulttabLabel.WordWrap = 'on';
            app.AutoswitchtoresulttabLabel.Position = [736 252 77 32];
            app.AutoswitchtoresulttabLabel.Text = 'Auto switch to result tab';

            % Create RegressionLabel
            app.RegressionLabel = uilabel(app.AnalysisoptionsPanel);
            app.RegressionLabel.Position = [714 202 66 22];
            app.RegressionLabel.Text = 'Regression';

            % Create Analysis_RegressionDropDown_1
            app.Analysis_RegressionDropDown_1 = uidropdown(app.AnalysisoptionsPanel);
            app.Analysis_RegressionDropDown_1.Items = {'Linear', '1x exp', '2x exp', 'All'};
            app.Analysis_RegressionDropDown_1.ItemsData = [1 2 3 4];
            app.Analysis_RegressionDropDown_1.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.Analysis_RegressionDropDown_1.BusyAction = 'cancel';
            app.Analysis_RegressionDropDown_1.Enable = 'off';
            app.Analysis_RegressionDropDown_1.Position = [713 180 76 22];
            app.Analysis_RegressionDropDown_1.Value = 1;

            % Create Analysis_RegressionDropDown_2
            app.Analysis_RegressionDropDown_2 = uidropdown(app.AnalysisoptionsPanel);
            app.Analysis_RegressionDropDown_2.Items = {'Linear', '1x exp', '2x exp', 'All'};
            app.Analysis_RegressionDropDown_2.ItemsData = [1 2 3 4];
            app.Analysis_RegressionDropDown_2.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.Analysis_RegressionDropDown_2.BusyAction = 'cancel';
            app.Analysis_RegressionDropDown_2.Enable = 'off';
            app.Analysis_RegressionDropDown_2.Position = [713 146 76 22];
            app.Analysis_RegressionDropDown_2.Value = 1;

            % Create Analysis_RegressionDropDown_3
            app.Analysis_RegressionDropDown_3 = uidropdown(app.AnalysisoptionsPanel);
            app.Analysis_RegressionDropDown_3.Items = {'Linear', '1x exp', '2x exp', 'All'};
            app.Analysis_RegressionDropDown_3.ItemsData = [1 2 3 4];
            app.Analysis_RegressionDropDown_3.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.Analysis_RegressionDropDown_3.BusyAction = 'cancel';
            app.Analysis_RegressionDropDown_3.Enable = 'off';
            app.Analysis_RegressionDropDown_3.Position = [713 113 76 22];
            app.Analysis_RegressionDropDown_3.Value = 1;

            % Create Analysis_RegressionDropDown_4
            app.Analysis_RegressionDropDown_4 = uidropdown(app.AnalysisoptionsPanel);
            app.Analysis_RegressionDropDown_4.Items = {'Linear', '1x exp', '2x exp', 'All'};
            app.Analysis_RegressionDropDown_4.ItemsData = [1 2 3 4];
            app.Analysis_RegressionDropDown_4.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.Analysis_RegressionDropDown_4.BusyAction = 'cancel';
            app.Analysis_RegressionDropDown_4.Enable = 'off';
            app.Analysis_RegressionDropDown_4.Position = [713 78 76 22];
            app.Analysis_RegressionDropDown_4.Value = 1;

            % Create Analysis_RegressionDropDown_5
            app.Analysis_RegressionDropDown_5 = uidropdown(app.AnalysisoptionsPanel);
            app.Analysis_RegressionDropDown_5.Items = {'Linear', '1x exp', '2x exp', 'All'};
            app.Analysis_RegressionDropDown_5.ItemsData = [1 2 3 4];
            app.Analysis_RegressionDropDown_5.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.Analysis_RegressionDropDown_5.BusyAction = 'cancel';
            app.Analysis_RegressionDropDown_5.Enable = 'off';
            app.Analysis_RegressionDropDown_5.Position = [713 44 76 22];
            app.Analysis_RegressionDropDown_5.Value = 1;

            % Create Analysis_RegressionDropDown_6
            app.Analysis_RegressionDropDown_6 = uidropdown(app.AnalysisoptionsPanel);
            app.Analysis_RegressionDropDown_6.Items = {'Linear', '1x exp', '2x exp', 'All'};
            app.Analysis_RegressionDropDown_6.ItemsData = [1 2 3 4];
            app.Analysis_RegressionDropDown_6.ValueChangedFcn = createCallbackFcn(app, @SelectedSweepsDropDownValueChanged, true);
            app.Analysis_RegressionDropDown_6.BusyAction = 'cancel';
            app.Analysis_RegressionDropDown_6.Enable = 'off';
            app.Analysis_RegressionDropDown_6.Position = [713 11 76 22];
            app.Analysis_RegressionDropDown_6.Value = 1;

            % Create Panel_3
            app.Panel_3 = uipanel(app.AnalysisoptionsPanel);
            app.Panel_3.AutoResizeChildren = 'off';
            app.Panel_3.BorderType = 'none';
            app.Panel_3.Position = [406 249 188 40];

            % Create SampleRateEditField
            app.SampleRateEditField = uieditfield(app.Panel_3, 'numeric');
            app.SampleRateEditField.Limits = [0 Inf];
            app.SampleRateEditField.ValueChangedFcn = createCallbackFcn(app, @SampleRateEditFieldValueChanged, true);
            app.SampleRateEditField.BusyAction = 'cancel';
            app.SampleRateEditField.Editable = 'off';
            app.SampleRateEditField.Position = [122 9 45 22];
            app.SampleRateEditField.Value = 1;

            % Create Analysis_SampleRateSpinner
            app.Analysis_SampleRateSpinner = uispinner(app.Panel_3);
            app.Analysis_SampleRateSpinner.Limits = [-4 4];
            app.Analysis_SampleRateSpinner.ValueChangedFcn = createCallbackFcn(app, @SampleRateEditFieldValueChanged, true);
            app.Analysis_SampleRateSpinner.BusyAction = 'cancel';
            app.Analysis_SampleRateSpinner.Position = [166 9 24 22];

            % Create DigitallyaltersampleratebyfactorLabel
            app.DigitallyaltersampleratebyfactorLabel = uilabel(app.Panel_3);
            app.DigitallyaltersampleratebyfactorLabel.WordWrap = 'on';
            app.DigitallyaltersampleratebyfactorLabel.Position = [7 -8 111 55];
            app.DigitallyaltersampleratebyfactorLabel.Text = 'Digitally alter sample rate by factor';

            % Create Button_ROIBaseline
            app.Button_ROIBaseline = uibutton(app.AnalysisoptionsPanel, 'state');
            app.Button_ROIBaseline.ValueChangedFcn = createCallbackFcn(app, @CheckBox_ROI2ValueChanged, true);
            app.Button_ROIBaseline.BusyAction = 'cancel';
            app.Button_ROIBaseline.Text = 'Add baseline values to results';
            app.Button_ROIBaseline.WordWrap = 'on';
            app.Button_ROIBaseline.Position = [189 246 105 38];
            app.Button_ROIBaseline.Value = true;

            % Create IncludecommandlevelButton
            app.IncludecommandlevelButton = uibutton(app.AnalysisoptionsPanel, 'state');
            app.IncludecommandlevelButton.ValueChangedFcn = createCallbackFcn(app, @IncludecommandlevelButtonValueChanged, true);
            app.IncludecommandlevelButton.BusyAction = 'cancel';
            app.IncludecommandlevelButton.Text = 'Include command level';
            app.IncludecommandlevelButton.WordWrap = 'on';
            app.IncludecommandlevelButton.Position = [301 251 105 32];

            % Create BaselinecorrectionPanel
            app.BaselinecorrectionPanel = uipanel(app.RawPanel);
            app.BaselinecorrectionPanel.Title = 'Baseline correction';
            app.BaselinecorrectionPanel.Position = [504 12 163 515];

            % Create ButtonGroup
            app.ButtonGroup = uibuttongroup(app.BaselinecorrectionPanel);
            app.ButtonGroup.SelectionChangedFcn = createCallbackFcn(app, @LeftSpinnerValueChanged, true);
            app.ButtonGroup.BorderType = 'none';
            app.ButtonGroup.BusyAction = 'cancel';
            app.ButtonGroup.Position = [7 215 136 270];

            % Create OffButton
            app.OffButton = uitogglebutton(app.ButtonGroup);
            app.OffButton.BusyAction = 'cancel';
            app.OffButton.Text = 'Off';
            app.OffButton.Position = [11 237 100 22];

            % Create CursorsButton
            app.CursorsButton = uitogglebutton(app.ButtonGroup);
            app.CursorsButton.BusyAction = 'cancel';
            app.CursorsButton.Text = 'Cursors';
            app.CursorsButton.Position = [11 202 100 22];

            % Create EpochButton
            app.EpochButton = uitogglebutton(app.ButtonGroup);
            app.EpochButton.BusyAction = 'cancel';
            app.EpochButton.Text = 'Epoch';
            app.EpochButton.Position = [11 119 100 23];
            app.EpochButton.Value = true;

            % Create EpisodeSpinner
            app.EpisodeSpinner = uispinner(app.ButtonGroup);
            app.EpisodeSpinner.Limits = [0 Inf];
            app.EpisodeSpinner.ValueChangedFcn = createCallbackFcn(app, @LeftSpinnerValueChanged, true);
            app.EpisodeSpinner.BusyAction = 'cancel';
            app.EpisodeSpinner.Position = [27 94 61 22];

            % Create LeftSpinnerLabel
            app.LeftSpinnerLabel = uilabel(app.ButtonGroup);
            app.LeftSpinnerLabel.HorizontalAlignment = 'right';
            app.LeftSpinnerLabel.Enable = 'off';
            app.LeftSpinnerLabel.Position = [91 175 26 22];
            app.LeftSpinnerLabel.Text = 'Left';

            % Create LeftSpinner
            app.LeftSpinner = uispinner(app.ButtonGroup);
            app.LeftSpinner.ValueChangedFcn = createCallbackFcn(app, @LeftSpinnerValueChanged, true);
            app.LeftSpinner.BusyAction = 'cancel';
            app.LeftSpinner.Enable = 'off';
            app.LeftSpinner.Position = [13 175 79 22];

            % Create RightSpinnerLabel
            app.RightSpinnerLabel = uilabel(app.ButtonGroup);
            app.RightSpinnerLabel.HorizontalAlignment = 'right';
            app.RightSpinnerLabel.Enable = 'off';
            app.RightSpinnerLabel.Position = [86 151 34 22];
            app.RightSpinnerLabel.Text = 'Right';

            % Create RightSpinner
            app.RightSpinner = uispinner(app.ButtonGroup);
            app.RightSpinner.ValueChangedFcn = createCallbackFcn(app, @RightSpinnerValueChanged, true);
            app.RightSpinner.BusyAction = 'cancel';
            app.RightSpinner.Enable = 'off';
            app.RightSpinner.Position = [13 151 79 22];

            % Create FailedforTextAreaLabel
            app.FailedforTextAreaLabel = uilabel(app.ButtonGroup);
            app.FailedforTextAreaLabel.HorizontalAlignment = 'right';
            app.FailedforTextAreaLabel.Position = [8 61 59 22];
            app.FailedforTextAreaLabel.Text = 'Failed for:';

            % Create BaseCorFailedTextArea
            app.BaseCorFailedTextArea = uitextarea(app.ButtonGroup);
            app.BaseCorFailedTextArea.Editable = 'off';
            app.BaseCorFailedTextArea.WordWrap = 'off';
            app.BaseCorFailedTextArea.Position = [1 -201 151 261];

            % Create RecordingDataLabel
            app.RecordingDataLabel = uilabel(app.RawPanel);
            app.RecordingDataLabel.HorizontalAlignment = 'right';
            app.RecordingDataLabel.Position = [1415 917 89 22];
            app.RecordingDataLabel.Text = 'Recording Data';

            % Create Raw_RecordingDataText
            app.Raw_RecordingDataText = uitextarea(app.RawPanel);
            app.Raw_RecordingDataText.Editable = 'off';
            app.Raw_RecordingDataText.WordWrap = 'off';
            app.Raw_RecordingDataText.Position = [1419 565 211 351];

            % Create Panel_2
            app.Panel_2 = uipanel(app.RawPanel);
            app.Panel_2.AutoResizeChildren = 'off';
            app.Panel_2.Position = [229 553 303 362];

            % Create MarkerSpinner_4
            app.MarkerSpinner_4 = uispinner(app.Panel_2);
            app.MarkerSpinner_4.Step = 0.1;
            app.MarkerSpinner_4.Limits = [0 Inf];
            app.MarkerSpinner_4.ValueDisplayFormat = '%.1f';
            app.MarkerSpinner_4.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.MarkerSpinner_4.BusyAction = 'cancel';
            app.MarkerSpinner_4.Position = [80 128 105 22];

            % Create MarkerSpinner_3
            app.MarkerSpinner_3 = uispinner(app.Panel_2);
            app.MarkerSpinner_3.Step = 0.1;
            app.MarkerSpinner_3.Limits = [0 Inf];
            app.MarkerSpinner_3.ValueDisplayFormat = '%.1f';
            app.MarkerSpinner_3.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.MarkerSpinner_3.BusyAction = 'cancel';
            app.MarkerSpinner_3.Position = [80 157 105 22];

            % Create MarkerSpinner_2
            app.MarkerSpinner_2 = uispinner(app.Panel_2);
            app.MarkerSpinner_2.Step = 0.1;
            app.MarkerSpinner_2.Limits = [0 Inf];
            app.MarkerSpinner_2.ValueDisplayFormat = '%.1f';
            app.MarkerSpinner_2.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.MarkerSpinner_2.BusyAction = 'cancel';
            app.MarkerSpinner_2.Position = [80 186 105 22];

            % Create MarkerSpinner_1
            app.MarkerSpinner_1 = uispinner(app.Panel_2);
            app.MarkerSpinner_1.Step = 0.1;
            app.MarkerSpinner_1.Limits = [0 Inf];
            app.MarkerSpinner_1.ValueDisplayFormat = '%.1f';
            app.MarkerSpinner_1.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.MarkerSpinner_1.BusyAction = 'cancel';
            app.MarkerSpinner_1.Position = [80 217 105 22];

            % Create Marker4Button
            app.Marker4Button = uibutton(app.Panel_2, 'state');
            app.Marker4Button.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.Marker4Button.BusyAction = 'cancel';
            app.Marker4Button.Text = 'Marker 4';
            app.Marker4Button.FontColor = [0 1 1];
            app.Marker4Button.Position = [10 128 63 22];

            % Create Marker3Button
            app.Marker3Button = uibutton(app.Panel_2, 'state');
            app.Marker3Button.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.Marker3Button.BusyAction = 'cancel';
            app.Marker3Button.Text = 'Marker 3';
            app.Marker3Button.FontColor = [1 0 1];
            app.Marker3Button.Position = [10 157 63 22];

            % Create Marker2Button
            app.Marker2Button = uibutton(app.Panel_2, 'state');
            app.Marker2Button.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.Marker2Button.BusyAction = 'cancel';
            app.Marker2Button.Text = 'Marker 2';
            app.Marker2Button.FontColor = [0 1 0];
            app.Marker2Button.Position = [10 186 63 22];

            % Create Marker1Button
            app.Marker1Button = uibutton(app.Panel_2, 'state');
            app.Marker1Button.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.Marker1Button.BusyAction = 'cancel';
            app.Marker1Button.Text = 'Marker 1';
            app.Marker1Button.FontColor = [0 0 1];
            app.Marker1Button.Position = [10 217 63 22];

            % Create maxLabel
            app.maxLabel = uilabel(app.Panel_2);
            app.maxLabel.Position = [200 335 61 22];
            app.maxLabel.Text = 'max';

            % Create minLabel
            app.minLabel = uilabel(app.Panel_2);
            app.minLabel.Position = [34 335 53 22];
            app.minLabel.Text = 'min';

            % Create AutoxButton
            app.AutoxButton = uibutton(app.Panel_2, 'push');
            app.AutoxButton.ButtonPushedFcn = createCallbackFcn(app, @AutoxButtonPushed, true);
            app.AutoxButton.BusyAction = 'cancel';
            app.AutoxButton.Position = [114 282 62 22];
            app.AutoxButton.Text = 'Auto x';

            % Create AutoyButton
            app.AutoyButton = uibutton(app.Panel_2, 'push');
            app.AutoyButton.ButtonPushedFcn = createCallbackFcn(app, @AutoyButtonPushed, true);
            app.AutoyButton.BusyAction = 'cancel';
            app.AutoyButton.Position = [113 314 63 22];
            app.AutoyButton.Text = 'Auto y';

            % Create xMaxSpinner
            app.xMaxSpinner = uispinner(app.Panel_2);
            app.xMaxSpinner.Limits = [0 Inf];
            app.xMaxSpinner.ValueChangedFcn = createCallbackFcn(app, @xMaxSpinnerValueChanged, true);
            app.xMaxSpinner.Position = [183 282 102 22];

            % Create xMinSpinner
            app.xMinSpinner = uispinner(app.Panel_2);
            app.xMinSpinner.Limits = [0 Inf];
            app.xMinSpinner.ValueChangedFcn = createCallbackFcn(app, @xMinSpinnerValueChanged, true);
            app.xMinSpinner.Position = [8 282 102 22];

            % Create yMaxSpinner
            app.yMaxSpinner = uispinner(app.Panel_2);
            app.yMaxSpinner.Step = 0.05;
            app.yMaxSpinner.ValueDisplayFormat = '%.2f';
            app.yMaxSpinner.ValueChangedFcn = createCallbackFcn(app, @yMaxSpinnerValueChanged, true);
            app.yMaxSpinner.Position = [184 314 101 22];

            % Create yMinSpinner
            app.yMinSpinner = uispinner(app.Panel_2);
            app.yMinSpinner.Step = 0.05;
            app.yMinSpinner.ValueDisplayFormat = '%.2f';
            app.yMinSpinner.ValueChangedFcn = createCallbackFcn(app, @yMinSpinnerValueChanged, true);
            app.yMinSpinner.Position = [8 314 103 22];

            % Create LockmanuelselectionCheckBox
            app.LockmanuelselectionCheckBox = uicheckbox(app.Panel_2);
            app.LockmanuelselectionCheckBox.Text = 'Lock manuel selection';
            app.LockmanuelselectionCheckBox.Position = [13 253 141 22];

            % Create Marker1_SendvaluetoDropDown
            app.Marker1_SendvaluetoDropDown = uidropdown(app.Panel_2);
            app.Marker1_SendvaluetoDropDown.Items = {'Set as...', 'ROI 1 (Left boundary)', 'ROI 1 (Right boundary)', 'ROI 2 (Left boundary)', 'ROI 2 (Right boundary)', 'ROI 3 (Left boundary)', 'ROI 3 (Right boundary)', 'ROI 4 (Left boundary)', 'ROI 4 (Right boundary)', 'ROI 5 (Left boundary)', 'ROI 5 (Right boundary)', 'ROI 6 (Left boundary)', 'ROI 6 (Right boundary)'};
            app.Marker1_SendvaluetoDropDown.ItemsData = [0 11 12 21 22 31 32 41 42 51 52 61 61];
            app.Marker1_SendvaluetoDropDown.ValueChangedFcn = createCallbackFcn(app, @Marker1_SendvaluetoDropDownValueChanged, true);
            app.Marker1_SendvaluetoDropDown.Position = [193 217 100 22];
            app.Marker1_SendvaluetoDropDown.Value = 0;

            % Create Marker2_SendvaluetoDropDown
            app.Marker2_SendvaluetoDropDown = uidropdown(app.Panel_2);
            app.Marker2_SendvaluetoDropDown.Items = {'Set as...', 'ROI 1 (Left boundary)', 'ROI 1 (Right boundary)', 'ROI 2 (Left boundary)', 'ROI 2 (Right boundary)', 'ROI 3 (Left boundary)', 'ROI 3 (Right boundary)', 'ROI 4 (Left boundary)', 'ROI 4 (Right boundary)', 'ROI 5 (Left boundary)', 'ROI 5 (Right boundary)', 'ROI 6 (Left boundary)', 'ROI 6 (Right boundary)'};
            app.Marker2_SendvaluetoDropDown.ItemsData = [0 11 12 21 22 31 32 41 42 51 52 61 61];
            app.Marker2_SendvaluetoDropDown.ValueChangedFcn = createCallbackFcn(app, @Marker1_SendvaluetoDropDownValueChanged, true);
            app.Marker2_SendvaluetoDropDown.Position = [193 186 100 22];
            app.Marker2_SendvaluetoDropDown.Value = 0;

            % Create Marker3_SendvaluetoDropDown
            app.Marker3_SendvaluetoDropDown = uidropdown(app.Panel_2);
            app.Marker3_SendvaluetoDropDown.Items = {'Set as...', 'ROI 1 (Left boundary)', 'ROI 1 (Right boundary)', 'ROI 2 (Left boundary)', 'ROI 2 (Right boundary)', 'ROI 3 (Left boundary)', 'ROI 3 (Right boundary)', 'ROI 4 (Left boundary)', 'ROI 4 (Right boundary)', 'ROI 5 (Left boundary)', 'ROI 5 (Right boundary)', 'ROI 6 (Left boundary)', 'ROI 6 (Right boundary)'};
            app.Marker3_SendvaluetoDropDown.ItemsData = [0 11 12 21 22 31 32 41 42 51 52 61 61];
            app.Marker3_SendvaluetoDropDown.ValueChangedFcn = createCallbackFcn(app, @Marker1_SendvaluetoDropDownValueChanged, true);
            app.Marker3_SendvaluetoDropDown.Position = [193 157 100 22];
            app.Marker3_SendvaluetoDropDown.Value = 0;

            % Create Marker4_SendvaluetoDropDown
            app.Marker4_SendvaluetoDropDown = uidropdown(app.Panel_2);
            app.Marker4_SendvaluetoDropDown.Items = {'Set as...', 'ROI 1 (Left boundary)', 'ROI 1 (Right boundary)', 'ROI 2 (Left boundary)', 'ROI 2 (Right boundary)', 'ROI 3 (Left boundary)', 'ROI 3 (Right boundary)', 'ROI 4 (Left boundary)', 'ROI 4 (Right boundary)', 'ROI 5 (Left boundary)', 'ROI 5 (Right boundary)', 'ROI 6 (Left boundary)', 'ROI 6 (Right boundary)'};
            app.Marker4_SendvaluetoDropDown.ItemsData = [0 11 12 21 22 31 32 41 42 51 52 61 61];
            app.Marker4_SendvaluetoDropDown.ValueChangedFcn = createCallbackFcn(app, @Marker1_SendvaluetoDropDownValueChanged, true);
            app.Marker4_SendvaluetoDropDown.Position = [193 128 100 22];
            app.Marker4_SendvaluetoDropDown.Value = 0;

            % Create MarkerSpinner_5
            app.MarkerSpinner_5 = uispinner(app.Panel_2);
            app.MarkerSpinner_5.Step = 0.1;
            app.MarkerSpinner_5.Limits = [0 Inf];
            app.MarkerSpinner_5.ValueDisplayFormat = '%.1f';
            app.MarkerSpinner_5.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.MarkerSpinner_5.BusyAction = 'cancel';
            app.MarkerSpinner_5.Position = [80 98 105 22];

            % Create Marker5Button
            app.Marker5Button = uibutton(app.Panel_2, 'state');
            app.Marker5Button.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.Marker5Button.BusyAction = 'cancel';
            app.Marker5Button.Text = 'Marker 5';
            app.Marker5Button.FontColor = [0.2 0.451 0.102];
            app.Marker5Button.Position = [10 97 63 23];

            % Create Marker5_SendvaluetoDropDown
            app.Marker5_SendvaluetoDropDown = uidropdown(app.Panel_2);
            app.Marker5_SendvaluetoDropDown.Items = {'Set as...', 'ROI 1 (Left boundary)', 'ROI 1 (Right boundary)', 'ROI 2 (Left boundary)', 'ROI 2 (Right boundary)', 'ROI 3 (Left boundary)', 'ROI 3 (Right boundary)', 'ROI 4 (Left boundary)', 'ROI 4 (Right boundary)', 'ROI 5 (Left boundary)', 'ROI 5 (Right boundary)', 'ROI 6 (Left boundary)', 'ROI 6 (Right boundary)'};
            app.Marker5_SendvaluetoDropDown.ItemsData = [0 11 12 21 22 31 32 41 42 51 52 61 61];
            app.Marker5_SendvaluetoDropDown.ValueChangedFcn = createCallbackFcn(app, @Marker1_SendvaluetoDropDownValueChanged, true);
            app.Marker5_SendvaluetoDropDown.Position = [193 98 100 22];
            app.Marker5_SendvaluetoDropDown.Value = 0;

            % Create MarkerSpinner_6
            app.MarkerSpinner_6 = uispinner(app.Panel_2);
            app.MarkerSpinner_6.Step = 0.1;
            app.MarkerSpinner_6.Limits = [0 Inf];
            app.MarkerSpinner_6.ValueDisplayFormat = '%.1f';
            app.MarkerSpinner_6.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.MarkerSpinner_6.BusyAction = 'cancel';
            app.MarkerSpinner_6.Position = [80 68 105 22];

            % Create Marker6Button
            app.Marker6Button = uibutton(app.Panel_2, 'state');
            app.Marker6Button.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.Marker6Button.BusyAction = 'cancel';
            app.Marker6Button.Text = 'Marker 6';
            app.Marker6Button.FontColor = [1 0.502 0.2];
            app.Marker6Button.Position = [10 67 63 23];

            % Create Marker6_SendvaluetoDropDown
            app.Marker6_SendvaluetoDropDown = uidropdown(app.Panel_2);
            app.Marker6_SendvaluetoDropDown.Items = {'Set as...', 'ROI 1 (Left boundary)', 'ROI 1 (Right boundary)', 'ROI 2 (Left boundary)', 'ROI 2 (Right boundary)', 'ROI 3 (Left boundary)', 'ROI 3 (Right boundary)', 'ROI 4 (Left boundary)', 'ROI 4 (Right boundary)', 'ROI 5 (Left boundary)', 'ROI 5 (Right boundary)', 'ROI 6 (Left boundary)', 'ROI 6 (Right boundary)'};
            app.Marker6_SendvaluetoDropDown.ItemsData = [0 11 12 21 22 31 32 41 42 51 52 61 61];
            app.Marker6_SendvaluetoDropDown.ValueChangedFcn = createCallbackFcn(app, @Marker1_SendvaluetoDropDownValueChanged, true);
            app.Marker6_SendvaluetoDropDown.Position = [193 68 100 22];
            app.Marker6_SendvaluetoDropDown.Value = 0;

            % Create MarkerSpinner_7
            app.MarkerSpinner_7 = uispinner(app.Panel_2);
            app.MarkerSpinner_7.Step = 0.1;
            app.MarkerSpinner_7.Limits = [0 Inf];
            app.MarkerSpinner_7.ValueDisplayFormat = '%.1f';
            app.MarkerSpinner_7.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.MarkerSpinner_7.BusyAction = 'cancel';
            app.MarkerSpinner_7.Position = [80 39 105 22];

            % Create Marker7Button
            app.Marker7Button = uibutton(app.Panel_2, 'state');
            app.Marker7Button.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.Marker7Button.BusyAction = 'cancel';
            app.Marker7Button.Text = 'Marker 7';
            app.Marker7Button.FontColor = [0.3176 0.0235 0.502];
            app.Marker7Button.Position = [10 38 63 23];

            % Create Marker7_SendvaluetoDropDown
            app.Marker7_SendvaluetoDropDown = uidropdown(app.Panel_2);
            app.Marker7_SendvaluetoDropDown.Items = {'Set as...', 'ROI 1 (Left boundary)', 'ROI 1 (Right boundary)', 'ROI 2 (Left boundary)', 'ROI 2 (Right boundary)', 'ROI 3 (Left boundary)', 'ROI 3 (Right boundary)', 'ROI 4 (Left boundary)', 'ROI 4 (Right boundary)', 'ROI 5 (Left boundary)', 'ROI 5 (Right boundary)', 'ROI 6 (Left boundary)', 'ROI 6 (Right boundary)'};
            app.Marker7_SendvaluetoDropDown.ItemsData = [0 11 12 21 22 31 32 41 42 51 52 61 61];
            app.Marker7_SendvaluetoDropDown.ValueChangedFcn = createCallbackFcn(app, @Marker1_SendvaluetoDropDownValueChanged, true);
            app.Marker7_SendvaluetoDropDown.Position = [193 39 100 22];
            app.Marker7_SendvaluetoDropDown.Value = 0;

            % Create MarkerSpinner_8
            app.MarkerSpinner_8 = uispinner(app.Panel_2);
            app.MarkerSpinner_8.Step = 0.1;
            app.MarkerSpinner_8.Limits = [0 Inf];
            app.MarkerSpinner_8.ValueDisplayFormat = '%.1f';
            app.MarkerSpinner_8.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.MarkerSpinner_8.BusyAction = 'cancel';
            app.MarkerSpinner_8.Position = [80 9 105 22];

            % Create Marker8Button
            app.Marker8Button = uibutton(app.Panel_2, 'state');
            app.Marker8Button.ValueChangedFcn = createCallbackFcn(app, @Marker1ButtonValueChanged, true);
            app.Marker8Button.BusyAction = 'cancel';
            app.Marker8Button.Text = 'Marker 8';
            app.Marker8Button.FontColor = [0.9294 0.8314 0.0784];
            app.Marker8Button.Position = [10 8 63 23];

            % Create Marker8_SendvaluetoDropDown
            app.Marker8_SendvaluetoDropDown = uidropdown(app.Panel_2);
            app.Marker8_SendvaluetoDropDown.Items = {'Set as...', 'ROI 1 (Left boundary)', 'ROI 1 (Right boundary)', 'ROI 2 (Left boundary)', 'ROI 2 (Right boundary)', 'ROI 3 (Left boundary)', 'ROI 3 (Right boundary)', 'ROI 4 (Left boundary)', 'ROI 4 (Right boundary)', 'ROI 5 (Left boundary)', 'ROI 5 (Right boundary)', 'ROI 6 (Left boundary)', 'ROI 6 (Right boundary)'};
            app.Marker8_SendvaluetoDropDown.ItemsData = [0 11 12 21 22 31 32 41 42 51 52 61 61];
            app.Marker8_SendvaluetoDropDown.ValueChangedFcn = createCallbackFcn(app, @Marker1_SendvaluetoDropDownValueChanged, true);
            app.Marker8_SendvaluetoDropDown.Position = [193 9 100 22];
            app.Marker8_SendvaluetoDropDown.Value = 0;

            % Create SelectallrecordingsButton
            app.SelectallrecordingsButton = uibutton(app.RawPanel, 'push');
            app.SelectallrecordingsButton.ButtonPushedFcn = createCallbackFcn(app, @SelectallrecordingsButtonPushed, true);
            app.SelectallrecordingsButton.BusyAction = 'cancel';
            app.SelectallrecordingsButton.Position = [19 80 124 22];
            app.SelectallrecordingsButton.Text = 'Select all recordings';

            % Create UnselectallrecordingsButton
            app.UnselectallrecordingsButton = uibutton(app.RawPanel, 'push');
            app.UnselectallrecordingsButton.ButtonPushedFcn = createCallbackFcn(app, @UnselectallrecordingsButtonPushed, true);
            app.UnselectallrecordingsButton.BusyAction = 'cancel';
            app.UnselectallrecordingsButton.Position = [18 53 137 22];
            app.UnselectallrecordingsButton.Text = 'Unselect all recordings';

            % Create Panel_4
            app.Panel_4 = uipanel(app.RawPanel);
            app.Panel_4.AutoResizeChildren = 'off';
            app.Panel_4.BorderType = 'none';
            app.Panel_4.BackgroundColor = [0.9412 0.9412 0.9412];
            app.Panel_4.Position = [671 327 931 200];

            % Create RecordingDropDownLabel
            app.RecordingDropDownLabel = uilabel(app.Panel_4);
            app.RecordingDropDownLabel.BusyAction = 'cancel';
            app.RecordingDropDownLabel.HorizontalAlignment = 'right';
            app.RecordingDropDownLabel.Position = [7 149 60 22];
            app.RecordingDropDownLabel.Text = 'Recording';

            % Create RecordingDropDown
            app.RecordingDropDown = uidropdown(app.Panel_4);
            app.RecordingDropDown.ValueChangedFcn = createCallbackFcn(app, @RecordingDropDownValueChanged, true);
            app.RecordingDropDown.BusyAction = 'cancel';
            app.RecordingDropDown.Position = [82 149 160 22];

            % Create RecordingSpinner
            app.RecordingSpinner = uispinner(app.Panel_4);
            app.RecordingSpinner.ValueChangedFcn = createCallbackFcn(app, @RecordingSpinnerValueChanged, true);
            app.RecordingSpinner.BusyAction = 'cancel';
            app.RecordingSpinner.Position = [242 149 23 23];

            % Create HighlightsweepButton
            app.HighlightsweepButton = uibutton(app.Panel_4, 'state');
            app.HighlightsweepButton.ValueChangedFcn = createCallbackFcn(app, @SweepSpinnerValueChanged, true);
            app.HighlightsweepButton.BusyAction = 'cancel';
            app.HighlightsweepButton.Text = 'Highlight sweep';
            app.HighlightsweepButton.FontColor = [1 0 0];
            app.HighlightsweepButton.Position = [277 149 100 22];
            app.HighlightsweepButton.Value = true;

            % Create DisplayallButton
            app.DisplayallButton = uibutton(app.Panel_4, 'state');
            app.DisplayallButton.ValueChangedFcn = createCallbackFcn(app, @RecordingDropDownValueChanged, true);
            app.DisplayallButton.BusyAction = 'cancel';
            app.DisplayallButton.Text = 'Display all';
            app.DisplayallButton.Position = [83 116 100 22];
            app.DisplayallButton.Value = true;

            % Create DisplaySDButton
            app.DisplaySDButton = uibutton(app.Panel_4, 'state');
            app.DisplaySDButton.ValueChangedFcn = createCallbackFcn(app, @DisplaySDButtonValueChanged, true);
            app.DisplaySDButton.BusyAction = 'cancel';
            app.DisplaySDButton.Text = 'Display SD';
            app.DisplaySDButton.FontColor = [0.302 0.749 0.9294];
            app.DisplaySDButton.Position = [308 115 100 22];

            % Create DisplaymeanButton
            app.DisplaymeanButton = uibutton(app.Panel_4, 'state');
            app.DisplaymeanButton.ValueChangedFcn = createCallbackFcn(app, @DisplaymeanButtonValueChanged, true);
            app.DisplaymeanButton.BusyAction = 'cancel';
            app.DisplaymeanButton.Text = 'Display mean';
            app.DisplaymeanButton.FontColor = [1 0.4118 0.1608];
            app.DisplaymeanButton.Position = [201 115 100 22];

            % Create SweepSpinner
            app.SweepSpinner = uispinner(app.Panel_4);
            app.SweepSpinner.Limits = [0 Inf];
            app.SweepSpinner.ValueChangedFcn = createCallbackFcn(app, @SweepSpinnerValueChanged, true);
            app.SweepSpinner.BusyAction = 'cancel';
            app.SweepSpinner.Position = [421 149 28 22];

            % Create SelectrecordingforanalysisButton
            app.SelectrecordingforanalysisButton = uibutton(app.Panel_4, 'state');
            app.SelectrecordingforanalysisButton.ValueChangedFcn = createCallbackFcn(app, @SelectrecordingforanalysisButtonValueChanged, true);
            app.SelectrecordingforanalysisButton.BusyAction = 'cancel';
            app.SelectrecordingforanalysisButton.Text = 'Select recording for analysis';
            app.SelectrecordingforanalysisButton.Position = [84 77 181 22];

            % Create SweepsListBoxLabel
            app.SweepsListBoxLabel = uilabel(app.Panel_4);
            app.SweepsListBoxLabel.HorizontalAlignment = 'right';
            app.SweepsListBoxLabel.Position = [518 175 48 22];
            app.SweepsListBoxLabel.Text = 'Sweeps';

            % Create SweepsListBox
            app.SweepsListBox = uilistbox(app.Panel_4);
            app.SweepsListBox.Multiselect = 'on';
            app.SweepsListBox.ValueChangedFcn = createCallbackFcn(app, @SweepsListBoxValueChanged, true);
            app.SweepsListBox.BusyAction = 'cancel';
            app.SweepsListBox.Position = [513 50 100 126];
            app.SweepsListBox.Value = {'Item 1'};

            % Create SelectallsweepsButton
            app.SelectallsweepsButton = uibutton(app.Panel_4, 'push');
            app.SelectallsweepsButton.ButtonPushedFcn = createCallbackFcn(app, @SelectallsweepsButtonPushed, true);
            app.SelectallsweepsButton.BusyAction = 'cancel';
            app.SelectallsweepsButton.Position = [510 27 108 22];
            app.SelectallsweepsButton.Text = 'Select all sweeps';

            % Create RecordingspecificcommentsTextAreaLabel
            app.RecordingspecificcommentsTextAreaLabel = uilabel(app.Panel_4);
            app.RecordingspecificcommentsTextAreaLabel.HorizontalAlignment = 'right';
            app.RecordingspecificcommentsTextAreaLabel.Position = [641 164 162 22];
            app.RecordingspecificcommentsTextAreaLabel.Text = 'Recording specific comments';

            % Create RecordingspecificcommentsTextArea
            app.RecordingspecificcommentsTextArea = uitextarea(app.Panel_4);
            app.RecordingspecificcommentsTextArea.ValueChangedFcn = createCallbackFcn(app, @RecordingspecificcommentsTextAreaValueChanged, true);
            app.RecordingspecificcommentsTextArea.Position = [638 30 273 128];

            % Create InvertsweepselectionButton
            app.InvertsweepselectionButton = uibutton(app.Panel_4, 'push');
            app.InvertsweepselectionButton.ButtonPushedFcn = createCallbackFcn(app, @InvertsweepselectionButtonPushed, true);
            app.InvertsweepselectionButton.BusyAction = 'cancel';
            app.InvertsweepselectionButton.Position = [498 1 134 23];
            app.InvertsweepselectionButton.Text = 'Invert sweep selection';

            % Create SweepLabel
            app.SweepLabel = uieditfield(app.Panel_4, 'numeric');
            app.SweepLabel.Editable = 'off';
            app.SweepLabel.Position = [386 149 38 22];
            app.SweepLabel.Value = 1;

            % Create ExcludesweepButton
            app.ExcludesweepButton = uibutton(app.Panel_4, 'push');
            app.ExcludesweepButton.ButtonPushedFcn = createCallbackFcn(app, @ExcludesweepButtonPushed, true);
            app.ExcludesweepButton.BusyAction = 'cancel';
            app.ExcludesweepButton.WordWrap = 'on';
            app.ExcludesweepButton.Position = [452 143 54 35];
            app.ExcludesweepButton.Text = 'Exclude sweep';

            % Create RemoverecordingButton
            app.RemoverecordingButton = uibutton(app.Panel_4, 'push');
            app.RemoverecordingButton.ButtonPushedFcn = createCallbackFcn(app, @RemoverecordingButtonPushed, true);
            app.RemoverecordingButton.BusyAction = 'cancel';
            app.RemoverecordingButton.BackgroundColor = [1 0.502 0.502];
            app.RemoverecordingButton.FontWeight = 'bold';
            app.RemoverecordingButton.Position = [7 11 120 23];
            app.RemoverecordingButton.Text = 'Remove recording';

            % Create GeneralcommentsTextAreaLabel
            app.GeneralcommentsTextAreaLabel = uilabel(app.RawPanel);
            app.GeneralcommentsTextAreaLabel.HorizontalAlignment = 'right';
            app.GeneralcommentsTextAreaLabel.Position = [232 508 106 22];
            app.GeneralcommentsTextAreaLabel.Text = 'General comments';

            % Create GeneralcommentsTextArea
            app.GeneralcommentsTextArea = uitextarea(app.RawPanel);
            app.GeneralcommentsTextArea.ValueChangedFcn = createCallbackFcn(app, @GeneralcommentsTextAreaValueChanged, true);
            app.GeneralcommentsTextArea.Position = [229 274 246 228];

            % Create ResultsTab
            app.ResultsTab = uitab(app.TabGroup2);
            app.ResultsTab.Title = 'Results';

            % Create AnalysisPanel
            app.AnalysisPanel = uipanel(app.ResultsTab);
            app.AnalysisPanel.Enable = 'off';
            app.AnalysisPanel.BorderType = 'none';
            app.AnalysisPanel.Position = [2 1 1640 950];

            % Create Results_UIAxes
            app.Results_UIAxes = uiaxes(app.AnalysisPanel);
            xlabel(app.Results_UIAxes, 'X')
            ylabel(app.Results_UIAxes, 'Y')
            zlabel(app.Results_UIAxes, 'Z')
            app.Results_UIAxes.Position = [501 76 913 444];

            % Create Results_UITable2
            app.Results_UITable2 = uitable(app.AnalysisPanel);
            app.Results_UITable2.ColumnName = {'Column 1'; 'Column 2'; 'Column 3'; 'Column 4'};
            app.Results_UITable2.RowName = {};
            app.Results_UITable2.Position = [182 635 1230 276];

            % Create AnalysislogTextAreaLabel
            app.AnalysislogTextAreaLabel = uilabel(app.AnalysisPanel);
            app.AnalysislogTextAreaLabel.HorizontalAlignment = 'right';
            app.AnalysislogTextAreaLabel.Position = [1421 914 70 22];
            app.AnalysislogTextAreaLabel.Text = 'Analysis log';

            % Create Results_AnalysislogTextArea
            app.Results_AnalysislogTextArea = uitextarea(app.AnalysisPanel);
            app.Results_AnalysislogTextArea.Editable = 'off';
            app.Results_AnalysislogTextArea.WordWrap = 'off';
            app.Results_AnalysislogTextArea.Position = [1421 293 205 619];

            % Create RecordingListBox_2Label
            app.RecordingListBox_2Label = uilabel(app.AnalysisPanel);
            app.RecordingListBox_2Label.HorizontalAlignment = 'right';
            app.RecordingListBox_2Label.Position = [9 906 60 22];
            app.RecordingListBox_2Label.Text = 'Recording';

            % Create RecordingListBox_2
            app.RecordingListBox_2 = uilistbox(app.AnalysisPanel);
            app.RecordingListBox_2.ValueChangedFcn = createCallbackFcn(app, @RecordingListBox_2ValueChanged, true);
            app.RecordingListBox_2.Position = [14 663 156 241];

            % Create PlotButton
            app.PlotButton = uibutton(app.AnalysisPanel, 'push');
            app.PlotButton.ButtonPushedFcn = createCallbackFcn(app, @PlotButtonPushed, true);
            app.PlotButton.BusyAction = 'cancel';
            app.PlotButton.Position = [192 169 100 22];
            app.PlotButton.Text = 'Plot';

            % Create LinestyleButtonGroup
            app.LinestyleButtonGroup = uibuttongroup(app.AnalysisPanel);
            app.LinestyleButtonGroup.SelectionChangedFcn = createCallbackFcn(app, @PlotButtonPushed, true);
            app.LinestyleButtonGroup.Title = 'Line style';
            app.LinestyleButtonGroup.BusyAction = 'cancel';
            app.LinestyleButtonGroup.Position = [47 97 123 106];

            % Create LineButton
            app.LineButton = uitogglebutton(app.LinestyleButtonGroup);
            app.LineButton.BusyAction = 'cancel';
            app.LineButton.Text = 'Line';
            app.LineButton.Position = [11 53 100 22];
            app.LineButton.Value = true;

            % Create MarkerButton
            app.MarkerButton = uitogglebutton(app.LinestyleButtonGroup);
            app.MarkerButton.BusyAction = 'cancel';
            app.MarkerButton.Text = 'Marker';
            app.MarkerButton.Position = [11 32 100 22];

            % Create LineMarkerButton
            app.LineMarkerButton = uitogglebutton(app.LinestyleButtonGroup);
            app.LineMarkerButton.BusyAction = 'cancel';
            app.LineMarkerButton.Text = 'Line + Marker';
            app.LineMarkerButton.Position = [11 11 100 22];

            % Create xvaluePanel
            app.xvaluePanel = uipanel(app.AnalysisPanel);
            app.xvaluePanel.Title = 'x value';
            app.xvaluePanel.Position = [44 439 447 75];

            % Create ResultLabel_2
            app.ResultLabel_2 = uilabel(app.xvaluePanel);
            app.ResultLabel_2.BusyAction = 'cancel';
            app.ResultLabel_2.HorizontalAlignment = 'right';
            app.ResultLabel_2.Position = [32 31 40 22];
            app.ResultLabel_2.Text = 'Result';

            % Create Results_xaxisDropDown
            app.Results_xaxisDropDown = uidropdown(app.xvaluePanel);
            app.Results_xaxisDropDown.ValueChangedFcn = createCallbackFcn(app, @Results_xaxisDropDownValueChanged, true);
            app.Results_xaxisDropDown.BusyAction = 'cancel';
            app.Results_xaxisDropDown.Position = [32 9 191 22];

            % Create timescaleDropDownLabel
            app.timescaleDropDownLabel = uilabel(app.xvaluePanel);
            app.timescaleDropDownLabel.HorizontalAlignment = 'right';
            app.timescaleDropDownLabel.Enable = 'off';
            app.timescaleDropDownLabel.Position = [230 30 60 22];
            app.timescaleDropDownLabel.Text = 'time scale';

            % Create Results_timescaleDropDown
            app.Results_timescaleDropDown = uidropdown(app.xvaluePanel);
            app.Results_timescaleDropDown.Items = {'ms', 's', 'min'};
            app.Results_timescaleDropDown.ItemsData = [1 1000 60000];
            app.Results_timescaleDropDown.BusyAction = 'cancel';
            app.Results_timescaleDropDown.Enable = 'off';
            app.Results_timescaleDropDown.Position = [230 9 100 22];
            app.Results_timescaleDropDown.Value = 1;

            % Create XCorCheckBox
            app.XCorCheckBox = uicheckbox(app.xvaluePanel);
            app.XCorCheckBox.BusyAction = 'cancel';
            app.XCorCheckBox.Enable = 'off';
            app.XCorCheckBox.Text = '';
            app.XCorCheckBox.Position = [374 9 25 22];
            app.XCorCheckBox.Value = true;

            % Create mintime0Label
            app.mintime0Label = uilabel(app.xvaluePanel);
            app.mintime0Label.Enable = 'off';
            app.mintime0Label.Position = [349 30 76 22];
            app.mintime0Label.Text = 'min(time) = 0';

            % Create yvaluePanel
            app.yvaluePanel = uipanel(app.AnalysisPanel);
            app.yvaluePanel.Title = 'y value';
            app.yvaluePanel.Position = [45 211 446 220];

            % Create Results_yaxisDropDown_Met_2
            app.Results_yaxisDropDown_Met_2 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Met_2.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Met_2.Enable = 'off';
            app.Results_yaxisDropDown_Met_2.Position = [226 127 170 22];

            % Create Results_yaxisDropDown_Rec_2
            app.Results_yaxisDropDown_Rec_2 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Rec_2.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Rec_2.Enable = 'off';
            app.Results_yaxisDropDown_Rec_2.Position = [29 127 173 22];

            % Create Results_yaxisDropDown_Met_3
            app.Results_yaxisDropDown_Met_3 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Met_3.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Met_3.Enable = 'off';
            app.Results_yaxisDropDown_Met_3.Position = [226 101 170 22];

            % Create Results_yaxisDropDown_Rec_3
            app.Results_yaxisDropDown_Rec_3 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Rec_3.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Rec_3.Enable = 'off';
            app.Results_yaxisDropDown_Rec_3.Position = [29 101 173 22];

            % Create Results_yaxisDropDown_Met_4
            app.Results_yaxisDropDown_Met_4 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Met_4.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Met_4.Enable = 'off';
            app.Results_yaxisDropDown_Met_4.Position = [226 73 170 22];

            % Create Results_yaxisDropDown_Rec_4
            app.Results_yaxisDropDown_Rec_4 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Rec_4.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Rec_4.Enable = 'off';
            app.Results_yaxisDropDown_Rec_4.Position = [29 73 173 22];

            % Create Results_yaxisDropDown_Met_5
            app.Results_yaxisDropDown_Met_5 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Met_5.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Met_5.Enable = 'off';
            app.Results_yaxisDropDown_Met_5.Position = [226 42 170 22];

            % Create Results_yaxisDropDown_Rec_5
            app.Results_yaxisDropDown_Rec_5 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Rec_5.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Rec_5.Enable = 'off';
            app.Results_yaxisDropDown_Rec_5.Position = [29 42 173 22];

            % Create Results_yaxisDropDown_Met_6
            app.Results_yaxisDropDown_Met_6 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Met_6.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Met_6.Enable = 'off';
            app.Results_yaxisDropDown_Met_6.Position = [226 11 170 22];

            % Create Results_yaxisDropDown_Rec_6
            app.Results_yaxisDropDown_Rec_6 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Rec_6.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Rec_6.Enable = 'off';
            app.Results_yaxisDropDown_Rec_6.Position = [29 11 173 22];

            % Create Results_yaxisCheckBox_2
            app.Results_yaxisCheckBox_2 = uicheckbox(app.yvaluePanel);
            app.Results_yaxisCheckBox_2.ValueChangedFcn = createCallbackFcn(app, @Results_yaxisCheckBox_2ValueChanged, true);
            app.Results_yaxisCheckBox_2.BusyAction = 'cancel';
            app.Results_yaxisCheckBox_2.Text = '';
            app.Results_yaxisCheckBox_2.Position = [5 127 25 22];

            % Create Results_yaxisCheckBox_3
            app.Results_yaxisCheckBox_3 = uicheckbox(app.yvaluePanel);
            app.Results_yaxisCheckBox_3.ValueChangedFcn = createCallbackFcn(app, @Results_yaxisCheckBox_2ValueChanged, true);
            app.Results_yaxisCheckBox_3.BusyAction = 'cancel';
            app.Results_yaxisCheckBox_3.Text = '';
            app.Results_yaxisCheckBox_3.Position = [5 101 25 22];

            % Create Results_yaxisCheckBox_4
            app.Results_yaxisCheckBox_4 = uicheckbox(app.yvaluePanel);
            app.Results_yaxisCheckBox_4.ValueChangedFcn = createCallbackFcn(app, @Results_yaxisCheckBox_2ValueChanged, true);
            app.Results_yaxisCheckBox_4.BusyAction = 'cancel';
            app.Results_yaxisCheckBox_4.Text = '';
            app.Results_yaxisCheckBox_4.Position = [5 73 25 22];

            % Create Results_yaxisCheckBox_5
            app.Results_yaxisCheckBox_5 = uicheckbox(app.yvaluePanel);
            app.Results_yaxisCheckBox_5.ValueChangedFcn = createCallbackFcn(app, @Results_yaxisCheckBox_2ValueChanged, true);
            app.Results_yaxisCheckBox_5.BusyAction = 'cancel';
            app.Results_yaxisCheckBox_5.Text = '';
            app.Results_yaxisCheckBox_5.Position = [5 42 25 22];

            % Create Results_yaxisCheckBox_6
            app.Results_yaxisCheckBox_6 = uicheckbox(app.yvaluePanel);
            app.Results_yaxisCheckBox_6.ValueChangedFcn = createCallbackFcn(app, @Results_yaxisCheckBox_2ValueChanged, true);
            app.Results_yaxisCheckBox_6.BusyAction = 'cancel';
            app.Results_yaxisCheckBox_6.Text = '';
            app.Results_yaxisCheckBox_6.Position = [5 11 25 22];

            % Create Results_yaxisLamp_1
            app.Results_yaxisLamp_1 = uilamp(app.yvaluePanel);
            app.Results_yaxisLamp_1.Position = [411 154 20 20];
            app.Results_yaxisLamp_1.Color = [0 0 0];

            % Create Results_yaxisLamp_2
            app.Results_yaxisLamp_2 = uilamp(app.yvaluePanel);
            app.Results_yaxisLamp_2.Position = [411 127 20 20];
            app.Results_yaxisLamp_2.Color = [0.851 0.3255 0.098];

            % Create Results_yaxisLamp_3
            app.Results_yaxisLamp_3 = uilamp(app.yvaluePanel);
            app.Results_yaxisLamp_3.Position = [411 101 20 20];
            app.Results_yaxisLamp_3.Color = [0 0.4471 0.7412];

            % Create Results_yaxisLamp_4
            app.Results_yaxisLamp_4 = uilamp(app.yvaluePanel);
            app.Results_yaxisLamp_4.Position = [411 73 20 20];
            app.Results_yaxisLamp_4.Color = [0.4667 0.6745 0.1882];

            % Create Results_yaxisLamp_5
            app.Results_yaxisLamp_5 = uilamp(app.yvaluePanel);
            app.Results_yaxisLamp_5.Position = [411 42 20 20];
            app.Results_yaxisLamp_5.Color = [0.7176 0.2745 1];

            % Create Results_yaxisLamp_6
            app.Results_yaxisLamp_6 = uilamp(app.yvaluePanel);
            app.Results_yaxisLamp_6.Position = [411 11 20 20];
            app.Results_yaxisLamp_6.Color = [0.851 0.6588 0.0353];

            % Create RecordingLabel
            app.RecordingLabel = uilabel(app.yvaluePanel);
            app.RecordingLabel.BusyAction = 'cancel';
            app.RecordingLabel.HorizontalAlignment = 'right';
            app.RecordingLabel.Position = [29 175 60 22];
            app.RecordingLabel.Text = 'Recording';

            % Create Results_yaxisDropDown_Rec_1
            app.Results_yaxisDropDown_Rec_1 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Rec_1.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Rec_1.Position = [29 154 173 22];

            % Create ResultLabel
            app.ResultLabel = uilabel(app.yvaluePanel);
            app.ResultLabel.HorizontalAlignment = 'right';
            app.ResultLabel.Position = [227 174 40 22];
            app.ResultLabel.Text = 'Result';

            % Create Results_yaxisDropDown_Met_1
            app.Results_yaxisDropDown_Met_1 = uidropdown(app.yvaluePanel);
            app.Results_yaxisDropDown_Met_1.BusyAction = 'cancel';
            app.Results_yaxisDropDown_Met_1.Position = [226 154 170 22];

            % Create ExportresultsPanel
            app.ExportresultsPanel = uipanel(app.AnalysisPanel);
            app.ExportresultsPanel.AutoResizeChildren = 'off';
            app.ExportresultsPanel.Title = 'Export results';
            app.ExportresultsPanel.Position = [182 537 1229 90];

            % Create Export_FormatDropDown
            app.Export_FormatDropDown = uidropdown(app.ExportresultsPanel);
            app.Export_FormatDropDown.Items = {'tsv (txt)', 'Excel file (xlsx)'};
            app.Export_FormatDropDown.ItemsData = [1 2];
            app.Export_FormatDropDown.ValueChangedFcn = createCallbackFcn(app, @Export_FormatDropDownValueChanged, true);
            app.Export_FormatDropDown.BusyAction = 'cancel';
            app.Export_FormatDropDown.Position = [4 34 100 22];
            app.Export_FormatDropDown.Value = 1;

            % Create Export_Label
            app.Export_Label = uilabel(app.ExportresultsPanel);
            app.Export_Label.BackgroundColor = [1 1 1];
            app.Export_Label.Position = [220 34 439 22];
            app.Export_Label.Text = '';

            % Create Export_SetsavepathButton
            app.Export_SetsavepathButton = uibutton(app.ExportresultsPanel, 'push');
            app.Export_SetsavepathButton.ButtonPushedFcn = createCallbackFcn(app, @Export_SetsavepathButtonPushed, true);
            app.Export_SetsavepathButton.BusyAction = 'cancel';
            app.Export_SetsavepathButton.Position = [114 34 100 22];
            app.Export_SetsavepathButton.Text = 'Set save path';

            % Create Export_meansweepwithSDCheckBox
            app.Export_meansweepwithSDCheckBox = uicheckbox(app.ExportresultsPanel);
            app.Export_meansweepwithSDCheckBox.BusyAction = 'cancel';
            app.Export_meansweepwithSDCheckBox.Text = 'Export mean sweep with SD';
            app.Export_meansweepwithSDCheckBox.Position = [943 34 173 22];

            % Create Export_resultsButton
            app.Export_resultsButton = uibutton(app.ExportresultsPanel, 'push');
            app.Export_resultsButton.ButtonPushedFcn = createCallbackFcn(app, @Export_resultsButtonPushed, true);
            app.Export_resultsButton.BusyAction = 'cancel';
            app.Export_resultsButton.Position = [1121 34 100 22];
            app.Export_resultsButton.Text = 'Export Results';

            % Create AddpostfixLabel
            app.AddpostfixLabel = uilabel(app.ExportresultsPanel);
            app.AddpostfixLabel.HorizontalAlignment = 'right';
            app.AddpostfixLabel.Position = [662 34 64 22];
            app.AddpostfixLabel.Text = 'Add postfix';

            % Create AddpostfixEditField
            app.AddpostfixEditField = uieditfield(app.ExportresultsPanel, 'text');
            app.AddpostfixEditField.InputType = 'alphanumerics';
            app.AddpostfixEditField.Position = [730 34 197 22];

            % Create AdditionallyunifyresultsinsingleExceltableCheckBox
            app.AdditionallyunifyresultsinsingleExceltableCheckBox = uicheckbox(app.ExportresultsPanel);
            app.AdditionallyunifyresultsinsingleExceltableCheckBox.BusyAction = 'cancel';
            app.AdditionallyunifyresultsinsingleExceltableCheckBox.Text = 'Additionally unify results in single Excel table';
            app.AdditionallyunifyresultsinsingleExceltableCheckBox.Position = [7 7 263 22];
            app.AdditionallyunifyresultsinsingleExceltableCheckBox.Value = true;

            % Create SetROIsleftrightboundaryspinnerresolutionPanel
            app.SetROIsleftrightboundaryspinnerresolutionPanel = uipanel(app.UIFigure);
            app.SetROIsleftrightboundaryspinnerresolutionPanel.AutoResizeChildren = 'off';
            app.SetROIsleftrightboundaryspinnerresolutionPanel.Title = 'Set ROIs left/ right boundary spinner resolution';
            app.SetROIsleftrightboundaryspinnerresolutionPanel.BackgroundColor = [0.3294 0.7294 0.8784];
            app.SetROIsleftrightboundaryspinnerresolutionPanel.Position = [393 -158 352 107];

            % Create SpinnerresolutionmsEditFieldLabel
            app.SpinnerresolutionmsEditFieldLabel = uilabel(app.SetROIsleftrightboundaryspinnerresolutionPanel);
            app.SpinnerresolutionmsEditFieldLabel.HorizontalAlignment = 'right';
            app.SpinnerresolutionmsEditFieldLabel.Position = [49 52 130 22];
            app.SpinnerresolutionmsEditFieldLabel.Text = 'Spinner resolution (ms)';

            % Create SpinnerresolutionmsEditField
            app.SpinnerresolutionmsEditField = uieditfield(app.SetROIsleftrightboundaryspinnerresolutionPanel, 'numeric');
            app.SpinnerresolutionmsEditField.Limits = [1e-15 Inf];
            app.SpinnerresolutionmsEditField.BusyAction = 'cancel';
            app.SpinnerresolutionmsEditField.Position = [194 52 100 22];
            app.SpinnerresolutionmsEditField.Value = 0.1;

            % Create OKButton
            app.OKButton = uibutton(app.SetROIsleftrightboundaryspinnerresolutionPanel, 'push');
            app.OKButton.ButtonPushedFcn = createCallbackFcn(app, @OKButtonPushed, true);
            app.OKButton.BusyAction = 'cancel';
            app.OKButton.Position = [23 17 81 22];
            app.OKButton.Text = 'OK';

            % Create Default01msButton
            app.Default01msButton = uibutton(app.SetROIsleftrightboundaryspinnerresolutionPanel, 'push');
            app.Default01msButton.ButtonPushedFcn = createCallbackFcn(app, @Default01msButtonPushed, true);
            app.Default01msButton.BusyAction = 'cancel';
            app.Default01msButton.Position = [116 17 101 22];
            app.Default01msButton.Text = 'Default (0.1 ms)';

            % Create CancelButton
            app.CancelButton = uibutton(app.SetROIsleftrightboundaryspinnerresolutionPanel, 'push');
            app.CancelButton.ButtonPushedFcn = createCallbackFcn(app, @CancelButtonPushed, true);
            app.CancelButton.BusyAction = 'cancel';
            app.CancelButton.Position = [226 17 100 22];
            app.CancelButton.Text = 'Cancel';

            % Create SetcommandlevelPanel
            app.SetcommandlevelPanel = uipanel(app.UIFigure);
            app.SetcommandlevelPanel.Title = 'Set command level ';
            app.SetcommandlevelPanel.BackgroundColor = [0.3294 0.7294 0.8784];
            app.SetcommandlevelPanel.Position = [-2 -158 345 107];

            % Create HoldinglevelEditFieldLabel
            app.HoldinglevelEditFieldLabel = uilabel(app.SetcommandlevelPanel);
            app.HoldinglevelEditFieldLabel.HorizontalAlignment = 'right';
            app.HoldinglevelEditFieldLabel.Position = [14 52 74 22];
            app.HoldinglevelEditFieldLabel.Text = 'Holding level';

            % Create HoldinglevelEditField
            app.HoldinglevelEditField = uieditfield(app.SetcommandlevelPanel, 'numeric');
            app.HoldinglevelEditField.BusyAction = 'cancel';
            app.HoldinglevelEditField.Position = [103 52 100 22];

            % Create LevelDropDown
            app.LevelDropDown = uidropdown(app.SetcommandlevelPanel);
            app.LevelDropDown.Items = {'mV', 'µV', 'µA', 'nA', 'pA'};
            app.LevelDropDown.BusyAction = 'cancel';
            app.LevelDropDown.Position = [211 52 68 22];
            app.LevelDropDown.Value = 'mV';

            % Create OKButton_Level
            app.OKButton_Level = uibutton(app.SetcommandlevelPanel, 'push');
            app.OKButton_Level.ButtonPushedFcn = createCallbackFcn(app, @OKButton_LevelPushed, true);
            app.OKButton_Level.BusyAction = 'cancel';
            app.OKButton_Level.Position = [62 17 100 22];
            app.OKButton_Level.Text = 'OK';

            % Create CancelButton_Level
            app.CancelButton_Level = uibutton(app.SetcommandlevelPanel, 'push');
            app.CancelButton_Level.ButtonPushedFcn = createCallbackFcn(app, @CancelButton_LevelPushed, true);
            app.CancelButton_Level.BusyAction = 'cancel';
            app.CancelButton_Level.Position = [198 17 100 22];
            app.CancelButton_Level.Text = 'Cancel';

            % Create AnalysisinprogressLabel
            app.AnalysisinprogressLabel = uilabel(app.UIFigure);
            app.AnalysisinprogressLabel.BackgroundColor = [0.3922 0.8314 0.0745];
            app.AnalysisinprogressLabel.HorizontalAlignment = 'center';
            app.AnalysisinprogressLabel.FontSize = 48;
            app.AnalysisinprogressLabel.Position = [756 -114 443 63];
            app.AnalysisinprogressLabel.Text = 'Analysis in progress';

            % Create ExportinprogressLabel
            app.ExportinprogressLabel = uilabel(app.UIFigure);
            app.ExportinprogressLabel.BackgroundColor = [0.3922 0.8314 0.0745];
            app.ExportinprogressLabel.HorizontalAlignment = 'center';
            app.ExportinprogressLabel.FontSize = 48;
            app.ExportinprogressLabel.Position = [1220 -114 443 63];
            app.ExportinprogressLabel.Text = 'Export in progress';

            % Create Panel_5
            app.Panel_5 = uipanel(app.UIFigure);
            app.Panel_5.BorderWidth = 2;
            app.Panel_5.BackgroundColor = [0.9412 0.9412 0.9412];
            app.Panel_5.Position = [-296 -396 457 221];

            % Create EpisodicABFanalysisv6Label
            app.EpisodicABFanalysisv6Label = uilabel(app.Panel_5);
            app.EpisodicABFanalysisv6Label.FontSize = 24;
            app.EpisodicABFanalysisv6Label.Position = [87 182 283 32];
            app.EpisodicABFanalysisv6Label.Text = 'Episodic ABF analysis v6 ';

            % Create LoadsessionButton
            app.LoadsessionButton = uibutton(app.Panel_5, 'push');
            app.LoadsessionButton.ButtonPushedFcn = createCallbackFcn(app, @LoadsessionButtonPushed, true);
            app.LoadsessionButton.BusyAction = 'cancel';
            app.LoadsessionButton.Position = [66 38 100 23];
            app.LoadsessionButton.Text = 'Load session';

            % Create ManualpdfButton
            app.ManualpdfButton = uibutton(app.Panel_5, 'push');
            app.ManualpdfButton.ButtonPushedFcn = createCallbackFcn(app, @OpenManualpdfMenuSelected, true);
            app.ManualpdfButton.BusyAction = 'cancel';
            app.ManualpdfButton.Position = [179 38 100 23];
            app.ManualpdfButton.Text = 'Manual (pdf)';

            % Create ImportrawPanel
            app.ImportrawPanel = uipanel(app.Panel_5);
            app.ImportrawPanel.TitlePosition = 'centertop';
            app.ImportrawPanel.Title = 'Import raw';
            app.ImportrawPanel.FontSize = 14;
            app.ImportrawPanel.Position = [26 70 411 98];

            % Create ButtonGroup_2
            app.ButtonGroup_2 = uibuttongroup(app.ImportrawPanel);
            app.ButtonGroup_2.SelectionChangedFcn = createCallbackFcn(app, @ButtonGroup_2SelectionChanged, true);
            app.ButtonGroup_2.BorderType = 'none';
            app.ButtonGroup_2.TitlePosition = 'centertop';
            app.ButtonGroup_2.BusyAction = 'cancel';
            app.ButtonGroup_2.FontSize = 14;
            app.ButtonGroup_2.Position = [33 40 344 30];

            % Create EventerfilesButton
            app.EventerfilesButton = uiradiobutton(app.ButtonGroup_2);
            app.EventerfilesButton.BusyAction = 'cancel';
            app.EventerfilesButton.Text = 'Eventer files';
            app.EventerfilesButton.FontSize = 14;
            app.EventerfilesButton.Position = [252 8 99 22];

            % Create abfButton
            app.abfButton = uiradiobutton(app.ButtonGroup_2);
            app.abfButton.BusyAction = 'cancel';
            app.abfButton.Text = 'abf';
            app.abfButton.FontSize = 14;
            app.abfButton.Position = [11 8 58 22];
            app.abfButton.Value = true;

            % Create LabcharttxtButton
            app.LabcharttxtButton = uiradiobutton(app.ButtonGroup_2);
            app.LabcharttxtButton.BusyAction = 'cancel';
            app.LabcharttxtButton.Text = 'Labchart txt';
            app.LabcharttxtButton.FontSize = 14;
            app.LabcharttxtButton.Position = [68 7 95 22];

            % Create FileselectionButton
            app.FileselectionButton = uibutton(app.ImportrawPanel, 'state');
            app.FileselectionButton.ValueChangedFcn = createCallbackFcn(app, @FileselectionButtonPushed, true);
            app.FileselectionButton.BusyAction = 'cancel';
            app.FileselectionButton.Text = 'File selection';
            app.FileselectionButton.Position = [74 13 100 23];

            % Create FullfolderButton
            app.FullfolderButton = uibutton(app.ImportrawPanel, 'state');
            app.FullfolderButton.ValueChangedFcn = createCallbackFcn(app, @FileselectionButtonPushed, true);
            app.FullfolderButton.BusyAction = 'cancel';
            app.FullfolderButton.Text = 'Full folder';
            app.FullfolderButton.Position = [234 13 100 23];

            % Create UnitEditField
            app.UnitEditField = uieditfield(app.ImportrawPanel, 'text');
            app.UnitEditField.Visible = 'off';
            app.UnitEditField.Position = [224 47 50 22];
            app.UnitEditField.Value = 'mV';

            % Create UnitLabel
            app.UnitLabel = uilabel(app.ImportrawPanel);
            app.UnitLabel.Visible = 'off';
            app.UnitLabel.Position = [198 46 30 22];
            app.UnitLabel.Text = 'Unit:';

            % Create CSVConverterButton
            app.CSVConverterButton = uibutton(app.Panel_5, 'push');
            app.CSVConverterButton.ButtonPushedFcn = createCallbackFcn(app, @CSVConverterButtonPushed, true);
            app.CSVConverterButton.Visible = 'off';
            app.CSVConverterButton.Position = [179 8 100 23];
            app.CSVConverterButton.Text = 'CSV Converter';

            % Create AboutButton
            app.AboutButton = uibutton(app.Panel_5, 'push');
            app.AboutButton.ButtonPushedFcn = createCallbackFcn(app, @AboutMenuSelected, true);
            app.AboutButton.Position = [291 38 100 23];
            app.AboutButton.Text = 'About';

            % Create FilemodeLabel
            app.FilemodeLabel = uilabel(app.UIFigure);
            app.FilemodeLabel.BackgroundColor = [0.3882 0.8314 0.0706];
            app.FilemodeLabel.HorizontalAlignment = 'center';
            app.FilemodeLabel.FontSize = 20;
            app.FilemodeLabel.Position = [232 946 1173 26];
            app.FilemodeLabel.Text = 'ABF mode';

            % Create ChangefiletypemodePanel
            app.ChangefiletypemodePanel = uipanel(app.UIFigure);
            app.ChangefiletypemodePanel.Title = 'Change file type mode';
            app.ChangefiletypemodePanel.BackgroundColor = [0.302 0.7451 0.9333];
            app.ChangefiletypemodePanel.Position = [-297 -158 256 107];

            % Create ButtonGroup_3
            app.ButtonGroup_3 = uibuttongroup(app.ChangefiletypemodePanel);
            app.ButtonGroup_3.SelectionChangedFcn = createCallbackFcn(app, @ButtonGroup_3SelectionChanged, true);
            app.ButtonGroup_3.BackgroundColor = [0.302 0.7451 0.9333];
            app.ButtonGroup_3.Position = [6 52 244 30];

            % Create abfButton_2
            app.abfButton_2 = uiradiobutton(app.ButtonGroup_3);
            app.abfButton_2.Text = 'abf';
            app.abfButton_2.Position = [14 4 58 22];
            app.abfButton_2.Value = true;

            % Create LabcharttxtButton_2
            app.LabcharttxtButton_2 = uiradiobutton(app.ButtonGroup_3);
            app.LabcharttxtButton_2.Text = 'Labchart txt';
            app.LabcharttxtButton_2.Position = [57 4 85 22];

            % Create EventerfilesButton_2
            app.EventerfilesButton_2 = uiradiobutton(app.ButtonGroup_3);
            app.EventerfilesButton_2.Text = 'Eventer files';
            app.EventerfilesButton_2.Position = [146 4 88 22];

            % Create OKButton_2
            app.OKButton_2 = uibutton(app.ChangefiletypemodePanel, 'push');
            app.OKButton_2.ButtonPushedFcn = createCallbackFcn(app, @OKButton_2Pushed, true);
            app.OKButton_2.Enable = 'off';
            app.OKButton_2.Position = [6 15 100 23];
            app.OKButton_2.Text = 'OK';

            % Create CancelButton_2
            app.CancelButton_2 = uibutton(app.ChangefiletypemodePanel, 'push');
            app.CancelButton_2.ButtonPushedFcn = createCallbackFcn(app, @CancelButton_2Pushed, true);
            app.CancelButton_2.Position = [150 15 100 23];
            app.CancelButton_2.Text = 'Cancel';

            % Create Gauge
            app.Gauge = uigauge(app.UIFigure, 'linear');
            app.Gauge.MajorTicks = [0 10 20 30 40 50 60 70 80 90 100];
            app.Gauge.MinorTicks = [];
            app.Gauge.Position = [755 -154 446 41];

            % Create AboutPanel
            app.AboutPanel = uipanel(app.UIFigure);
            app.AboutPanel.Title = 'About';
            app.AboutPanel.BackgroundColor = [1 1 0.9686];
            app.AboutPanel.Position = [179 -796 1643 621];

            % Create Licence_ABFloadTextArea
            app.Licence_ABFloadTextArea = uitextarea(app.AboutPanel);
            app.Licence_ABFloadTextArea.Editable = 'off';
            app.Licence_ABFloadTextArea.FontSize = 14;
            app.Licence_ABFloadTextArea.Position = [861 77 762 477];
            app.Licence_ABFloadTextArea.Value = {'Forrest Collman (2023). fcollman/abfload (https://github.com/fcollman/abfload), GitHub. Retrieved July 10, 2023.'; ''; 'BSD-2-Clause license'; ''; 'Copyright (c) 2009, Forrest Collman'; 'Copyright (c) 2004, Harald Hentschke'; 'All rights reserved.'; ''; 'Redistribution and use in source and binary forms, with or without'; 'modification, are permitted provided that the following conditions are'; 'met:'; ''; '    * Redistributions of source code must retain the above copyright'; '      notice, this list of conditions and the following disclaimer.'; '    * Redistributions in binary form must reproduce the above copyright'; '      notice, this list of conditions and the following disclaimer in'; '      the documentation and/or other materials provided with the distribution'; ''; 'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"'; 'AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE'; 'IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE'; 'ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE'; 'LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR'; 'CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF'; 'SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS'; 'INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN'; 'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)'; 'ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE'; 'POSSIBILITY OF SUCH DAMAGE.'};

            % Create Licence_AppTextArea
            app.Licence_AppTextArea = uitextarea(app.AboutPanel);
            app.Licence_AppTextArea.Editable = 'off';
            app.Licence_AppTextArea.FontSize = 14;
            app.Licence_AppTextArea.Position = [36 77 762 476];
            app.Licence_AppTextArea.Value = {'Rabenstein, Michael, 2024, "Episodic ABF analysis", https://doi.org/10.60507/FK2/LBX1UB, bonndata, V1'; ''; 'BSD-3-Clause license'; ''; 'Copyright (c) 2024, Michael Rabenstein'; 'All rights reserved.'; ''; 'Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:'; ''; '1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.'; ''; '2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.'; ''; '3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.'; ''; 'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.'};

            % Create abfloadLabel
            app.abfloadLabel = uilabel(app.AboutPanel);
            app.abfloadLabel.FontSize = 24;
            app.abfloadLabel.Position = [861 554 84 32];
            app.abfloadLabel.Text = 'abfload';

            % Create Episodic_ABF_analysisLabel
            app.Episodic_ABF_analysisLabel = uilabel(app.AboutPanel);
            app.Episodic_ABF_analysisLabel.FontSize = 24;
            app.Episodic_ABF_analysisLabel.Position = [36 553 710 32];
            app.Episodic_ABF_analysisLabel.Text = 'Episodic_ABF_analysis + CSV Converter Episodic ABF analysis ';

            % Create CloseAboutButton
            app.CloseAboutButton = uibutton(app.AboutPanel, 'push');
            app.CloseAboutButton.ButtonPushedFcn = createCallbackFcn(app, @CloseAboutButtonPushed, true);
            app.CloseAboutButton.FontSize = 24;
            app.CloseAboutButton.Position = [752 13 145 39];
            app.CloseAboutButton.Text = 'Close';

            % Create TextArea
            app.TextArea = uitextarea(app.UIFigure);
            app.TextArea.Editable = 'off';
            app.TextArea.BackgroundColor = [0.9412 0.9412 0.9412];
            app.TextArea.Position = [13 2 233 38];
            app.TextArea.Value = {'(c) Michael Rabenstein'; 'Licensed under the BSD-3-Clause license'};

            % Show the figure after all components are created
            app.UIFigure.Visible = 'on';
        end
    end

    % App creation and deletion
    methods (Access = public)

        % Construct app
        function app = Episodic_ABF_analysis

            runningApp = getRunningApp(app);

            % Check for running singleton app
            if isempty(runningApp)

                % Create UIFigure and components
                createComponents(app)

                % Register the app with App Designer
                registerApp(app, app.UIFigure)

                % Execute the startup function
                runStartupFcn(app, @startupFcn)
            else

                % Focus the running singleton app
                figure(runningApp.UIFigure)

                app = runningApp;
            end

            if nargout == 0
                clear app
            end
        end

        % Code that executes before app deletion
        function delete(app)

            % Delete UIFigure when app is deleted
            delete(app.UIFigure)
        end
    end
end