function [ ] = dotQuant_GUI()

if ishandle(findobj('tag', 'particleTrackingFigure')) == 1
    close all;
end

guiHandle = figure('Position', [200, 100, 1200, 720],...
    'tag','figure','color', 'w', 'MenuBar','none',...
    'name','Main window','numbertitle','off', 'Visible', 'off');

particleTrackingFigureHandle = figure('Position', [50, 100, 400, 850],...
    'tag','particleTrackingFigure','color', 'w', 'MenuBar','none',...
    'name','Particle tracking','numbertitle','off','Visible', 'on');

statisticalAnalysisFigureHandle = figure('Position', [1200, 100, 225, 800],...
    'tag','statisticalAnalysisFigure','color', 'w', 'MenuBar','none',...
    'name','statistical analysis','numbertitle','off', 'Visible', 'off');

%-------------------------------------------------------------------------%
%------------------------------- Axes handles ----------------------------%
%-------------------------------------------------------------------------%


axesHandle = subplot('position', [0.15 0.15 0.7 0.75], 'color', 'k',...
    'parent', guiHandle, 'tag', 'mainAxes');
%[left,bottom,width,height]
set(axesHandle,'XColor','w', 'xtick',[]);
set(axesHandle,'YColor','w', 'ytick',[]);


%-------------------------------------------------------------------------%
%------------------------------- UI tables -------------------------------%
%-------------------------------------------------------------------------%

uitable('parent', guiHandle,...
        'unit', 'norm',...
        'position',[0.01 0.65 0.131 0.2],... %[left,bottom,width,height]
        'Visible', 'off',...
        'ColumnName', {'Track','Show'},...
        'ColumnFormat', {'numeric','logical'},...
        'ColumnWidth',{42},...
        'tag', 'tracksTable1',...
        'ColumnEditable', [false true],...
        'Data', {});
uicontrol('Style','text',...
    'parent', guiHandle,...
    'String','Show tracks:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 12,...
    'Visible', 'off',...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.03 0.86 0.12 0.03],... %[left,bottom,width,height]
    'tag','showTrack1Title');
uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'Visible', 'off',...
    'Value', 1,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.01 0.87 0.02 0.02],... %[left,bottom,width,height]
    'tag','showAllTracks1',...
    'callback', {@showAll, 'tracksTable1'});

uitable('parent', guiHandle,...
        'unit', 'norm',...
        'position',[0.01 0.365 0.131 0.2],... %[left,bottom,width,height]
        'Visible', 'off',...
        'ColumnName', {'Track','Show'},...
        'ColumnFormat', {'numeric','logical'},...
        'ColumnWidth',{42},...
        'tag', 'tracksTable2',...
        'ColumnEditable', [false true],...
        'Data', {});
uicontrol('Style','text',...
    'parent', guiHandle,...
    'String','Show tracks:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 12,...
    'Visible', 'off',...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.03 0.575 0.12 0.03],... %[left,bottom,width,height]
    'tag','showTrack2Title');
uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'Visible', 'off',...
    'Value', 1,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.01 0.585 0.02 0.02],... %[left,bottom,width,height]
    'tag','showAllTracks2',...
    'callback', {@showAll, 'tracksTable2'});
    
uitable('parent', guiHandle,...
        'unit', 'norm',...
        'position',[0.01 0.085 0.131 0.2],... %[left,bottom,width,height]
        'Visible', 'off',...
        'ColumnName', {'Track','Show'},...
        'ColumnFormat', {'numeric','logical'},...
        'ColumnWidth',{42},...
        'tag', 'tracksTable3',...
        'ColumnEditable', [false true],...
        'Data', {});
uicontrol('Style','text',...
    'parent', guiHandle,...
    'String','Show tracks:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 12,...
    'Visible', 'off',...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.03 0.295 0.12 0.03],... %[left,bottom,width,height]
    'tag','showTrack3Title');
uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'Visible', 'off',...
    'Value', 1,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.01 0.305 0.02 0.02],... %[left,bottom,width,height]
    'tag','showAllTracks3',...
    'callback', {@showAll, 'tracksTable3'});

%-------------------------------------------------------------------------%
%------------------------------- UI controls -----------------------------%
%-------------------------------------------------------------------------%

uicontrol('style'   ,'slider',....
    'parent', guiHandle,...
    'unit', 'norm',...
    'position',[0.15 0.085 0.7 0.025],... %[left,bottom,width,height]
    'Enable', 'off',...
    'tag'     ,'timePointSlider',...
    'max'     ,100,... %change values to fit number of time points 
    'min'     ,1,...
    'sliderstep',[0.01 0.1],... %change to 1 time point per minor step
    'value'   ,1,...
    'callback', {@changeImage, axesHandle});
% Adds timepoint over slider
uicontrol('Style','text',...
    'parent', guiHandle,...
    'String','Time point',...
    'fontsize', 12,...
    'HorizontalAlignment', 'left',...
    'backgroundColor','w',...
    'foregroundColor','b',...
    'unit', 'norm',...
    'Position',[0.15 0.12 0.2 0.025],... %[left,bottom,width,height]
    'tag','timePoint');

uicontrol('style'   ,'popupmenu',...
    'String', '3D time lapse|2D time lapse',...
    'parent', particleTrackingFigureHandle,...
    'unit', 'norm',...
    'fontsize', 11,...
    'position',[0.075 0.87 0.43 0.05],... %[left,bottom,width,height]
    'tag','dataType');
% Adds title to pop up menu
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Data type',...
    'fontsize', 14,...
    'backgroundColor','w',...
    'foregroundColor','b',...
    'unit', 'norm',...
    'Position',[0.075 0.92 0.43 0.0375],... %[left,bottom,width,height]
    'tag','dataTypeTitle');

%controls for user to enter pixel and step size 
uicontrol('style'        ,'edit',...
    'parent', particleTrackingFigureHandle,...
    'String', '0.2',...
    'value', 0.2,...
    'fontsize', 10,...
    'tag', 'pixelSize',...
    'TooltipString', 'The pixel size (on the X and Y axes) in microns',...
    'unit', 'norm',...
    'position', [0.075 0.765 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Pixel size (microns)',...
    'HorizontalAlignment', 'left',...
    'fontsize', 11,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.795 0.43 0.025],... %[left,bottom,width,height]
    'tag','pixelSizeTitle');

uicontrol('style'        ,'edit',...
    'parent', particleTrackingFigureHandle,...
    'String', '0.8',...
    'value', 0.8,...
    'fontsize', 10,...
    'tag', 'stepSize',...
    'TooltipString', 'The step size (or pixel size on the Z axis) in microns',...
    'unit', 'norm',...
    'position', [0.075 0.705 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Step size (microns)',...
    'HorizontalAlignment', 'left',...
    'fontsize', 11,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.735 0.43 0.025],... %[left,bottom,width,height]
    'tag','stepSizeTitle');

% Adds title to text edit boxes
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Voxel size',...
    'fontsize', 14,...
    'backgroundColor','w',...
    'foregroundColor','b',...
    'unit', 'norm',...
    'Position',[0.075 0.825 0.43 0.0375],... %[left,bottom,width,height]
    'tag','voxelSizeTitle');

%controls for user to adjust particle tracking
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Particles',...
    'fontsize', 14,...
    'backgroundColor','w',...
    'foregroundColor','b',...
    'unit', 'norm',...
    'Position',[0.075 0.645 0.43 0.0375],... %[left,bottom,width,height]
    'tag','ParticleTrackingTitle');

uicontrol('style'        ,'edit',...
    'parent', particleTrackingFigureHandle,...
    'String', '140',...
    'value', 140,...
    'fontsize', 10,...
    'tag', 'threshold',...
    'TooltipString', ['The threshold value specifies the intensity value under which local maxima will', char(10),...
    'be omitted, as a percentage of the mean intensity of the entire image.', char(10),...
    'Insert a higher threshold to ignore all but the brightest dots.'],...
    'unit', 'norm',...
    'position', [0.075 0.575 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Threshold (percent of mean)',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.6 0.45 0.03],... %[left,bottom,width,height]
    'tag','thresholdTitle');

uicontrol('style'        ,'edit',...
    'parent', particleTrackingFigureHandle,...
    'String', '250',...
    'value', 250,...
    'fontsize', 10,...
    'tag', 'maxNoOfParticles',...
    'TooltipString', ['The maximum number of particles expected per time point.', char(10),...
    'For a maximum of 250 for example, the program will only find', char(10),...
    'between 0 and 250 particles in each time point.'],...
    'unit', 'norm',...
    'position', [0.075 0.48 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Maximum number of particles in time point',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.51 0.43 0.05],... %[left,bottom,width,height]
    'tag','maxNoOfParticlesTitle');

uicontrol('style'        ,'edit',...
    'parent', particleTrackingFigureHandle,...
    'String', '3',...
    'value', 3,...
    'fontsize', 10,...
    'tag', 'maxLinkingDistance',...
    'TooltipString', ['The maximum allowed distance between particles over time. The program will not link particles in successive time points', char(10),...
    'if they are farther apart than the specified distance. Increase this value if the dots move around a lot in your data.', char(10),...
    'Distance should be specified in microns.'],...
    'unit', 'norm',...
    'position', [0.075 0.385 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Maximum linking distance (microns)',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.415 0.43 0.05],... %[left,bottom,width,height]
    'tag','maxLinkingDistanceTitle');

uicontrol('style'        ,'edit',...
    'parent', particleTrackingFigureHandle,...
    'String', '0',...
    'value', 0,...
    'fontsize', 10,...
    'tag', 'maxLinkingGap',...
    'TooltipString', ['The maximum gap that can be closed between two successive tracks. The program will not close', char(10),...
    'gaps between tracks that are further apart than the specified value.', char(10),...
    'Gap size should be specified in time points. Insert 0 to ignore this feature.'],...
    'unit', 'norm',...
    'position', [0.075 0.285 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Maximum linking gap (time points)',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.315 0.43 0.05],... %[left,bottom,width,height]
    'tag','maxLinkingGapTitle');

uicontrol('style'        ,'edit',...
    'parent', particleTrackingFigureHandle,...
    'String', '45',...
    'value', 45,...
    'fontsize', 10,...
    'tag', 'minTrackLength',...
    'TooltipString', ['Insert the minimum acceptable particle track length. The program will omit tracks', char(10),...
    'that are shorter than the specified length.', char(10),...
    'Minimum size should be specified in time points. Insert 0 to ignore this feature.'],...
    'unit', 'norm',...
    'position', [0.075 0.195 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Minimum track length (time points)',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.225 0.43 0.05],... %[left,bottom,width,height]
    'tag','minTrackLengthTitle');

uicontrol('style'        ,'edit',...
    'parent', particleTrackingFigureHandle,...
    'String', '10',...
    'value', 10,...
    'fontsize', 10,...
    'tag', 'regionalMaximumRadiusXY',...
    'TooltipString', ['Local maxima are detected as the brightest voxel in a cube of this size.', char(10),...
    'The value specifies the X and Y radius of the cube in pixels.'],...
    'unit', 'norm',...
    'position', [0.31 0.095 0.23 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','XY radius',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.095 0.23 0.025],... %[left,bottom,width,height]
    'tag','regionalMaximumRadiusXYTitle');

uicontrol('style'        ,'edit',...
    'parent', particleTrackingFigureHandle,...
    'String', '4',...
    'value', 4,...
    'fontsize', 10,...
    'tag', 'regionalMaximumRadiusZ',...
    'TooltipString', ['Local maxima are detected as the brightest voxel in a cube of this size.', char(10),...
    'The value specifies the Z radius of the cube in pixels.'],...
    'unit', 'norm',...
    'position', [0.31 0.06 0.23 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Z radius',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.06 0.23 0.025],... %[left,bottom,width,height]
    'tag','regionalMaximaRadiusZTitle');

uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Regional maximum area',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.12 0.43 0.05],... %[left,bottom,width,height]
    'tag','regionalMaximumAreaTitle');

uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'fontsize', 10,...
    'backgroundColor','k',...
    'foregroundColor','k',...
    'unit', 'norm',...
    'Position',[0.55 0.15 0.005 0.8]); %[left,bottom,width,height]

%This part holds buttons for the user to choose a channel and its name
uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Channels',...
    'fontsize', 14,...
    'backgroundColor','w',...
    'foregroundColor','b',...
    'unit', 'norm',...
    'Position',[0.575 0.92 0.43 0.0375],... %[left,bottom,width,height]
    'tag','channelsTitle');

uicontrol('Style','text',...
    'parent', particleTrackingFigureHandle,...
    'String','Choose channels:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 12,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.6 0.86 0.43 0.05],... %[left,bottom,width,height]
    'tag','chooseChannelTitle');

%Check box and editable text box for first channel
uicontrol('Style','checkbox',...
    'parent', particleTrackingFigureHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.6 0.835 0.2 0.02],... %[left,bottom,width,height]
    'tag','chooseChannel1',...
    'TooltipString', 'Tick to choose this channel',... 
    'callback', {@chooseChannel, 'Channel1'});

uicontrol('style','edit',...
    'parent', particleTrackingFigureHandle,...
    'TooltipString', 'Change name to match channel name',...
    'String', 'c405',...
    'Enable', 'off',...
    'fontsize', 11,...
    'HorizontalAlignment', 'left',...
    'unit', 'norm',...
    'position', [0.7 0.835 0.225 0.03],...%[left,bottom,width,height]
    'tag','Channel1');

%Check box and editable text box for second channel
uicontrol('Style','checkbox',...
    'parent', particleTrackingFigureHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.6 0.785 0.2 0.02],... %[left,bottom,width,height]
    'tag','chooseChannel2',...
    'TooltipString', 'Tick to choose this channel',...
    'callback', {@chooseChannel, 'Channel2'});

uicontrol('style','edit',...
    'parent', particleTrackingFigureHandle,...
    'TooltipString', 'Change name to match channel name',...
    'String', 'c488',...
    'Enable', 'off',...
    'fontsize', 11,...
    'HorizontalAlignment', 'left',...
    'unit', 'norm',...
    'position', [0.7 0.785 0.225 0.03],...%[left,bottom,width,height]
    'tag','Channel2');

%Check box and editable text box for third channel
uicontrol('Style','checkbox',...
    'parent', particleTrackingFigureHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.6 0.735 0.2 0.02],... %[left,bottom,width,height]
    'tag','chooseChannel3',...
    'TooltipString', 'Tick to choose this channel',...
    'callback', {@chooseChannel, 'Channel3'});

uicontrol('style','edit',...
    'parent', particleTrackingFigureHandle,...
    'TooltipString', 'Change name to match channel name',...
    'String', 'c561',...
    'Enable', 'off',...
    'fontsize', 11,...
    'HorizontalAlignment', 'left',...
    'unit', 'norm',...
    'position', [0.7 0.735 0.225 0.03],...%[left,bottom,width,height]
    'tag','Channel3');

uicontrol('style','pushbutton',...
    'parent', particleTrackingFigureHandle,...
    'String', 'Align Tracks',...
    'Enable', 'off',...
    'fontsize', 11,...
    'HorizontalAlignment', 'left',...
    'unit', 'norm',...
    'position', [0.6 0.55 0.35 0.03],...%[left,bottom,width,height]
    'tag','alignTracks',...
    'TooltipString', 'Correlate particles across channels. This will create additional tracks.',...
    'callback', {@alignTracks});

uicontrol('Style','checkbox',...
    'parent', particleTrackingFigureHandle,...
    'String','Run parallel CPU',...
    'value', 1,...
    'fontsize', 11,...
    'backgroundColor','w',...
    'foregroundColor','k',...
    'unit', 'norm',...
    'Position',[0.6 0.68 0.45 0.02],... %[left,bottom,width,height]
    'tag','multithread',...
    'callback', {@setWarning, 'warning'});

uicontrol('style','text',...
    'parent', particleTrackingFigureHandle,...
    'String', 'Warning: may cause crashes if memory is insufficient',...
    'Enable', 'on',...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'fontsize', 11,...
    'HorizontalAlignment', 'left',...
    'unit', 'norm',...
    'position', [0.6 0.58 0.45 0.09],...%[left,bottom,width,height]
    'tag','warning');

%This part holds buttons for the user to choose to show a channel and 
%its name
uicontrol('Style','text',...
    'parent', guiHandle,...
    'String','Show channels:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 12,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.87 0.85 0.1 0.03],... %[left,bottom,width,height]
    'tag','showChannelTitle');

%Check box and editable text box for first channel
uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.87 0.8 0.05 0.03],... %[left,bottom,width,height]
    'tag','chooseShowChannel1',...
    'TooltipString', 'Tick to show image of channel in current time point',...
    'callback', {@changeImage, axesHandle});

