function [dataOUT,params] = correct_time_baseline(dataIN,params)
%CORRECT_TIME_BASELINE UI for basline correction along time axis
%
%   Usage: [dataOUT,params] = CORRECT_TIME_BASELINE(dataIN,params), where
%   dataIN is a dataset loaded via the LOAD_MATLAB or LOAD_BRUKER function.
%
%   The function will show the input data and offer an input field, where
%   the number of pretrigger points should be set. By pressing "Apply" the
%   correction will be executed and the graph changes to the corrected data.
%   The number of pretigger points will also be appended to the params struct.
%   By pressing "Reset" the graph will return to show the original data.
%   Exit the function by pressing "Done".

%% creating UI
fig = figure;
fig.Name = 'Correct Time Baseline';
fig.Units = 'Normalized';
fig.Position = [.2 .2 .6 .6];
fig.Tag = 'CorrTimeBase';

%panel for plot
plotpanel = uipanel(fig);
plotpanel.Units = 'Normalized';
plotpanel.Position = [.01 .06 .98 .92];
%axes for plot
ax = axes(plotpanel);
%plot current data in figure
plot(ax,dataIN)
xlabel(ax,'Time Points');
ylabel(ax,'EPR Signal / A. U.');
axis(ax,'tight');

%create push buttons
a = uicontrol(fig,'Style','pushbutton');
a.String = 'Apply';
a.Units = 'Normalized';
a.Position = [.52 .01 .15 .05];
a.FontUnits = 'Normalized';
a.FontSize = 0.6;
a.Tag = 'Apply';
a.Callback = @TimeApplyButtonPushed;

r = uicontrol(fig,'Style','pushbutton');
r.String = 'Reset';
r.Units = 'Normalized';
r.Position = [.68 .01 .15 .05];
r.FontUnits = 'Normalized';
r.FontSize = 0.6;
r.Tag = 'Reset';
r.Callback = @TimeResetButtonPushed;

d = uicontrol(fig,'Style','pushbutton');
d.String = 'Done';
d.Units = 'Normalized';
d.Position = [.84 .01 .15 .05];
d.FontUnits = 'Normalized';
d.FontSize = 0.6;
d.Tag = 'Done';
d.Callback = @TimeDoneButtonPushed;

%create input field
inp = uicontrol(fig,'Style','edit');
inp.String = 'No. points baseline';
inp.Units = 'Normalized';
inp.Position = [.01 .01 .5 .05];
inp.HorizontalAlignment = 'left';
inp.FontUnits = 'Normalized';
inp.FontSize = 0.6;
inp.Tag = 'TimePoints';

uicontrol(inp); %passes focus to input
uiwait(fig)

%% Callback functions
    function TimeApplyButtonPushed(~,~)
        pretrigger = str2double(get(inp,'String'));
        %timeline CORRECTING
        data_size = size(dataIN);
        dataOUT = zeros(data_size);
        for n = 1:data_size(2)
            column_mean = mean(dataIN(1:pretrigger,n));
            dataOUT(:,n) = dataIN(:,n) - column_mean;
        end
        %plotting result
        plot(ax,dataOUT)
        xlabel(ax,'Time Points');
        ylabel(ax,'EPR Signal / A. U.');
        axis(ax,'tight');
        %writing parameter
        params.pretrigger = pretrigger;
    end

    function TimeResetButtonPushed(~,~)
        plot(ax,dataIN)
        xlabel(ax,'Time Points');
        ylabel(ax,'EPR Signal / A. U.');
        axis(ax,'tight');
    end

    function TimeDoneButtonPushed(~,~)
        close 'Correct Time Baseline'
    end

end