uicontrol('style','edit',...
    'parent', guiHandle,...
    'String', 'c405',...
    'fontsize', 11,...
    'HorizontalAlignment', 'left',...
    'TooltipString', 'Change name to match channel name',...
    'unit', 'norm',...
    'position', [0.9 0.8 0.075 0.03],...%[left,bottom,width,height]
    'tag','showChannel1');

uicontrol('style'   ,'text',...
    'parent', guiHandle,...
    'backgroundColor','b',...
    'foregroundColor','b',...
    'unit', 'norm',...
    'fontsize', 11,...
    'position',[0.87 0.75 0.105 0.02],... %[left,bottom,width,height]
    'tag','channel1Color');

uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'backgroundColor','w',...
    'foregroundColor','k',...
    'String', 'Enhance contrast',...
    'fontsize', 10,...
    'unit', 'norm',...
    'Position',[0.87 0.77 0.15 0.03],... %[left,bottom,width,height]
    'tag','enhanceContrastChannel1',...
    'TooltipString', 'Tick to enable image contrast enhancing');

%Check box and editable text box for second channel
uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.87 0.7 0.05 0.03],... %[left,bottom,width,height]
    'tag','chooseShowChannel2',...
    'TooltipString', 'Tick to show image of channel in current time point',...
    'callback', {@changeImage, axesHandle});

uicontrol('style','edit',...
    'parent', guiHandle,...
    'String', 'c488',...
    'fontsize', 11,...
    'HorizontalAlignment', 'left',...
    'TooltipString', 'Change name to match channel name',...
    'unit', 'norm',...
    'position', [0.9 0.7 0.075 0.03],...%[left,bottom,width,height]
    'tag','showChannel2');

uicontrol('style'   ,'text',...
    'parent', guiHandle,...
    'backgroundColor','g',...
    'foregroundColor','g',...
    'unit', 'norm',...
    'fontsize', 11,...
    'position',[0.87 0.65 0.105 0.02],... %[left,bottom,width,height]
    'tag','channel2Color');

uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'backgroundColor','w',...
    'foregroundColor','k',...
    'String', 'Enhance contrast',...
    'fontsize', 10,...
    'unit', 'norm',...
    'Position',[0.87 0.67 0.15 0.03],... %[left,bottom,width,height]
    'tag','enhanceContrastChannel2',...
    'TooltipString', 'Tick to enable image contrast enhancing');

%Check box and editable text box for third channel
uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.87 0.6 0.075 0.03],... %[left,bottom,width,height]
    'tag','chooseShowChannel3',...
    'TooltipString', 'Tick to show image of channel in current time point',...
    'callback', {@changeImage, axesHandle});

uicontrol('style','edit',...
    'parent', guiHandle,...
    'String', 'c561',...
    'fontsize', 11,...
    'HorizontalAlignment', 'left',...
    'TooltipString', 'Change name to match channel name',...
    'unit', 'norm',...
    'position', [0.9 0.6 0.075 0.03],...%[left,bottom,width,height]
    'tag','showChannel3');

uicontrol('style'   ,'text',...
    'parent', guiHandle,...
    'backgroundColor','r',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'fontsize', 11,...
    'position',[0.87 0.55 0.105 0.02],... %[left,bottom,width,height]
    'tag','channel3Color');

uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'backgroundColor','w',...
    'foregroundColor','k',...
    'String', 'Enhance contrast',...
    'fontsize', 10,...
    'unit', 'norm',...
    'Position',[0.87 0.57 0.15 0.03],... %[left,bottom,width,height]
    'tag','enhanceContrastChannel3',...
    'TooltipString', 'Tick to enable image contrast enhancing');

%Check box and editable text box for forth channel
uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.87 0.5 0.075 0.03],... %[left,bottom,width,height]
    'tag','chooseShowChannel4',...
    'TooltipString', 'Tick to show image of channel in current time point',...
    'callback', {@changeImage, axesHandle});

uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'backgroundColor','w',...
    'foregroundColor','k',...
    'String', 'Enhance contrast',...
    'fontsize', 10,...
    'unit', 'norm',...
    'Position',[0.87 0.47 0.15 0.03],... %[left,bottom,width,height]
    'tag','enhanceContrastChannel4',...
    'TooltipString', 'Tick to enable image contrast enhancing');

uicontrol('style','edit',...
    'parent', guiHandle,...
    'String', 'cDIC',...
    'fontsize', 11,...
    'HorizontalAlignment', 'left',...
    'TooltipString', 'Change name to match channel name',...
    'unit', 'norm',...
    'position', [0.9 0.5 0.075 0.03],...%[left,bottom,width,height]
    'tag','showChannel4');

uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'backgroundColor','w',...
    'unit', 'norm',...
    'Position',[0.87 0.44 0.15 0.03],... %[left,bottom,width,height]
    'tag','showSeparate',...
    'TooltipString', ['Tick to show channel in a separate window. This is helpful', char(10),...
    'for when this channel dims the general image.'],...
    'callback', {@showSeparateFun, 'showChannel4'});

uicontrol('Style','text',...
    'parent', guiHandle,...
    'String','Show channel in separate window',...
    'foregroundColor','k',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'HorizontalAlignment', 'left',...
    'unit', 'norm',...
    'Position',[0.885 0.4175 0.12 0.05],... %[left,bottom,width,height]
    'tag','showDICSeparateTitle');

uicontrol('style'   ,'text',...
    'parent', guiHandle,...
    'Enable', 'off',...
    'unit', 'norm',...
    'fontsize', 11,...
    'position',[0.87 0.395 0.105 0.02],... %[left,bottom,width,height]
    'tag','channel4Color');

uicontrol('Style','checkbox',...
    'parent', guiHandle,...
    'backgroundColor','w',...
    'Value', 0,...
    'foregroundColor','k',...
    'fontsize', 12,...
    'string', 'Zoom in',...
    'unit', 'norm',...
    'Position',[0.9 0.25 0.15 0.03],... %[left,bottom,width,height]
    'tag','zoomIn',...
    'TooltipString', ['Tick to zoom in on image.', char(10),...
    'Draw an area or click to zoom in.', char(10),...
    'Double click to reset view.'],...
    'callback', {@Zoom, 'zoomIn', guiHandle, 'on'});

uicontrol('style'   ,'pushbutton',...
    'parent', guiHandle,...
    'String','Reset view' ,...
    'Enable', 'on',...
    'unit', 'norm',...
    'fontsize', 12,...
    'position',[0.9 0.2 0.075 0.03],... %[left,bottom,width,height]
    'tag','resetView',...
    'TooltipString', 'Reset image view to original zoom factor',...
    'callback', {@Zoom, 'zoomIn', guiHandle, 'out'});

uicontrol('style'   ,'pushbutton',...
    'parent', guiHandle,...
    'String','Refresh' ,...
    'Enable', 'on',...
    'unit', 'norm',...
    'fontsize', 12,...
    'position',[0.9 0.15 0.075 0.03],... %[left,bottom,width,height]
    'tag','refreshButton',...
    'TooltipString', ['Refresh image to current time point.', char(10),...
    'This is helpful when graphic processing is slow.'],...
    'callback', {@refresh, axesHandle});


%------------------------------- data analysis ---------------------------%

uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Data analysis',...
    'fontsize', 14,...
    'backgroundColor','w',...
    'foregroundColor','b',...
    'unit', 'norm',...
    'Position',[0.075 0.92 0.75 0.0375],... %[left,bottom,width,height]
    'tag','dataAnalysisTitle');
%inserts title for section

%sum according to a number of neighbors
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Sum object pixels:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'on',...
    'unit', 'norm',...
    'Position',[0.3 0.885 0.75 0.02],... %[left,bottom,width,height]
    'tag','sumObjectPixelsTitle');

%Check box and editable text boxes for number of pixels to quantify around
%local maxima
uicontrol('Style','checkbox',...
    'parent', statisticalAnalysisFigureHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'on',...
    'unit', 'norm',...
    'Position',[0.075 0.885 0.2 0.02],... %[left,bottom,width,height]
    'tag','chooseSumPixels',...
    'TooltipString', 'Tick to sum all voxels within range around local maxima',...
    'callback', {@chooseSum});

%edit text boxes for user to input range for qunatifying sum
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '1',...
    'value', 1,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'sumPixelsXY',...
    'TooltipString', ['Choose radius in X and Y around local maxima to sum all voxels within cube.', char(10),...
    'Radius value is specified in pixels.'],...
    'unit', 'norm',...
    'position', [0.5 0.835 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','XY pixels',...
    'HorizontalAlignment', 'left',...
    'Enable', 'off',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.835 0.4 0.025],... %[left,bottom,width,height]
    'tag','sumPixelsXYTitle');

uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '0',...
    'value', 0,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'sumPixelsZ',...
    'TooltipString', ['Choose radius in Z around local maxima to sum all voxels within cube.', char(10),...
    'Radius value is specified in pixels.'],...
    'unit', 'norm',...
    'position', [0.5 0.805 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Z pixels',...
    'HorizontalAlignment', 'left',...
    'Enable', 'off',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.805 0.4 0.025],... %[left,bottom,width,height]
    'tag','sumPixelsZTitle');

%perform analysis within a selection cube
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Define selection cube',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'on',...
    'unit', 'norm',...
    'Position',[0.3 0.745 0.75 0.02],... %[left,bottom,width,height]
    'tag','selectCubeTitle');
%Check box and editable text boxes to define a selection cube
uicontrol('Style','checkbox',...
    'parent', statisticalAnalysisFigureHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'on',...
    'unit', 'norm',...
    'Position',[0.075 0.745 0.2 0.02],... %[left,bottom,width,height]
    'tag','selectCube',...
    'TooltipString', 'Tick to define a selection cube around local maxima for further analysis',...
    'callback', {@selectCube});

%edit text boxes for user to input range for selection cube
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '5',...
    'value', 5,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'selectionPixelsXY',...
    'TooltipString', 'Choose radius in X and Y around local maxima to define cube',...
    'unit', 'norm',...
    'position', [0.5 0.7 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','XY pixels',...
    'HorizontalAlignment', 'left',...
    'Enable', 'off',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.7 0.4 0.025],... %[left,bottom,width,height]
    'tag','selectionPixelsXYTitle');

uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '2',...
    'value', 2,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'selectionPixelsZ',...
    'TooltipString', 'Choose radius in Z around local maxima to define cube',...
    'unit', 'norm',...
    'position', [0.5 0.67 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Z pixels',...
    'HorizontalAlignment', 'left',...
    'Enable', 'off',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.67 0.4 0.025],... %[left,bottom,width,height]
    'tag','selectionPixelsZTitle');

%added checkboxes for user to decide how to quantify within selection cube
%when needed, there's also an edit text box

%quantify n brightest pixels
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Sum brightest pixels',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.3 0.64 0.75 0.02],... %[left,bottom,width,height]
    'tag','sumBrightestPixelsTitle');
uicontrol('Style','checkbox',...
    'parent', statisticalAnalysisFigureHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.075 0.64 0.2 0.02],... %[left,bottom,width,height]
    'tag','sumBrightestPixels',...
    'TooltipString', 'Tick to quantify box intensity by summing the #n brightest pixels within the cube',...
    'callback', {@selectBrightestPixels});
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '12',...
    'value', 12,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'numberOfBrightestPixels',...
    'unit', 'norm',...
    'TooltipString', 'Select number of brightest pixels to sum',...
    'position', [0.5 0.6 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Pixels',...
    'HorizontalAlignment', 'left',...
    'Enable', 'off',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.6 0.4 0.025],... %[left,bottom,width,height]
    'tag','numberOfBrightestPixelsTitle');

%sum pixels n% above median
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Sum pixels above median',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.3 0.56 0.75 0.02],... %[left,bottom,width,height]
    'tag','sumPixelsAboveMedianTitle');
uicontrol('Style','checkbox',...
    'parent', statisticalAnalysisFigureHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.075 0.56 0.2 0.02],... %[left,bottom,width,height]
    'tag','sumPixelsAboveMedian',...
    'TooltipString', ['Tick to quantify box intensity by summing all pixels', char(10),...
    'that are #n percent above the cube median'],...
    'callback', {@sumPixelsAboveMedian});

uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '100',...
    'value', 100,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'percentAboveMedian',...
    'TooltipString', 'Select percent above median for intensity quantification',...
    'unit', 'norm',...
    'position', [0.5 0.52 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Percent above',...
    'HorizontalAlignment', 'left',...
    'Enable', 'off',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.52 0.4 0.025],... %[left,bottom,width,height]
    'tag','percentAboveMedianTitle');

%sum pixels over n% of local maximum
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Sum pixels close to max',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.3 0.48 0.75 0.02],... %[left,bottom,width,height]
    'tag','sumPixelsCloseToMaxTitle');
uicontrol('Style','checkbox',...
    'parent', statisticalAnalysisFigureHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.075 0.48 0.2 0.02],... %[left,bottom,width,height]
    'tag','sumPixelsCloseToMax',...
    'TooltipString', ['Tick to quantify box intensity by summing all pixels that are', char(10),...
    'between the cube median intensity and the maximum intensity'],...
    'callback', {@sumPixelsCloseToMax});    

uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '50',...
    'value', 50,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'percentOfMax',...
    'TooltipString', ['Choose percent of the range between the cube median and the maximum value.', char(10),...
    'For exemple, if the value is 50, then the sum will be that of all pixels above', char(10),...
    'the intensity value that is at 50 percent between the cube median and maximum'],...
    'unit', 'norm',...
    'position', [0.5 0.44 0.4 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Percent of range',...
    'HorizontalAlignment', 'left',...
    'Enable', 'off',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'unit', 'norm',...
    'Position',[0.075 0.44 0.42 0.025],... %[left,bottom,width,height]
    'tag','percentOfMaxTitle');

%fit gaussian
%uicontrol('Style','text',...
    %'parent', statisticalAnalysisFigureHandle,...
   % 'String','Fit to gaussian:',...
   % 'HorizontalAlignment', 'left',...
  %  'fontsize', 10,...
  %  'backgroundColor','w',...
  %  'foregroundColor','r',...
  %  'Enable', 'off',...
  %  'unit', 'norm',...
  %  'Position',[0.3 0.3 0.75 0.02],... %[left,bottom,width,height]
  %  'tag','fitGaussianTitle');

%Check box and editable text boxes for number of pixels to quantify around
%local maxima
%uicontrol('Style','checkbox',...
  %  'parent', statisticalAnalysisFigureHandle,...
  %  'backgroundColor','w',...
  %  'foregroundColor','r',...
  %  'Enable', 'off',...
  %  'unit', 'norm',...
  %  'Position',[0.075 0.3 0.2 0.02],... %[left,bottom,width,height]
  %  'tag','chooseFitGaussian',...
  %  'callback',{@chooseGaussian});

%edit text boxes for user to input range around maximum to fit gaussian
%uicontrol('style'        ,'edit',...
    %'parent', statisticalAnalysisFigureHandle,...
    %'String', '3',...
    %'value', 3,...
    %'fontsize', 10,...
    %'Enable', 'off',...
    %'tag', 'gaussianFitXY',...
    %'unit', 'norm',...
    %'position', [0.5 0.27 0.4 0.025],... %[left,bottom,width,height]
    %'callback', {@changeValue});
%uicontrol('Style','text',...
    %'parent', statisticalAnalysisFigureHandle,...
   % 'String','XY range',...
    %'HorizontalAlignment', 'left',...
   % 'Enable', 'off',...
   % 'fontsize', 10,...
   % 'backgroundColor','w',...
   % 'foregroundColor','r',...
   % 'unit', 'norm',...
   % 'Position',[0.075 0.27 0.4 0.025],... %[left,bottom,width,height]
  %  'tag','gaussianFitXYTitle');

%uicontrol('style'        ,'edit',...
    %'parent', statisticalAnalysisFigureHandle,...
    %'String', '3',...
    %'value', 3,...
    %'fontsize', 10,...
    %'Enable', 'off',...
   % 'tag', 'gaussianFitZ',...
   % 'unit', 'norm',...
   % 'position', [0.5 0.24 0.4 0.025],... %[left,bottom,width,height]
   % 'callback', {@changeValue});
%uicontrol('Style','text',...
    %'parent', statisticalAnalysisFigureHandle,...
    %'String','Z range',...
    %'HorizontalAlignment', 'left',...
    %'Enable', 'off',...
    %'fontsize', 10,...
    %'backgroundColor','w',...
    %'foregroundColor','r',...
    %'unit', 'norm',...
    %'Position',[0.075 0.24 0.4 0.025],... %[left,bottom,width,height]
    %'tag','gaussianFitZTitle');

%noise subtraction

uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Subtract background',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'on',...
    'unit', 'norm',...
    'Position',[0.3 0.38 0.75 0.02],... %[left,bottom,width,height]
    'tag','subtractBackgroundTitle');
uicontrol('Style','checkbox',...
    'parent', statisticalAnalysisFigureHandle,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'on',...
    'unit', 'norm',...
    'Position',[0.075 0.38 0.2 0.02],... %[left,bottom,width,height]
    'tag','subtractBackground',...
    'TooltipString', ['Tick to create a rectangle in image background to',  char(10),...
    'subtract noise from final intensity analysis'],...
    'callback',{@subtractBackground, 'subtractBackgroundXMax', 'subtractBackgroundYMax',...
    'subtractBackgroundXTitle1', 'subtractBackgroundXTitle2', 'subtractBackgroundXstart', 'subtractBackgroundXend',...
    'subtractBackgroundYTitle1', 'subtractBackgroundYTitle2', 'subtractBackgroundYstart', 'subtractBackgroundYend'});

uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','X from:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.075 0.34 0.2 0.02],... %[left,bottom,width,height]
    'tag','subtractBackgroundXTitle1');
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '1',...
    'value', 1,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'subtractBackgroundXstart',...
    'unit', 'norm',...
    'position', [0.275 0.34 0.2 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','to',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.5 0.34 0.1 0.02],... %[left,bottom,width,height]
    'tag','subtractBackgroundXTitle2');
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '',...
    'value', 1,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'subtractBackgroundXend',...
    'unit', 'norm',...
    'position', [0.6 0.34 0.2 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'Visible', 'off',...
    'unit', 'norm',...
    'Position',[0.825 0.34 0.2 0.02],... %[left,bottom,width,height]
    'tag','subtractBackgroundXMax');

uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Y from:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.075 0.3 0.2 0.02],... %[left,bottom,width,height]
    'tag','subtractBackgroundYTitle1');
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '1',...
    'value', 1,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'subtractBackgroundYstart',...
    'unit', 'norm',...
    'position', [0.275 0.3 0.2 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','to',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.5 0.3 0.1 0.02],... %[left,bottom,width,height]
    'tag','subtractBackgroundYTitle2');
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '',...
    'value', 1,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'subtractBackgroundYend',...
    'unit', 'norm',...
    'position', [0.6 0.3 0.2 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'Visible', 'off',...
    'unit', 'norm',...
    'Position',[0.825 0.3 0.2 0.02],... %[left,bottom,width,height]
    'tag','subtractBackgroundYMax');

uicontrol('style'   ,'checkbox',....
    'parent', statisticalAnalysisFigureHandle,...
    'unit', 'norm',...
    'string','Analyze individual tracks',...
    'Value', 1,...
    'fontsize', 11,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'position',[0.075 0.2375 0.9 0.022],... %[left,bottom,width,height]
    'Enable', 'on',...
    'tag','individualAnalysis',...
    'TooltipString', 'Tick to perform analysis on separate unaligned tracks',...
    'callback', {@toggle, 'individualAnalysis', 'alignedAnalysis', 'autoFitWindowTitle1', 'autoFitWindowTitle2',...
    'autoFitWindowMin', 'autoFitWindowMax', 'autoFitDeltaTitle1', 'autoFitDeltaTitle2',...
    'autoFitDeltaMin', 'autoFitDeltaMax'});
uicontrol('style'   ,'checkbox',....
    'parent', statisticalAnalysisFigureHandle,...
    'unit', 'norm',...
    'string','Analyze aligned tracks',...
    'Value', 0,...
    'fontsize', 11,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'position',[0.075 0.2 0.9 0.022],... %[left,bottom,width,height]
    'Enable', 'off',...
    'tag','alignedAnalysis',...
    'TooltipString', 'Tick to perform analysis on aligned tracks',...
    'callback', {@toggle, 'individualAnalysis', 'alignedAnalysis', 'autoFitWindowTitle1', 'autoFitWindowTitle2',...
    'autoFitWindowMin', 'autoFitWindowMax', 'autoFitDeltaTitle1', 'autoFitDeltaTitle2',...
    'autoFitDeltaMin', 'autoFitDeltaMax'});

uicontrol('style'   ,'checkbox',....
    'parent', statisticalAnalysisFigureHandle,...
    'unit', 'norm',...
    'string','Auto fit sigmoid',...
    'Value', 0,...
    'fontsize', 11,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'position',[0.075 0.1625 0.9 0.022],... %[left,bottom,width,height]
    'Enable', 'off',...
    'tag','autoFitSigmoid',...
    'TooltipString', 'Tick to automatically fit sigmoid to data',...
    'callback', {@autoFit, 'autoFitWindowTitle1', 'autoFitWindowTitle2',...
    'autoFitWindowMin', 'autoFitWindowMax', 'autoFitDeltaTitle1', 'autoFitDeltaTitle2',...
    'autoFitDeltaMin', 'autoFitDeltaMax'});

uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Window min:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.075 0.12 0.35 0.02],... %[left,bottom,width,height]
    'tag','autoFitWindowTitle1');
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '25',...
    'value', 25,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'autoFitWindowMin',...
    'unit', 'norm',...
    'position', [0.425 0.12 0.15 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','max:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.6 0.12 0.15 0.02],... %[left,bottom,width,height]
    'tag','autoFitWindowTitle2');
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '90',...
    'value', 90,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'autoFitWindowMax',...
    'unit', 'norm',...
    'position', [0.75 0.12 0.15 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});

uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','Delta T min:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.075 0.08 0.35 0.02],... %[left,bottom,width,height]
    'tag','autoFitDeltaTitle1');
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '7',...
    'value', 7,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'autoFitDeltaMin',...
    'unit', 'norm',...
    'position', [0.425 0.08 0.15 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});
uicontrol('Style','text',...
    'parent', statisticalAnalysisFigureHandle,...
    'String','max:',...
    'HorizontalAlignment', 'left',...
    'fontsize', 10,...
    'backgroundColor','w',...
    'foregroundColor','r',...
    'Enable', 'off',...
    'unit', 'norm',...
    'Position',[0.6 0.08 0.15 0.02],... %[left,bottom,width,height]
    'tag','autoFitDeltaTitle2');
uicontrol('style'        ,'edit',...
    'parent', statisticalAnalysisFigureHandle,...
    'String', '30',...
    'value', 30,...
    'fontsize', 10,...
    'Enable', 'off',...
    'tag', 'autoFitDeltaMax',...
    'unit', 'norm',...
    'position', [0.75 0.08 0.15 0.025],... %[left,bottom,width,height]
    'callback', {@changeValue});


%----------------------------- executing buttons -------------------------%

uicontrol('style'   ,'pushbutton',...
    'parent', statisticalAnalysisFigureHandle,...
    'string', 'Analyze',...
    'unit', 'norm',...
    'enable', 'on',...
    'fontsize', 12,...
    'position',[0.075, 0.02 0.4 0.03],... %[left,bottom,width,height]
    'tag','analyze',...
    'TooltipString', 'Execute analysis (one or more, simultaneously)',...
    'callback', {@analyze});

uicontrol('style'   ,'pushbutton',...
    'parent', statisticalAnalysisFigureHandle,...
    'string', 'Plot results',...
    'unit', 'norm',...
    'enable', 'off',...
    'fontsize', 12,...
    'position',[0.5, 0.02 0.45 0.03],... %[left,bottom,width,height]
    'tag','plotAnalysisResults',...
    'TooltipString', 'Plot graphs of all analyzed objects. Opens new window.',...
    'callback', {@plotResults});

uicontrol('style'   ,'pushbutton',...
    'parent', particleTrackingFigureHandle,...
    'string', 'Run',...
    'unit', 'norm',...
    'fontsize', 12,...
    'position',[0.05, 0.01 0.4 0.03],... %[left,bottom,width,height]
    'tag','run',...
    'callback', {@run, guiHandle, axesHandle});
                  
uicontrol('style'   ,'pushbutton',...
    'parent', particleTrackingFigureHandle,...
    'string', 'Close all',...
    'fontsize', 12,...
    'unit', 'norm',...
    'position',[0.5, 0.01 0.4 0.03],... %[left,bottom,width,height]
    'tag','close',...
    'callback', {@closepushbutton, guiHandle});


%-------------------------------------------------------------------------%
%-------------------------------- call backs -----------------------------%
%-------------------------------------------------------------------------%

function [] = autoFit (calling_button, eventData, Handle1, Handle2, Handle3, Handle4, Handle5, Handle6, Handle7, Handle8)

if get(calling_button, 'value') == 1
    set(findobj('tag', Handle1), 'Enable', 'on');
    set(findobj('tag', Handle2), 'Enable', 'on');
    set(findobj('tag', Handle3), 'Enable', 'on');
    set(findobj('tag', Handle4), 'Enable', 'on');
    set(findobj('tag', Handle5), 'Enable', 'on');
    set(findobj('tag', Handle6), 'Enable', 'on');
    set(findobj('tag', Handle7), 'Enable', 'on');
    set(findobj('tag', Handle8), 'Enable', 'on');
else
    set(findobj('tag', Handle1), 'Enable', 'off');
    set(findobj('tag', Handle2), 'Enable', 'off');
    set(findobj('tag', Handle3), 'Enable', 'off');
    set(findobj('tag', Handle4), 'Enable', 'off');
    set(findobj('tag', Handle5), 'Enable', 'off');
    set(findobj('tag', Handle6), 'Enable', 'off');
    set(findobj('tag', Handle7), 'Enable', 'off');
    set(findobj('tag', Handle8), 'Enable', 'off');
end
end

function [] = setWarning (calling_button, eventData, warning)
%sets a warning to red if checked
if get(calling_button, 'value') == 1
    set(findobj('tag', warning), 'Enable', 'on');
else
    set(findobj('tag', warning), 'Enable', 'off');
end
end


function [] = Zoom (calling_button, eventData, checkbox, fig, status)
%allows the user to zoom in on axes
if get(findobj('tag', checkbox), 'value') == 1
    zoom(fig, status);
else
    zoom(fig, 'out');
    zoom(fig, 'off');
end
end
    
function [] = toggle (calling_button, eventData, individualTag, alignedTag, Handle1, Handle2, Handle3, Handle4, Handle5, Handle6, Handle7, Handle8)
%sets the other checkbox to be checked or not depending the calling_button
%checkbox
alignedTagHandle = findobj('tag', alignedTag);
individualTagHandle = findobj('tag', individualTag);
enable = get(alignedTagHandle, 'Enable');
if strcmp(enable, 'on') == 1
    if strcmp(get(calling_button, 'tag'),individualTag) == 1
        if get(individualTagHandle, 'value') == 1
            set(alignedTagHandle, 'value', 0);
            set(findobj('tag', 'autoFitSigmoid'), 'Enable', 'off', 'Value', 0);
            set(findobj('tag', Handle1), 'Enable', 'off');
            set(findobj('tag', Handle2), 'Enable', 'off');
            set(findobj('tag', Handle3), 'Enable', 'off');
            set(findobj('tag', Handle4), 'Enable', 'off');
            set(findobj('tag', Handle5), 'Enable', 'off');
            set(findobj('tag', Handle6), 'Enable', 'off');
            set(findobj('tag', Handle7), 'Enable', 'off');
            set(findobj('tag', Handle8), 'Enable', 'off');
        else
            set(alignedTagHandle, 'value', 1);
            set(findobj('tag', 'autoFitSigmoid'), 'Enable', 'on');
        end
    elseif strcmp(get(calling_button, 'tag'),alignedTag) == 1
        if get(alignedTagHandle, 'value') == 1
            set(individualTagHandle, 'value', 0);
            set(findobj('tag', 'autoFitSigmoid'), 'Enable', 'on');
        else
            set(individualTagHandle, 'value', 1);
            set(findobj('tag', 'autoFitSigmoid'), 'Enable', 'off', 'Value', 0);
            set(findobj('tag', Handle1), 'Enable', 'off');
            set(findobj('tag', Handle2), 'Enable', 'off');
            set(findobj('tag', Handle3), 'Enable', 'off');
            set(findobj('tag', Handle4), 'Enable', 'off');
            set(findobj('tag', Handle5), 'Enable', 'off');
            set(findobj('tag', Handle6), 'Enable', 'off');
            set(findobj('tag', Handle7), 'Enable', 'off');
            set(findobj('tag', Handle8), 'Enable', 'off');
        end
        
    end
else
    set(individualTagHandle, 'value', 1);
end

end
    
function [] = showAll (calling_button, eventData, table)
    %either shows all tracks or shows none
    tableHandle = findobj('tag', table);
    tableData = get(tableHandle, 'Data');
    rows = size(tableData);
    rows = rows(1);
    if get(calling_button, 'value') == 1
        tableData(:,2) = num2cell(true(rows, 1));
    else
        tableData(:,2) = num2cell(false(rows, 1));
    end
    set(tableHandle, 'Data', tableData);
end


function [] = changeImage (calling_button, eventData, axesHandle)
%lets the user move slider and image time point
sliderHandle = findobj('tag', 'timePointSlider');
sliderValue = get(sliderHandle, 'value');

%change text to show current time point
timePointHandle = findobj('tag', 'timePoint');
sliderMax = get(sliderHandle, 'max');
set(timePointHandle, 'string', ['Time Point: '  num2str(round(sliderValue)) ' / ' num2str(sliderMax)]);

%find which channels the user wants to present
showChannel1Handle = findobj('tag','chooseShowChannel1');
showChannel1 = get(showChannel1Handle, 'value');
showChannel2Handle = findobj('tag','chooseShowChannel2');
showChannel2 = get(showChannel2Handle, 'value');
showChannel3Handle = findobj('tag','chooseShowChannel3');
showChannel3 = get(showChannel3Handle, 'value');
showChannel4Handle = findobj('tag','chooseShowChannel4');
showChannel4 = get(showChannel4Handle, 'value');    

%if the user wants to show a channel find the image
imageMatrixVector = cell(1,4);
colorVector = cell(1,4);
%create saver matrix with names to be used for plotTracks
show = cell(1,3);
%first find red, then green, then blue
if showChannel3 == 1
Channel3Handle = findobj('tag','showChannel3');
imageMatrixName3 = get(Channel3Handle,'string');
show{3} = imageMatrixName3;
color = 'r';
%find data set
data = evalin('base',imageMatrixName3);
%save data set
imageMatrixVector{1} = data;
colorVector{1} = color;
end
if showChannel2 == 1
Channel2Handle = findobj('tag','showChannel2');
imageMatrixName2 = get(Channel2Handle,'string');
show{2} = imageMatrixName2;
color = 'g';
%find data set
data = evalin('base',imageMatrixName2);
%save data set
imageMatrixVector{2} = data;
colorVector{2} = color;
end
if showChannel1 == 1
Channel1Handle = findobj('tag','showChannel1');
imageMatrixName1 = get(Channel1Handle,'string');
show{1} = imageMatrixName1;
color = 'b';
%find data set
data = evalin('base',imageMatrixName1);
%save data set
imageMatrixVector{3} = data;
colorVector{3} = color;
end
if showChannel4 == 1
Channel4Handle = findobj('tag','showChannel4');
imageMatrixName4 = get(Channel4Handle,'string');
color = 'w';
%find data set
data = evalin('base',imageMatrixName4);
%save data set
imageMatrixVector{4} = data;
colorVector{4} = color;
end

%find which channels the user tracked
tracksVector = cell(2,3);

chooseChannel1Handle = findobj('tag','chooseChannel1');
chooseChannel1 = get(chooseChannel1Handle, 'value');
chooseChannel2Handle = findobj('tag','chooseChannel2');
chooseChannel2 = get(chooseChannel2Handle, 'value');
chooseChannel3Handle = findobj('tag','chooseChannel3');
chooseChannel3 = get(chooseChannel3Handle, 'value');

if chooseChannel1 == 1
Channel1Handle = findobj('tag','Channel1');
imageMatrixName = get(Channel1Handle,'string');
imageMatrixName = ['finalTracks_' imageMatrixName];
%find data set
data = evalin('base',imageMatrixName);
%save data set
tracksVector{1,1} = data;
tracksVector{2,1} = imageMatrixName;
end
if chooseChannel2 == 1
Channel2Handle = findobj('tag','Channel2');
imageMatrixName = get(Channel2Handle,'string');
imageMatrixName = ['finalTracks_' imageMatrixName];
%find data set
data = evalin('base',imageMatrixName);
%save data set
tracksVector{1,2} = data;
tracksVector{2,2} = imageMatrixName;
end
if chooseChannel3 == 1
Channel3Handle = findobj('tag','Channel3');
imageMatrixName = get(Channel3Handle,'string');
imageMatrixName = ['finalTracks_' imageMatrixName];
%find data set
data = evalin('base',imageMatrixName);
%save data set
tracksVector{1,3} = data;
tracksVector{2,3} = imageMatrixName;
end

if isempty(find(~cellfun(@isempty,imageMatrixVector)) == 1) == 1
    %this deals with unclicking a check box but still prompting a callback
    cla(axesHandle, 'reset');
    set(axesHandle, 'color', 'k');
    set(axesHandle,'XColor','w', 'xtick',[]);
    set(axesHandle,'YColor','w', 'ytick',[]);
else
    showImage(imageMatrixVector, round(sliderValue), colorVector, axesHandle);
    %creates gray scale images of a time point and presents them 
    
    color = 'm';
    plotTracks(tracksVector, round(sliderValue), axesHandle, show, color);
    %plot tracks over image in axes
    
    alignTracksHandle = findobj('tag', 'toggleAlignedTracks');
    clicked = get(alignTracksHandle, 'Value');
    if clicked == 1
        tracksVector = cell(2,1);
        finalAlignedTracks = evalin('base','finalAlignedTracks');
        tracksVector{1,1} = finalAlignedTracks;
        tracksVector{2,1} = 'Aligned_tracks';
        show = tracksVector(2,1);
        color = 'y';
        plotTracks(tracksVector, round(sliderValue), axesHandle, show, color);
    end
    %plot aligned tracks over image in axes
    
end

end

function [] = changeValue (calling_button, eventData)
%Clears the sequence from edit text box and allows user input.

userInput = get(calling_button, 'String');
if isempty(userInput) == 1
    userInput = '0';
    set(calling_button, 'String', userInput);
end
userValue = str2double(userInput);
set(calling_button, 'value', userValue);

end

function [] =  chooseChannel(calling_button, eventData, tag)
%lets the user choose a channel and input its name

checked = get(calling_button, 'value');
handle = findobj('tag', tag);
if checked == 1
set(handle, 'Enable', 'on');
else
set(handle, 'Enable', 'off');   
end   

end


%-------------------- statistical analysis call backs --------------------%

function [] =  chooseSum(calling_button, eventData)
%lets the user choose to sum the pixels around the object


handleXY = findobj('tag','sumPixelsXY');
handleXYTitle = findobj('tag','sumPixelsXYTitle');
handleZ = findobj('tag','sumPixelsZ');
handleZTitle = findobj('tag','sumPixelsZTitle');

checked = get(calling_button, 'value');
if checked == 1
set(handleXY, 'Enable', 'on');
set(handleXYTitle, 'Enable', 'on');
set(handleZ, 'Enable', 'on');
set(handleZTitle, 'Enable', 'on');
else
set(handleXY, 'Enable', 'off');
set(handleXYTitle, 'Enable', 'off');
set(handleZ, 'Enable', 'off');
set(handleZTitle, 'Enable', 'off');
end

end

function [] =  selectCube(calling_button, eventData)
%lets the user analyze tracks within a selection cube

selectionPixelsXYTitleHandle = findobj('tag', 'selectionPixelsXYTitle');
selectionPixelsXYHandle = findobj('tag', 'selectionPixelsXY');
selectionPixelsZTitleHandle = findobj('tag', 'selectionPixelsZTitle');
selectionPixelsZHandle = findobj('tag', 'selectionPixelsZ');

sumBrightestPixelsTitleHandle = findobj('tag', 'sumBrightestPixelsTitle');
sumBrightestPixelsHandle = findobj('tag', 'sumBrightestPixels');
numberOfBrightestPixelsTitleHandle = findobj('tag','numberOfBrightestPixelsTitle');
numberOfBrightestPixelsHandle = findobj('tag','numberOfBrightestPixels');

sumPixelsAboveMedianTitleHandle = findobj('tag', 'sumPixelsAboveMedianTitle');
sumPixelsAboveMedianHandle = findobj('tag', 'sumPixelsAboveMedian');
percentAboveMedianTitleHandle = findobj('tag','percentAboveMedianTitle');
percentAboveMedianHandle = findobj('tag','percentAboveMedian');


sumPixelsCloseToMaxTitleHandle = findobj('tag', 'sumPixelsCloseToMaxTitle');
sumPixelsCloseToMaxHandle = findobj('tag', 'sumPixelsCloseToMax');
percentOfMaxTitleHandle = findobj('tag','percentOfMaxTitle');
percentOfMaxHandle = findobj('tag','percentOfMax');

checked = get(calling_button, 'value');
if checked == 1

set(selectionPixelsXYTitleHandle, 'Enable', 'on');
set(selectionPixelsXYHandle, 'Enable', 'on');
set(selectionPixelsZTitleHandle, 'Enable', 'on');
set(selectionPixelsZHandle, 'Enable', 'on');

set(sumBrightestPixelsTitleHandle, 'Enable', 'on');
set(sumBrightestPixelsHandle, 'Enable', 'on');

set(sumPixelsAboveMedianTitleHandle, 'Enable', 'on');
set(sumPixelsAboveMedianHandle, 'Enable', 'on');

set(sumPixelsCloseToMaxTitleHandle, 'Enable', 'on');
set(sumPixelsCloseToMaxHandle, 'Enable', 'on');

else

set(selectionPixelsXYTitleHandle, 'Enable', 'off');
set(selectionPixelsXYHandle, 'Enable', 'off');
set(selectionPixelsZTitleHandle, 'Enable', 'off');
set(selectionPixelsZHandle, 'Enable', 'off');

set(sumBrightestPixelsTitleHandle, 'Enable', 'off');
set(sumBrightestPixelsHandle, 'Enable', 'off', 'value', 0);
set(numberOfBrightestPixelsTitleHandle, 'Enable', 'of');
set(numberOfBrightestPixelsHandle, 'Enable', 'of');

set(sumPixelsAboveMedianTitleHandle, 'Enable', 'off');
set(sumPixelsAboveMedianHandle, 'Enable', 'off', 'value', 0);
set(percentAboveMedianTitleHandle, 'Enable', 'off');
set(percentAboveMedianHandle, 'Enable', 'off');

set(sumPixelsCloseToMaxTitleHandle, 'Enable', 'off');
set(sumPixelsCloseToMaxHandle, 'Enable', 'off', 'value', 0);
set(percentOfMaxTitleHandle, 'Enable', 'off');
set(percentOfMaxHandle, 'Enable', 'off');
    
end

end

function [] =  selectBrightestPixels(calling_button, eventData)
%lets the user choose to sum a number of maximum intensity picels around
%local maximum

numberOfBrightestPixelsTitleHandle = findobj('tag','numberOfBrightestPixelsTitle');
numberOfBrightestPixelsHandle = findobj('tag','numberOfBrightestPixels');

checked = get(calling_button, 'value');
if checked == 1
set(numberOfBrightestPixelsTitleHandle, 'Enable', 'on');
set(numberOfBrightestPixelsHandle, 'Enable', 'on');
else
set(numberOfBrightestPixelsTitleHandle, 'Enable', 'off');
set(numberOfBrightestPixelsHandle, 'Enable', 'off');
end

end

function [] =  sumPixelsAboveMedian(calling_button, eventData)
%lets user to choose to quantify all pixels that are above a certain
%percent of the median intensity

percentAboveMedianTitleHandle = findobj('tag','percentAboveMedianTitle');
percentAboveMedianHandle = findobj('tag','percentAboveMedian');

checked = get(calling_button, 'value');
if checked == 1
set(percentAboveMedianTitleHandle, 'Enable', 'on');
set(percentAboveMedianHandle, 'Enable', 'on');
else
set(percentAboveMedianTitleHandle, 'Enable', 'off');
set(percentAboveMedianHandle, 'Enable', 'off');
end

end

function [] =  sumPixelsCloseToMax(calling_button, eventData)
%lets user to choose to quantify all pixels that are above a certain
%percent of the max intensity

percentOfMaxTitleHandle = findobj('tag','percentOfMaxTitle');
percentOfMaxHandle = findobj('tag','percentOfMax');

checked = get(calling_button, 'value');
if checked == 1
set(percentOfMaxTitleHandle, 'Enable', 'on');
set(percentOfMaxHandle, 'Enable', 'on');
else
set(percentOfMaxTitleHandle, 'Enable', 'off');
set(percentOfMaxHandle, 'Enable', 'off');
end

end


function [] =  subtractBackground(calling_button, eventData, maxX, maxY, xFrom, xTo, xStart, xEnd, yFrom, yTo, yStart, yEnd)
%lets the user to choose an area in the image for background subtraction
    
    recAxes = findobj(findobj('tag', 'figure'),'type','axes');
    
    if get(calling_button, 'Value') == 1
    xLim = floor(get(recAxes, 'xlim'));
    xString = ['/ ' num2str(xLim(2))];
    yLim = floor(get(recAxes, 'ylim'));
    yString = ['/ ' num2str(yLim(2))];
    set(findobj('tag', maxX), 'Enable', 'on', 'Visible', 'on', 'string', xString)
    set(findobj('tag', maxY), 'Enable', 'on', 'Visible', 'on', 'string', yString)
    
    set(findobj('tag', xFrom), 'Enable', 'on')
    set(findobj('tag', xTo), 'Enable', 'on')
    set(findobj('tag', xStart), 'Enable', 'on')
    set(findobj('tag', xStart), 'Enable', 'on', 'string', num2str((xLim(2))/3), 'value', (xLim(2))/3);
    set(findobj('tag', xEnd), 'Enable', 'on', 'string', num2str((xLim(2)*2)/3), 'value', ((xLim(2)*2)/3))
    width = get(findobj('tag', xEnd), 'Value');
    set(findobj('tag', yFrom), 'Enable', 'on')
    set(findobj('tag', yTo), 'Enable', 'on')
    set(findobj('tag', yStart), 'Enable', 'on', 'string', num2str((yLim(2))/3), 'value', (yLim(2))/3);
    set(findobj('tag', yEnd), 'Enable', 'on', 'string', num2str((yLim(2)*2)/3), 'value', ((yLim(2)*2)/3))
    height = get(findobj('tag', yEnd), 'Value');
    
    axes(recAxes);
    %change current axis. Couldn't force rectangle into recAxes by playing
    %with properties
    rectangle('Position', [width/2 height/2 width/2 height/2], 'EdgeColor', 'w');
    
    else
        
    set(findobj('tag', maxX), 'Enable', 'off', 'Visible', 'off')
    set(findobj('tag', maxY), 'Enable', 'off', 'Visible', 'off')
    set(findobj('tag', xFrom), 'Enable', 'off')
    set(findobj('tag', xTo), 'Enable', 'off')
    set(findobj('tag', xStart), 'Enable', 'off')
    set(findobj('tag', xEnd), 'Enable', 'off')
    set(findobj('tag', yFrom), 'Enable', 'off')
    set(findobj('tag', yTo), 'Enable', 'off')
    set(findobj('tag', yStart), 'Enable', 'off')
    set(findobj('tag', yEnd), 'Enable', 'off')
    
    refresh (calling_button, eventData, recAxes);
    delete(findobj(findobj('tag', 'statisticalAnalysisFigure'),'type','axes'));
        
    end
    
end


function [] =  chooseGaussian(calling_button, eventData)
%lets the user choose to sum the pixels around the object


handleXY = findobj('tag','gaussianFitXY');
handleXYTitle = findobj('tag','gaussianFitXYTitle');
handleZ = findobj('tag','gaussianFitZ');
handleZTitle = findobj('tag','gaussianFitZTitle');


checked = get(calling_button, 'value');
if checked == 1
set(handleXY, 'Enable', 'on');
set(handleXYTitle, 'Enable', 'on');
set(handleZ, 'Enable', 'on');
set(handleZTitle, 'Enable', 'on');
else
set(handleXY, 'Enable', 'off');
set(handleXYTitle, 'Enable', 'off');
set(handleZ, 'Enable', 'off');
set(handleZTitle, 'Enable', 'off');
end

end

%-------------------------- executing call backs -------------------------%

function [] = refresh (calling_button, eventData, axesHandle)
    cla(axesHandle);
    changeImage(calling_button, eventData, axesHandle);
end
    
function [] = run (calling_button, eventData, guiHandle, axesHandle)
%Runs the program.
%profile on (shows amount of time take, if activated);

waitBar = msgbox('You can go make yourself some coffee. I will do the work. Alone. In the dark.','Program is running');
%notify the user the program is running

%find all user inputs for particle tracking
xyRadiusHandle = findobj('tag','regionalMaximumRadiusXY');
maskXY = get(xyRadiusHandle,'value');
if maskXY < 1 || mod(maskXY,1) ~= 0
    close(waitBar);
    errordlg('XY radius has to be a positive integer', 'False initial parametres');
    error('XY radius has to be a positive integer');
end
%look up user input for x and y radius for local maximum

zRadiusHandle = findobj('tag','regionalMaximumRadiusZ');
maskZ = get(zRadiusHandle,'value');
if maskZ < 0 || mod(maskZ,1) ~= 0
    close(waitBar);
    errordlg('Z radius has to be an integer greater than or equal to 0', 'False initial parametres');
    error('Z radius has to be an integer greater than or equal to 0');
end
%look up user input for z radius for local maximum

thresholdHandle = findobj('tag','threshold');
threshold = get(thresholdHandle,'value');
if threshold < 0
    close(waitBar);
    errordlg('Threshold has to be greater than or equal to 0', 'False initial parametres');
    error('Threshold has to be greater than or equal to 0');
end
%look up user input for intensity threshold

useChannel1Handle = findobj('tag','chooseChannel1');
useChannel1 = get(useChannel1Handle, 'value');
useChannel2Handle = findobj('tag','chooseChannel2');
useChannel2 = get(useChannel2Handle, 'value');
useChannel3Handle = findobj('tag','chooseChannel3');
useChannel3 = get(useChannel3Handle, 'value');
%look up input image channles from user

maxLinkingDistanceHandle = findobj('tag','maxLinkingDistance');
maxLinkingDistance = get(maxLinkingDistanceHandle, 'value');
if maxLinkingDistance < 0 || mod(maxLinkingDistance,1) ~= 0
    close(waitBar);
    errordlg('Max linking distance has to be an integer greater than or equal to 0', 'False initial parametres');
    error('Max linking distance has to be an integer greater than or equal to 0');
end
%look up user input for maximum linking distance for two particles

maxGapHandle = findobj('tag','maxLinkingGap');
maxGap = get(maxGapHandle, 'value');
if maxGap < 0 || mod(maxGap,1) ~= 0
    close(waitBar);
    errordlg('Max gap has to be an integer greater than or equal to 0', 'False initial parametres');
    error('Max gap has to be an integer greater than or equal to 0');
end
%look up user input for max acceptable time gap

minimumTrackLengthHandle = findobj('tag','minTrackLength');
minimumTrackLength = get(minimumTrackLengthHandle, 'value');
if minimumTrackLength < 0 || mod(minimumTrackLength,1) ~= 0
    close(waitBar);
    errordlg('Minimal track length has to be an integer greater than or equal to 0', 'False initial parametres');
    error('Minimal track length has to be an integer greater than or equal to 0');
end
%look up user input for minimum acceptable track length

pixelSizeHandle = findobj('tag','pixelSize');
pixelSize = get(pixelSizeHandle, 'value');
if (pixelSize > 0) == 0
    close(waitBar);
    errordlg('Pixel size has to be greater than 0', 'False initial parametres');
    error('Pixel size has to be greater than 0');
end
%look up user input for pixel size

stepSizeHandle = findobj('tag','stepSize');
stepSize = get(stepSizeHandle, 'value');
if (stepSize > 0) == 0
    close(waitBar);
    errordlg('Step size has to be greater than 0', 'False initial parametres');
    error('Step size has to be greater than 0');
end
%look up user input for step size

maxNoOfParticlesHandle = findobj('tag','maxNoOfParticles');
maxNoOfParticles = get(maxNoOfParticlesHandle, 'value');
if maxNoOfParticles < 1 || mod(maxNoOfParticles,1) ~= 0
    close(waitBar);
    errordlg('Max number of particles has to be a positive integer', 'False initial parametres');
    error('Max number of particles has to be a positive integer');
end
%look up user input for maximum number of particles in a single time point

%find input channels
imageMatrixVector = cell(1,3);

if useChannel1 == 1
Channel1Handle = findobj('tag','Channel1');
imageMatrixName = get(Channel1Handle,'string');
if any(strcmp(evalin('base','who'),imageMatrixName)) == 0
    close(waitBar);
    errordlg('Channel not found. Please match channel name to an existing file or variable', 'Channel selection error');
    error('Channel not found. Please match channel name to an existing file or variable');
end
imageMatrixVector{1} = imageMatrixName;
end
if useChannel2 == 1
Channel2Handle = findobj('tag','Channel2');
imageMatrixName = get(Channel2Handle,'string');
if any(strcmp(evalin('base','who'),imageMatrixName)) == 0
    close(waitBar);
    errordlg('Channel not found. Please match channel name to an existing file or variable', 'Channel selection error');
    error('Channel not found. Please match channel name to an existing file or variable');
end
imageMatrixVector{2} = imageMatrixName;
end
if useChannel3 == 1
Channel3Handle = findobj('tag','Channel3');
imageMatrixName = get(Channel3Handle,'string');
if any(strcmp(evalin('base','who'),imageMatrixName)) == 0
    close(waitBar);
    errordlg('Channel not found. Please match channel name to an existing file or variable', 'Channel selection error');
    error('Channel not found. Please match channel name to an existing file or variable');
end
imageMatrixVector{3} = imageMatrixName;
end

channels2use = find(~cellfun(@isempty,imageMatrixVector));
numberOfChannels = numel(channels2use);
timePoints = [];

%run analysis for each channel
for i = 1:numberOfChannels

index = channels2use(i);
imageMatrixName = imageMatrixVector{index};
imageMatrix = evalin('base',imageMatrixName);
timePoints = size(imageMatrix);
timePoints = timePoints(4);

finalTracks = dotQuant( imageMatrix, maskXY, maskZ, maxLinkingDistance, maxGap, minimumTrackLength, pixelSize, stepSize, maxNoOfParticles, threshold );
trackName = ['finalTracks_' imageMatrixName];
assignin('base', trackName, finalTracks);
%save final tracks globally

%set tracks to table data to allow user to show or hide tracks
dims = ndims(finalTracks);
tableName = ['tracksTable' num2str(i)];
tableHandle = findobj('tag', tableName);
if dims == 2
    set (tableHandle, 'data', {1 true});
else
    numberTracks = size(finalTracks);
    iVector = 1:numberTracks(3);
    iVector = iVector';
    trueVector = true(numberTracks(3),1);
    data = [num2cell(iVector) num2cell(trueVector)];
    set (tableHandle, 'data', data);
end
set (tableHandle, 'Visible', 'on');
titleName = ['showTrack' num2str(i) 'Title'];
tableTitleHandle = findobj('tag', titleName);
title = ['Show all ' imageMatrixName ' tracks'];
set(tableTitleHandle, 'String', title);
set(tableTitleHandle, 'Visible', 'on');
checkboxName = ['showAllTracks' num2str(i)];
checkboxHandle = findobj('tag', checkboxName);
set(checkboxHandle, 'Visible', 'on');
end
    
%allow slider maneuvering (slider has to stay inactive untill there's
%something to present)
sliderHandle = findobj('tag', 'timePointSlider');
set(sliderHandle, 'max', timePoints);
set(sliderHandle, 'SliderStep',...
    [1/timePoints , 10/timePoints ]);
set(sliderHandle, 'Enable', 'on'); 
timePointHandle = findobj('tag', 'timePoint');
set(timePointHandle, 'string', ['Time Point: '  '1' ' / ' num2str(timePoints)]);

figHandle = findobj('tag', 'figure');
set(figHandle, 'Visible', 'on');
analysisFigHandle = findobj('tag', 'statisticalAnalysisFigure');
set(analysisFigHandle, 'Visible', 'on');

alignTracksHandle = findobj('tag', 'alignTracks');
set(alignTracksHandle, 'Enable', 'on'); 

close(waitBar);

%profile viewer
end

end

function [] =  analyze(calling_button, eventData)
%runs the data analysis

box = msgbox('Analyzing data and preparing files. Go treat yourself to something nice. You deserve it after all this hard work.','Program is running');

%check which analyses protocol to perform
sumPixelsHandle = findobj('tag','chooseSumPixels');
sumPixels = get(sumPixelsHandle, 'value');
%check for sum of neighboring pixels
selectCubeHandle = findobj('tag','selectCube');
selectCube = get(selectCubeHandle, 'value');
%check for selection cube
fitGaussianHandle = findobj('tag','chooseFitGaussian');
fitGaussian = get(fitGaussianHandle, 'value');
%check for gaussian fit

individualHandle = findobj('tag','individualAnalysis');
individualAnalysis = get(individualHandle, 'value');
alignedHandle = findobj('tag','alignedAnalysis');
alignedAnalysis = get(alignedHandle, 'value');
%check if user wishes to analyze aligned tracks or individual tracks

%create saver matrix
tracks = cell(3,3);

if individualAnalysis == 1
%look up input image channles from user
useChannel1Handle = findobj('tag','chooseChannel1');
useChannel1 = get(useChannel1Handle, 'value');
useChannel2Handle = findobj('tag','chooseChannel2');
useChannel2 = get(useChannel2Handle, 'value');
useChannel3Handle = findobj('tag','chooseChannel3');
useChannel3 = get(useChannel3Handle, 'value');

if useChannel1 == 1
    channel1Handle = findobj('tag','Channel1');
    dataName = get(channel1Handle,'string');
    imageMatrix = evalin('base',dataName);
    tracks{1,1} = imageMatrix;
    %find intensities matrix
    finalTracks = evalin('base',['finalTracks_' dataName]);
    tracks{2,1} = finalTracks;
    tracks{3,1} = dataName;
    %find tracks
end
if useChannel2 == 1
    channel2Handle = findobj('tag','Channel2');
    dataName = get(channel2Handle,'string');
    imageMatrix = evalin('base',dataName);
    tracks{1,2} = imageMatrix;
    %find intensities matrix
    finalTracks = evalin('base',['finalTracks_' dataName]);
    tracks{2,2} = finalTracks;
    tracks{3,2} = dataName;
    %find tracks
end
if useChannel3 == 1
    channel3Handle = findobj('tag','Channel3');
    dataName = get(channel3Handle,'string');
    imageMatrix = evalin('base',dataName);
    tracks{1,3} = imageMatrix;
    %find intensities matrix
    finalTracks = evalin('base',['finalTracks_' dataName]);
    tracks{2,3} = finalTracks;
    tracks{3,3} = dataName;
    %find tracks
end

elseif alignedAnalysis == 1 
    
alignedTracksNames = evalin('base','alignedTracksNames');
name1 = strrep(alignedTracksNames(1), 'finalTracks_', '');
tracks(3,1) = alignedTracksNames(1);
image1 = evalin('base', name1{1});
tracks{1,1} = image1;
name2 = strrep(alignedTracksNames(2), 'finalTracks_', '');
tracks(3,2) = alignedTracksNames(2);
image2 = evalin('base', name2{1});
tracks{1,2} = image2;
%save names of channels and the original images
alignedTracks = evalin('base','finalAlignedTracks');
tracks{2,1} = alignedTracks(:,5:8,:);
tracks{2,2} = alignedTracks(:,9:12,:);
%save individual aligned tracks

resultNames = cell(1,2);
resultNames_sumPixels = resultNames;
resultNames_sumBrightest = resultNames;
resultNames_sumPixelsAboveMedian = resultNames;
resultNames_sumPixelsCloseToMax = resultNames;
resultNames_fitGaussian = resultNames;

fitSigmoid = get(findobj('tag', 'autoFitSigmoid'), 'Value');
if  fitSigmoid == 1
    
    minWindow = get(findobj('tag', 'autoFitWindowMin'), 'value');
    maxWindow = get(findobj('tag', 'autoFitWindowMax'), 'value');
    minDeltaT = get(findobj('tag', 'autoFitDeltaMin'), 'value');
    maxDeltaT = get(findobj('tag', 'autoFitDeltaMax'), 'value');
    
end

end

indices = find(~cellfun(@isempty,tracks(1,:)));
numberOfTracks = numel(indices);

for i = 1:numberOfTracks
    
    index = indices(i);
    imageMatrix = tracks{1,index};
    finalTracks = tracks{2,index};
    channelName = tracks{3,index};
    %find tracks and channels
    
    %find which analysis protocol the user chose
    if sumPixels == 1
       handleXY = findobj('tag','sumPixelsXY');
       handleZ = findobj('tag','sumPixelsZ');
       xyPixels = get(handleXY, 'value');
       zPixels = get(handleZ, 'value');
       %get user defined variables
       flag = 2;
       resultName_sumPixels = [channelName '_sumNeighbors'];
       sumTrack(resultName_sumPixels, imageMatrix, finalTracks, xyPixels, zPixels, flag)
       %perform data analysis
       if alignedAnalysis == 1
             if i == 2
                 resultNames_sumPixels{2} = resultName_sumPixels;
                 if fitSigmoid == 1
                    [greenFit, redFit] = autoYeastAnalyzer(resultNames_sumPixels, minWindow, maxWindow, minDeltaT, maxDeltaT);
                    writeData(resultNames_sumPixels, greenFit, redFit);
                 else
                    writeData(resultNames_sumPixels);
                 end
             else
                 resultNames_sumPixels{1} = resultName_sumPixels;
             end
       else
            writeData(resultName_sumPixels);
            %save data to file
        end
    end

    if selectCube == 1

        selectionPixelsXYHandle = findobj('tag', 'selectionPixelsXY');
        maskXY = get(selectionPixelsXYHandle, 'value');
        selectionPixelsZHandle = findobj('tag', 'selectionPixelsZ');
        maskZ = get(selectionPixelsZHandle, 'value');
        %find size of selection cube

        %what protocol did the user choose
        sumBrightestPixelsHandle = findobj('tag', 'sumBrightestPixels');
        sumBrightest = get(sumBrightestPixelsHandle, 'value');
        if sumBrightest == 1
            numberOfBrightestPixelsHandle = findobj('tag', 'numberOfBrightestPixels'); 
            pixels = get(numberOfBrightestPixelsHandle, 'value');
            flag = 3;
            resultName_sumBrightest = [channelName '_brightestNeighbors'];
            sumTrack(resultName_sumBrightest, imageMatrix, finalTracks, maskXY, maskZ, flag, pixels)
            if alignedAnalysis == 1
                 if i == 2
                    resultNames_sumBrightest{2} = resultName_sumBrightest;
                    if fitSigmoid == 1
                        [greenFit, redFit] = autoYeastAnalyzer(resultNames_sumBrightest, minWindow, maxWindow, minDeltaT, maxDeltaT);
                        writeData(resultNames_sumBrightest, greenFit, redFit);
                    else
                        writeData(resultNames_sumBrightest);
                    end    
                 else
                    resultNames_sumBrightest{1} = resultName_sumBrightest;
                 end
            else
                writeData(resultName_sumBrightest);
                %save data to file
            end
        end
    
        sumPixelsAboveMedianHandle = findobj('tag', 'sumPixelsAboveMedian');
        sumPixelsAboveMedian = get(sumPixelsAboveMedianHandle, 'value');
        if sumPixelsAboveMedian == 1
            percentAboveMedianHandle = findobj('tag', 'percentAboveMedian'); 
            percentAboveMedian = get(percentAboveMedianHandle, 'value');
            flag = 4;
            resultName_sumPixelsAboveMedian = [channelName '_aboveMedian'];
            sumTrack(resultName_sumPixelsAboveMedian, imageMatrix, finalTracks, maskXY, maskZ, flag, percentAboveMedian)
            if alignedAnalysis == 1
                if i == 2
                    resultNames_sumPixelsAboveMedian{2} = resultName_sumPixelsAboveMedian;
                    if fitSigmoid == 1
                        [greenFit, redFit] = autoYeastAnalyzer(resultNames_sumPixelsAboveMedian, minWindow, maxWindow, minDeltaT, maxDeltaT);
                        writeData(resultNames_sumPixelsAboveMedian, greenFit, redFit);
                    else
                        writeData(resultNames_sumPixelsAboveMedian);
                    end
                 else
                    resultNames_sumPixelsAboveMedian{1} = resultName_sumPixelsAboveMedian;
                 end
            else
                writeData(resultName_sumPixelsAboveMedian);
                %save data to file
            end      
        end

        sumPixelsCloseToMaxHandle = findobj('tag', 'sumPixelsCloseToMax');
        sumPixelsCloseToMax = get(sumPixelsCloseToMaxHandle, 'value');
        if sumPixelsCloseToMax == 1
             percentOfMaxHandle = findobj('tag', 'percentOfMax'); 
             percentOfMax = get(percentOfMaxHandle, 'value');
             flag = 5;
             resultName_sumPixelsCloseToMax = [channelName '_closeToMax'];
             sumTrack(resultName_sumPixelsCloseToMax, imageMatrix, finalTracks, maskXY, maskZ, flag, percentOfMax)
             if alignedAnalysis == 1
                 if i == 2
                    resultNames_sumPixelsCloseToMax{2} = resultName_sumPixelsCloseToMax;
                    if fitSigmoid == 1
                        [greenFit, redFit] = autoYeastAnalyzer(resultNames_sumPixelsCloseToMax, minWindow, maxWindow, minDeltaT, maxDeltaT);
                        writeData(resultNames_sumPixelsCloseToMax, greenFit, redFit);
                    else
                        writeData(resultNames_sumPixelsCloseToMax);
                    end
                 else
                    resultNames_sumPixelsCloseToMax{1} = resultName_sumPixelsCloseToMax;
                 end
             else
             writeData(resultName_sumPixelsCloseToMax);
             %save data to file
             end
        end

    end

    if fitGaussian == 1
        handleXY = findobj('tag','gaussianFitXY');
        handleZ = findobj('tag','gaussianFitZ');
        xyRange = get(handleXY, 'value');
        zRange = get(handleZ, 'value');

        pixelSizeHandle = findobj('tag','pixelSize');
        pixelSize = get(pixelSizeHandle, 'value');
        %look up user input for pixel size
        stepSizeHandle = findobj('tag','stepSize');
        stepSize = get(stepSizeHandle, 'value');
        %look up user input for step size
        %get user defined variables

        resultName_fitGaussian = [channelName '_gaussian'];
        sumTrack(resultName_fitGaussian, imageMatrix, finalTracks, xyRange, zRange, flag, pixelSize, stepSize)
        if alignedAnalysis == 1
             if i == 2
                resultNames_fitGaussian{2} = resultName_fitGaussian;
                if fitSigmoid == 1
                    [greenFit, redFit] = autoYeastAnalyzer(resultNames_fitGaussian, minWindow, maxWindow, minDeltaT, maxDeltaT);
                    writeData(resultNames_fitGaussian, greenFit, redFit);
                else
                    writeData(resultNames_fitGaussian);
                end
             else
                resultNames_fitGaussian{1} = resultName_fitGaussian;
             end
        else
        writeData(resultName_fitGaussian);
        %save data to file
        end
    end

end

close(box);

%find text files in current folder
currentFolder = pwd;
title = 'Choose folder to save analysis files';
if ismac
    h = helpdlg(title, 'File saver');
end
targetFolder = uigetdir(currentFolder, title);
if ismac
    close(h);
end
files = [currentFolder '/' '*.xlsx'];
folderInfo = dir(files);
fileNames = {folderInfo(:).name};
numberFiles = numel(fileNames);

for i = 1:numberFiles
file = [currentFolder '/' fileNames{i}];
copyfile(file,targetFolder)
end

delete(files);

set(findobj('tag', 'plotAnalysisResults'), 'enable', 'on');

end

function [] =  closepushbutton(calling_button, eventData, FigHandle)
%Closes the main figure (quit button)

close all;
end

%-------------------------------------------------------------------------%
%-------------------------------- graphics -------------------------------%
%-------------------------------------------------------------------------%

function [] = showImage(imageMatrixVector, time, colorVector, axesHandle)
%creates a gray scale maximum projection for a single time point 
%from a 3D time lapse. Does this to all data sets and shows them
%in axes

dataSetsIndices = find(~cellfun('isempty',colorVector));
dataSets = numel(dataSetsIndices);
[y,x,~,~,~] = size(imageMatrixVector{dataSetsIndices(1)});
%find image dimensions
grayMaxImage = zeros(y,x);
%create saver matrix for maximum projection
red = grayMaxImage;
green = grayMaxImage;
blue = grayMaxImage;
gray = ones(y,x);
transparencyMatrix = grayMaxImage;


for i = 1:dataSets
    index = dataSetsIndices(i);
    image = imageMatrixVector{index};
    maximumProjection = max(image(:,:,:,time),[],3);
    grayScaled = mat2gray(maximumProjection);
    %create a gray scale maximum projection
    grayMaxImage(:,:) = grayScaled;
    
    color = colorVector{index};
    if strcmp(color, 'r') == 1
        red = grayMaxImage;
        if get(findobj('Tag', 'enhanceContrastChannel3'), 'Value') == 1
           red = adapthisteq(red);
        end
    elseif strcmp(color, 'g') == 1
        green = grayMaxImage;
        if get(findobj('Tag', 'enhanceContrastChannel2'), 'Value') == 1
           green = adapthisteq(green);
        end
    elseif strcmp(color, 'b') == 1
        blue = grayMaxImage;
        if get(findobj('Tag', 'enhanceContrastChannel1'), 'Value') == 1
           blue = adapthisteq(blue);
        end
    elseif strcmp(color, 'w') == 1
        gray = grayMaxImage;
        if get(findobj('Tag', 'enhanceContrastChannel4'), 'Value') == 1
           gray = adapthisteq(gray);
        end
    end
    
end

    rgbImage = cat(3, red, green, blue);
    imshow(rgbImage, 'Parent', axesHandle);
    hold on;
    dic = imshow(gray, 'Parent', axesHandle);
    set(dic, 'AlphaData', (1-gray));
    if get(findobj('Tag', 'subtractBackground'), 'Value') == 1
    hold on;
    left = get(findobj('Tag', 'subtractBackgroundXstart'), 'Value');
    if left < 1
        set(findobj('Tag', 'subtractBackgroundXstart'), 'Value', 1, 'String', '1');
        left = 1;
    end
    bottom = get(findobj('Tag', 'subtractBackgroundYstart'), 'Value');
    if bottom < 1
        set(findobj('Tag', 'subtractBackgroundYstart'), 'Value', 1, 'String', '1');
        bottom = 1;
    end
    width = get(findobj('Tag', 'subtractBackgroundXend'), 'Value') - left;
    xMax = strsplit(get(findobj('Tag', 'subtractBackgroundXMax'), 'String'),' ');
    xMax = str2double(xMax{2});
    if left+width >= xMax
        set(findobj('Tag', 'subtractBackgroundXend'), 'Value', (xMax-1), 'String', num2str(xMax-1));
        width = xMax - (left+1);
    end
    height = get(findobj('Tag', 'subtractBackgroundYend'), 'Value') - bottom;
    yMax = strsplit(get(findobj('Tag', 'subtractBackgroundYMax'), 'String'),' ');
    yMax = str2double(yMax{2});
    if bottom+height >= yMax
    set(findobj('Tag', 'subtractBackgroundYend'), 'Value', (yMax-1), 'String', num2str(yMax-1));
    height = yMax - (bottom+1);
    end
    
    rectangle('Position', [left bottom width height], 'EdgeColor', 'w');
    end
    
end

function [] = plotTracks(tracks, timePoint, axesHandle, show, color)
%plots tracks over image

%find all channels that require track plotting
indicesTracks = find(~cellfun(@isempty,tracks(1,:)));
indicesShow = find(~cellfun(@isempty,show));
indices = ismember(indicesTracks, indicesShow);
indices = indicesTracks(indices);
tracks2plot = numel(indices);

for i = 1:tracks2plot
    index = indices(1,i);
    channelTracks = tracks{1,index};
tracksInTime = channelTracks(1,4,:)<=timePoint;
%find if there are tracks that have current time point

channelName = show{index};
if strcmp(channelName, 'Aligned_tracks') == 1
tag = 'tracksTable4';
else
tableTitleName = ['Show all ' channelName ' tracks'];
titleHandle = findobj('String', tableTitleName);
tag = get(titleHandle, 'Tag');
tag = strrep(tag, 'Title', '');
tag = strrep(tag, 'showTrack', 'tracksTable');
end
tableHandle = findobj('tag', tag);
tableData = get(tableHandle, 'Data');
tableData = logical(~cellfun(@isempty,(cellfun(@find,tableData(:,2),'UniformOutput', 0))));
%find if there are tracks that the user wishes to show

for x = 1:numel(tableData)
    tracksInTime(1,1,x) = tracksInTime(1,1,x)*tableData(x);
end


%if there are any tracks in the current time point that the user wishes to show 
%plot them up to that time point
if isempty(tracksInTime) == 0 && isempty(find(tracksInTime,3)) == 0   
    
    tracksIndices = find(tracksInTime == 1);
    %which tracks are in current time point
    numberOfTracks = numel(tracksIndices);
    %how many tracks in total are in current time point
    sizeTracks = size(channelTracks);
    if numel(sizeTracks)<3
        colorVector = hsv(1);
    else
    colorVector = hsv(sizeTracks(3));
    end
    for track = 1:numberOfTracks
        %for each track
        
        trackColor = colorVector(track,:);
        %choose color for tracks
        
        currentTrack = tracksIndices(track);
        endRow = find(channelTracks(:,4,currentTrack) == timePoint);
        
        if strcmp(channelName, 'Aligned_tracks') == 1
            iterations = 2;
            column = [5,6;9,10];
        else
            iterations = 1;
            column = [1,2];
        end
        
        for iteration = 1:iterations
        hold(axesHandle,'on')
        scatter(axesHandle, channelTracks(endRow,column(iteration,2),currentTrack), channelTracks(endRow,column(iteration,1), currentTrack),...
        50,...
        'LineWidth',2,...
        'MarkerEdgeColor',color);
        %where to plot, x(2nd column), y(first column), style
        end
        s2 = num2str(currentTrack); %track number
        if strcmp(channelName, 'Aligned_tracks') == 1
        s3 = strcat('Aligned\_track','\_');
        else
        s3 = strcat(channelName,'\_');    
        end
        trackText = strcat(s3,s2);
        %create string for track number
        text( channelTracks(endRow,2,currentTrack), channelTracks(endRow,1,currentTrack),...
            trackText,...
            'FontSize', 12,...
            'HorizontalAlignment', 'left',...
            'VerticalAlignment', 'bottom',...
            'parent', axesHandle,...
            'Color', 'c')
        %add track number reference  
      
        if timePoint > 1
            x = channelTracks(1:endRow,2,currentTrack);
            y = channelTracks(1:endRow,1,currentTrack);
            plot( axesHandle, x, y, ':', 'Color', trackColor, 'LineWidth',2)
            %connect the dots to form a track
        end
    end
end
end

end

%-------------------------------------------------------------------------%
%-------------------------- statistical analysis -------------------------%
%-------------------------------------------------------------------------%

function [] = sumTrack(matrixName, image, tracks, xyPixels, zPixels, flag, threshold, pixelSize, stepSize)
%sums the intensity of each time point for each track
%flag = 2 : sum all neighboring pixels within range
%flag = 3 : sum #n brightest neighboring pixels
%flag = 4 : sum neighbors above median
%flag = 5 : sum neighbors close to max value

inputs = nargin;

imageDimensions = size(image);

dimensions = size(tracks);

if numel(dimensions) == 2
    numberOfTracks = 1;
else
numberOfTracks = dimensions(3);
%find number of tracks
end

tracksSum = cell(numberOfTracks,1);

for track = 1:numberOfTracks
    %analyze track by track
    timePoints = max(find(tracks(:,4,track) ~=0));
    %find last non zero element
    intensities = zeros(timePoints,2);
    %create array the size of the number of actual coordinates
    %one column for intensity the other for time point: [intensity time]
    for time = 1:timePoints
        %calculate intensity for each time point
        x = tracks(time,2,track);
        y = tracks(time,1,track);
        z = tracks(time,3,track);
        t = tracks(time,4,track);
        indCoordinate = sub2ind(imageDimensions, y, x, z, t);
        %turn subscripted coordinates to indexed coordinates to use in 
        %compareSubMatrix
        
        if inputs == 6
        sumIntensity = compareSubMatrix( image, xyPixels, zPixels, indCoordinate, flag);
        elseif inputs == 7
        sumIntensity = compareSubMatrix( image, xyPixels, zPixels, indCoordinate, flag, threshold);
        end
        
        intensities(time,1) = sumIntensity;
        intensities(time,2) = tracks(time,4,track);
    end
    %copy to outside saver matrix
    tracksSum{track} = intensities;
end

assignin('base', matrixName, tracksSum);
%assign as a global variable

end

%-------------------------------------------------------------------------%
%------------------------------ data export ------------------------------%
%-------------------------------------------------------------------------%

function [] = writeData(resultName, greenFit, redFit)
%write results to file
%different files for individual tracks. same files for aligned tracks
    pause('on');
    dimensions = size(resultName,2);
    %if results has 2 entries then it's aligned tracks
    if dimensions == 2
        data1 = evalin('base',resultName{1});
        data2 = evalin('base',resultName{2});
        %copy results data
        tracks = numel(data1);
        %find number of tracks
        analysisType = (strsplit(resultName{1},'_'));
        analysisType = analysisType {1,size(analysisType, 2)};
        fileName = ['Aligned_tracks' '_' analysisType '.xlsx'];
        %create excel file name
        columnHeaders = {'Timepoint' 'Intensity' 'y' 'x' 'z'};
        %create column headers: timepoint, intensity and coordinates
        for i = 1:tracks
            sheet = ['Track_' num2str(i)];
            %open new sheet for each track
            coordinatesData = evalin('base','finalAlignedTracks');
            trackData1 = data1{i};
            coordinatesData1 = coordinatesData(1:size(trackData1, 1),5:7,i);
            trackData2 = data2{i};
            coordinatesData2 = coordinatesData(1:size(trackData2, 1),9:11,i);
            tracksData1 = [trackData1(:,2) trackData1(:,1)];
            tracksData2 = [trackData2(:,2) trackData2(:,1)];
            rows = size(tracksData1,1);
            
            dataToExport = cell(rows+3,25);
            dataToExport(1,1) = {strjoin([resultName(1), 'aligned with', resultName(2)])};
            dataToExport(2,1) = resultName(1);
            dataToExport(2,6) = resultName(2);
            dataToExport(3,1:10) = [columnHeaders columnHeaders];   
            dataToExport(4:end,1:10) = num2cell([tracksData1 coordinatesData1 tracksData2 coordinatesData2]);
            
            if nargin == 3
                %if auto fit was applied
                fitHeader1 = strsplit(resultName{1},'_');
                fitHeader2 = strsplit(resultName{2},'_');
                fitColumnHeaders = {[fitHeader1{2} '_norm'] [fitHeader1{2} '_sigmoid'] [fitHeader2{2} '_norm'] [fitHeader2{2} '_sigmoid']};
                
                dataToExport(3,11:14) = fitColumnHeaders;
                dataToExport(4:end,11:14) = num2cell([greenFit{i,1} greenFit{i,2} redFit{i,1} redFit{i,2}]);
                dataToExport(3:4,16) = [fitHeader1(2);fitHeader2(2)];
                
                dataToExport(2,16:25) = {'Sigmoidal Fit:' 'Window Start' 'Window End' 'Minimum' 'Height' 'Slope' 'Midpoint' 'Score' '' 'delta T'};
                dataToExport(3:4,17:23) = num2cell([greenFit{i,3};redFit{i,3}]);
                dataToExport(3,25) = num2cell(redFit{i,3}(6) - greenFit{i,3}(6));
                
            end
            
            writecell(dataToExport,fileName,'Sheet',sheet,'Range','A1');
            
        end
    else
        data = evalin('base',resultName);
        tracks = numel(data);
        fileName = [resultName '.xlsx'];
        columnHeaders = {'timePoint' 'Intensity' 'y' 'x' 'z'};
        channel = (strsplit(resultName,'_'));
        channel = channel{1};
        coordinatesData = evalin('base', ['finalTracks_' channel]);
        for i = 1:tracks
            sheet = ['Track_' num2str(i)];
            %open new sheet for each track
            trackData = data{i};
            tracksData = [trackData(:,2) trackData(:,1)];
            rows = size(tracksData,1);
            coordinates = coordinatesData(1:rows,1:3,i);
            
            dataToExport = cell(rows+2,5);
            dataToExport(1,1) = {resultName};
            dataToExport(2,1:5) = columnHeaders;
            dataToExport(3:end,1:5) = num2cell([tracksData coordinates]);
            
            writecell(dataToExport,fileName,'Sheet',sheet,'Range','A1');
            
        end
    end
end

%-------------------------------------------------------------------------%
%------------------------------ separate GUIs ----------------------------%
%-------------------------------------------------------------------------%

function [ ] = showSeparateFun(calling_button, eventData, tag )
%call back function
%shows an image in seperate axes

clicked = get(calling_button, 'Value');

imageNameHandle = findobj('tag', tag);
imageName = get(imageNameHandle, 'String');
exists = any(strcmp(evalin('base','who'),imageName));

if clicked == 1 && exists == 1
separateWindow = figure('Position', [200, 200, 960, 720],...
    'tag','sperateFigure','color', 'w', 'MenuBar','none',...
    'name','','numbertitle','off', 'Visible', 'on');

separateAxes = subplot('position', [0.025 0.15 0.85 0.825], 'color', 'k',...
    'parent', separateWindow, 'tag', 'mainAxes');
%[left,bottom,width,height]
set(separateAxes,'XColor','w', 'xtick',[]);
set(separateAxes,'YColor','w', 'ytick',[]);

uicontrol('style'   ,'slider',....
    'parent', separateWindow,...
    'unit', 'norm',...
    'position',[0.1 0.05 0.75 0.025],... %[left,bottom,width,height]
    'Enable', 'on',...
    'tag'     ,'separateSlider',...
    'max'     ,100,... %change values to fit number of time points 
    'min'     ,1,...
    'sliderstep',[0.01 0.1],... %change to 1 time point per minor step
    'value'   ,1,...
    'callback', {@changeSeparate, separateAxes, tag});
% Adds timepoint over slider
uicontrol('Style','text',...
    'parent', separateWindow,...
    'String','Time point',...
    'fontsize', 12,...
    'HorizontalAlignment', 'left',...
    'backgroundColor','w',...
    'foregroundColor','b',...
    'unit', 'norm',...
    'Position',[0.125 0.1 0.2 0.025],... %[left,bottom,width,height]
    'tag','separateTimePoint');

uicontrol('style'   ,'pushbutton',...
    'parent', separateWindow,...
    'string', 'Close',...
    'fontsize', 12,...
    'unit', 'norm',...
    'position',[0.9, 0.05 0.075 0.03],... %[left,bottom,width,height]
    'tag','close',...
    'callback', {@closeFig, separateWindow, 'showSeparate'});

uicontrol('Style','checkbox',...
    'parent', separateWindow,...
    'backgroundColor','w',...
    'Value', 0,...
    'foregroundColor','k',...
    'fontsize', 12,...
    'string', 'Zoom in',...
    'unit', 'norm',...
    'Position',[0.9 0.2 0.15 0.03],... %[left,bottom,width,height]
    'tag','separateZoomIn',...
    'callback', {@Zoom, 'separateZoomIn', separateWindow, 'on'});

uicontrol('style'   ,'pushbutton',...
    'parent', separateWindow,...
    'String','Reset view' ,...
    'Enable', 'on',...
    'unit', 'norm',...
    'fontsize', 12,...
    'position',[0.9 0.15 0.075 0.03],... %[left,bottom,width,height]
    'tag','separateResetView',...
    'callback', {@Zoom, 'separateZoomIn', separateWindow, 'out'});

set(separateWindow, 'name', imageName);
set(findobj('tag', 'separateSlider'), 'Max', get(findobj('tag', 'timePointSlider'), 'Max'));
set(findobj('tag', 'separateSlider'), 'value', get(findobj('tag', 'timePointSlider'), 'value'));

changeSeparate(calling_button, eventData, separateAxes, tag)

else
    if ishandle(findobj('tag', 'sperateFigure')) == 1
    close(findobj('tag', 'sperateFigure'));
    end
end
end

function [] =  changeSeparate(calling_button, eventData, axes, tag)
%changes image in response to slider

value = get(findobj('tag', 'separateSlider'), 'value');

imageNameHandle = findobj('tag', tag);
imageName = get(imageNameHandle, 'String');
imageMatrix = evalin('base',imageName);

imageMatrixVector = cell(1);
imageMatrixVector{1} = imageMatrix;
colorVector = cell(1);
colorVector{1} = 'w';

showImage(imageMatrixVector, round(value), colorVector, axes);

%change text to show current time point
separateTimePointHandle = findobj('tag', 'separateTimePoint');
sliderMax = get(findobj('tag', 'separateSlider'), 'max');
set(separateTimePointHandle, 'string', ['Time Point: '  num2str(round(value)) ' / ' num2str(sliderMax)]);

end

function [] =  closeFig(calling_button, eventData, FigHandle, checkbox)
%Closes the window with handle FigHandle

set(findobj('tag', checkbox), 'value', 0);
close (FigHandle); 

end

function [] = Zoom (calling_button, eventData, checkbox, fig, status)
%allows the user to zoom in on axes
if get(findobj('tag', checkbox), 'value') == 1
    zoom(fig, status);
else
    zoom(fig, 'out');
    zoom(fig, 'off');
end
end
