%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Phasor analysis program %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Phasor(~,~)
global UserValues PhasorData
h.Phasor=findobj('Tag','Phasor');

addpath(genpath(['.' filesep 'functions']));

if ~isempty(h.Phasor) % Creates new figure, if none exists
    figure(h.Phasor);
    return
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Figure generation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%% Disables uitabgroup warning
    warning('off','MATLAB:uitabgroup:OldVersion');
    %%% Loads user profile
    LSUserValues(0);
    %%% To save typing
    Look=UserValues.Look;
    %%% Generates the Pam figure
    h.Phasor = figure(...
        'Units','normalized',...
        'Tag','Phasor',...
        'Name','Phasor Analysis',...
        'NumberTitle','off',...
        'Menu','none',...
        'defaultUicontrolFontName',Look.Font,...
        'defaultAxesFontName',Look.Font,...
        'defaultTextFontName',Look.Font,...
        'defaultAxesYColor',Look.Fore,...
        'Toolbar','figure',...
        'UserData',[],...
        'BusyAction','cancel',...
        'OuterPosition',[0.01 0.1 0.98 0.9],...
        'WindowScrollWheelFcn',{@Phasor_Move,3,[],[]},...
        'WindowButtonUpFcn',@Stop_All,...
        'KeyPressFcn',{@Phasor_Key,1},...
        'CloseRequestFcn',@CloseWindow,...
        'Visible','on');
    %%% Sets background of axes and other things
    whitebg(Look.Fore);
    %%% Changes Pam background; must be called after whitebg
    h.Phasor.Color=Look.Back;
    %%% Remove unneeded items from toolbar
    toolbar = findall(h.Phasor,'Type','uitoolbar');
    toolbar_items = findall(toolbar);
    delete(toolbar_items([2:7 9 13:17]));
    
    h.Load_Phasor = uimenu(...
    'Parent',h.Phasor,...
    'Label','Load Phasor Data',...
    'Callback',@Load_Phasor_Data,...
    'Tag','Load_Phasor');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Main Phasor plot and displays %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%% Panel containing phasor plot and information
    h.Phasor_Panel = uibuttongroup(...
        'Parent',h.Phasor,...
        'Units','normalized',...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HighlightColor', Look.Control,...
        'ShadowColor', Look.Shadow,...
        'Position',[0.55 0.35 0.44 0.64],...
        'Tag','Phasor_Panel');
    %%% Main phasor plot
    h.Phasor_Plot = axes(...
        'Parent',h.Phasor_Panel,...
        'Units','normalized',...
        'Position',[0.07 0.08 0.88 0.78],...
        'Tag','Phasor_Plot',...
        'XColor',Look.Fore,...
        'YColor',Look.Fore,...
        'Layer','top',...
        'DataAspectRatio',[1 1 1],...
        'Box','on');
    hold on;
    %%% Plots empty histogram
    h.Phasor_Hist=image(linspace(-0.1,1.2,260),linspace(-0.1,1.2,260),ones(260,260,3));
    h.Phasor_Hist.HitTest='off';
    %%% Plots universal circle and sets axes properties
    y=0:0.001:1; z=0:0.001:1;
    h.Universal_Circle=plot(y,sqrt(z-z.^2),'k','LineStyle','--','Linewidth',2);
    h.Universal_Circle.HitTest='off';
    h.Phasor_Plot.YDir='normal';
    h.Phasor_Plot.XLabel.Color=Look.Fore;
    h.Phasor_Plot.XLabel.String='g';
    h.Phasor_Plot.YLabel.Color=Look.Fore;
    h.Phasor_Plot.YLabel.String='s';
    h.Phasor_Plot.YLim=[0, 1];
    h.Phasor_Plot.XLim=[0, 1];
    h.Phasor_Plot.ButtonDownFcn={@Phasor_Plot_Callback,[]};
    %%% Initializes ROIs
    for i=1:6
        %%% Rectangular ROIS
        h.Phasor_ROI(i,1)=rectangle(...
            'Parent',h.Phasor_Plot,...
            'Position',[0 0 0 0],...
            'HitTest','off',...
            'Visible','off',...
            'EdgeColor',[0 0 0]);
        %%% Elipsiod ROIS
        h.Phasor_ROI(i,2)=line(...
            'Parent',h.Phasor_Plot,...
            'XData',[0 0],...
            'YData',[0 0],...
            'HitTest','off',...
            'Visible','off',...
            'Color',[0 0 0]);
    end
    %%% Fraction Lines
    h.Phasor_Fraction=line(...
        'Parent',h.Phasor_Plot,...
        'XData',[0 0],...
        'YData',[0 0],...
        'HitTest','off',...
        'Visible','off',...
        'Color',[0 0 0]);
    %%% Triangle Line
    h.Phasor_Triangle=line(...
        'Parent',h.Phasor_Plot,...
        'XData',[0 1 0 0],...
        'YData',[0 1 1 0],...
        'HitTest','off',...
        'Visible','off',...
        'Color',[0 0 0]);
    
    
    %%% Initializes FRET lines
    h.Phasor_FRET(1,1)=line(...
        'Parent',h.Phasor_Plot,...
        'XData',[0 0],...
        'YData',[0 0],...
        'HitTest','off',...
        'Visible','off',...
        'LineWidth', str2double(UserValues.Phasor.Settings_FRETWidth{1}),...
        'LineStyle',UserValues.Phasor.Settings_FRETStyle{1},...
        'Color',UserValues.Phasor.Settings_FRETColor(1,:));
    h.Phasor_FRET(1,2)=line(...
        'Parent',h.Phasor_Plot,...
        'XData',0,...
        'YData',0,...
        'HitTest','off',...
        'LineStyle','none',...
        'LineWidth',2,...
        'MarkerSize', str2double(UserValues.Phasor.Settings_FRETSize{1}),...
        'Marker', UserValues.Phasor.Settings_FRETMarker{1},...
        'Visible','off',...
        'Color',UserValues.Phasor.Settings_FRETColor(1,:));
    h.Phasor_FRET(2,1)=line(...
        'Parent',h.Phasor_Plot,...
        'XData',[0 0],...
        'YData',[0 0],...
        'HitTest','off',...
        'Visible','off',...
        'LineWidth', str2double(UserValues.Phasor.Settings_FRETWidth{2}),...
        'LineStyle', UserValues.Phasor.Settings_FRETStyle{2},...
        'Color',UserValues.Phasor.Settings_FRETColor(2,:));
    h.Phasor_FRET(2,2)=line(...
        'Parent',h.Phasor_Plot,...
        'XData',0,...
        'YData',0,...
        'HitTest','off',...
        'LineStyle','none',...
        'LineWidth',2,...
        'MarkerSize', str2double(UserValues.Phasor.Settings_FRETSize{2}),...
        'Marker', UserValues.Phasor.Settings_FRETMarker{2},...
        'Visible','off',...
        'Color',UserValues.Phasor.Settings_FRETColor(2,:));
    h.Phasor_FRET(3,1)=line(...
        'Parent',h.Phasor_Plot,...
        'XData',[0.5 0],...
        'YData',[0.5 0],...
        'HitTest','off',...
        'Visible','off',...
        'LineWidth', str2double(UserValues.Phasor.Settings_FRETWidth{3}),...
        'LineStyle', UserValues.Phasor.Settings_FRETStyle{3},...
        'Color',UserValues.Phasor.Settings_FRETColor(3,:));
    h.Phasor_FRET(3,2)=line(...
        'Parent',h.Phasor_Plot,...
        'XData',0,...
        'YData',0,...
        'HitTest','off',...
        'LineStyle','none',...
        'LineWidth',2,...
        'MarkerSize', str2double(UserValues.Phasor.Settings_FRETSize{3}),...
        'Marker', UserValues.Phasor.Settings_FRETMarker{3},...
        'Visible','off',...
        'Color',UserValues.Phasor.Settings_FRETColor(3,:));
    h.Phasor_FRET(4,1)=line(...
        'Parent',h.Phasor_Plot,...
        'XData',[0 0],...
        'YData',[0 0],...
        'HitTest','off',...
        'Visible','off',...
        'LineWidth', str2double(UserValues.Phasor.Settings_FRETWidth{4}),...
        'LineStyle', UserValues.Phasor.Settings_FRETStyle{4},...
        'Color',UserValues.Phasor.Settings_FRETColor(4,:));
    h.Phasor_FRET(4,2)=line(...
        'Parent',h.Phasor_Plot,...
        'XData',0,...
        'YData',0,...
        'HitTest','off',...
        'LineStyle','none',...
        'LineWidth',2,...
        'MarkerSize', str2double(UserValues.Phasor.Settings_FRETSize{4}),...
        'Marker', UserValues.Phasor.Settings_FRETMarker{4},...
        'Visible','off',...
        'Color',UserValues.Phasor.Settings_FRETColor(4,:));
    h.Phasor_FRET(5,1)=line(...
        'Parent',h.Phasor_Plot,...
        'XData',0,...
        'YData',0,...
        'HitTest','off',...
        'LineWidth', str2double(UserValues.Phasor.Settings_FRETWidth{4}),...
        'LineStyle', UserValues.Phasor.Settings_FRETStyle{4},...
        'Visible','off',...
        'Color',UserValues.Phasor.Settings_FRETColor(4,:));
    %%% Context menu for phasor plot 
    h.Phasor_Plot_Menu = uicontextmenu;
    h.Phasor_Plot_FRET = uimenu(...
        'Parent',h.Phasor_Plot_Menu,...
        'Label','Set Donor',...
        'Callback',{@Calc_FRET,1},...
        'Tag','Phasor_Plot_FRET');
    h.Phasor_Plot_BG = uimenu(...
        'Parent',h.Phasor_Plot_Menu,...
        'Label','Set Background',...
        'Callback',{@Calc_FRET,2},...
        'Tag','Phasor_Plot_BG');
    
    
    %%% Text for displaying TauP
    h.TauP_Text = uicontrol(...
        'Parent',h.Phasor_Panel,...
        'Units','normalized',...
        'Position',[0.02 0.9 0.4 0.03],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'Tag','TauP_Text',...
        'HorizontalAlignment','left',...
        'FontSize',10,...
        'Style', 'text',...
        'String','TauP =');
    %%% Text for displaying TauM
    h.TauM_Text = uicontrol(...
        'Parent',h.Phasor_Panel,...
        'Units','normalized',...
        'Position',[0.02 0.96 0.4 0.03],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'Tag','TauM_Text',...
        'HorizontalAlignment','left',...
        'FontSize',10,...
        'Style', 'text',...
        'String','TauM =');
    %%% Text for displaying TauG
    h.G_Text = uicontrol(...
        'Parent',h.Phasor_Panel,...
        'Units','normalized',...
        'Position',[0.52 0.9 0.4 0.03],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'Tag','G_Text',...
        'HorizontalAlignment','left',...
        'FontSize',10,...
        'Style', 'text',...
        'String','G =');
    %%% Text for displaying TauS
    h.S_Text = uicontrol(...
        'Parent',h.Phasor_Panel,...
        'Units','normalized',...
        'Position',[0.52 0.96 0.4 0.03],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'Tag','S_Text',...
        'HorizontalAlignment','left',...
        'FontSize',10,...
        'Style', 'text',...
        'String','S =');


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Tabs for general Settings & File List, ROIs & Fraction, FRET and Markers
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%% Tab container for additional controls
    h.Additional_Tab=uitabgroup(...
        'Parent',h.Phasor,...
        'Tag','Additional_Tab',...
        'Units','normalized',...
        'Position',[0.55 0.01 0.44 0.33]);
    %% Tab containing ploting settings
    h.Settings_Tab=uitab(...
        'title','Settings',...
        'Tag','Settings_Tab'); 
    %%% Listbox of all loaded files
    h.Settings_Panel = uibuttongroup(...
        'Parent',h.Settings_Tab,...
        'Units','normalized',...
        'BackgroundColor',Look.Back,...
        'ForegroundColor',Look.Fore,...
        'HighlightColor',Look.Control,...
        'ShadowColor',Look.Shadow,...
        'Position',[0 0 1 1],...
        'Tag','Settings_Panel');  
    %%% Text for threshold
    uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.9 0.20 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',10,...
        'Style', 'text',...
        'String','Threshold min/max:');

    %%% Lower threshold
    h.THmin = uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.22 0.9 0.08 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag','THmin',...
        'HorizontalAlignment','center',...
        'FontSize',10,...
        'Callback',{@Plot_Phasor,1,1:10},...
        'Style', 'edit',...
        'ToolTipString', ['<html>Lower count threshold: <br>',...
                        'Pixels with fewer counts will not be displayed <br>'...
                        'in phasor histogram or colored for ROIs'],...
        'String',UserValues.Phasor.Settings_THMin);
    %%% Upper threshold
    h.THmax = uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.31 0.9 0.08 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag','THmax',...
        'HorizontalAlignment','center',...
        'FontSize',10,...
        'Callback',{@Plot_Phasor,1,1:10},...
        'Style', 'edit',...
        'ToolTipString', ['<html>Upper count threshold: <br>',...
                    'Pixels with more counts will not be displayed <br>'...
                    'in phasor histogram or colored for ROIs'],...
        'String',UserValues.Phasor.Settings_THMax);
    %%% Text for threshold
    h.Autoscale=uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.81 0.20 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',10,...
        'Callback',{@Plot_Phasor,0,1:10},...
        'Style', 'checkbox',...
        'Value',UserValues.Phasor.Settings_Use_AS,...
        'ToolTipString', ['<html>Toggle autoscaling of images'],...
        'String','Use Autoscale:');
   
    %%% Lower threshold
    h.ASmin = uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.22 0.81 0.08 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag','ASmin',...
        'HorizontalAlignment','center',...
        'FontSize',10,...
        'Callback',{@Plot_Phasor,0,1:10},...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_ASMin);
    %%% Upper threshold
    h.ASmax = uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.31 0.81 0.08 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag','ASmax',...
        'HorizontalAlignment','center',...
        'FontSize',10,...
        'Callback',{@Plot_Phasor,0,1:10},...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_ASMax);
    %%% Text for image colormap
    uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.7 0.20 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',10,...
        'Style', 'text',...
        'String','Image colormap:');
    %%% Image_Colormap
    h.ImageColor = uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.22 0.72 0.17 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag','ImageColor',...
        'FontSize',10,...
        'Callback',{@Plot_Phasor,0,1:10},...
        'Style', 'popupmenu',...
        'Value', UserValues.Phasor.Settings_ImageColor,...
        'ToolTipString', ['<html>Select colormap for image display: <br>',...
                '<b>Gray:</b> ROIs are colorcoded according to pixel counts <br>'...
                '<b>Other:</b> ROIs are colorcoded with constant brightness' ],...
        'String',{'Gray';'Jet';'Hot';'HSV';'Black'});
    if ismac
        h.ImageColor.ForegroundColor = [0 0 0];
        h.ImageColor.BackgroundColor = [1 1 1];
    end
    %%% Text for Phasor resolution
    uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.6 0.20 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',10,...
        'Style', 'text',...
        'String','Phasor resolution:');
    %%% Resolution of phasor plot in pixel for 0 to 1
    h.Phasor_Res = uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.22 0.6 0.17 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag','ImageColor',...
        'FontSize',10,...
        'Callback',{@Plot_Phasor,1,1:10},...
        'Style', 'edit',...
        'ToolTipString', ['<html>Phasor Resolution: <br>',...
                'Determines number of bins <br>'...
                'for both dimensions between 0 and 1 <br>'...
                '<b>!!!Only use multiples of 10!!!</b>' ],...
        'String',UserValues.Phasor.Settings_Resolution);
    %%% Text for phasor colormap
    uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.49 0.20 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',10,...
        'Style', 'text',...
        'String','Phasor colormap:');
    %%% Image_Colormap
    h.PhasorColor = uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.22 0.51 0.17 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag','PhasorColor',...
        'FontSize',10,...
        'Value', UserValues.Phasor.Settings_PhasorColor,...
        'Callback',{@Plot_Phasor,1,[]},...
        'Style', 'popupmenu',...
        'ToolTipString', '<html>Select colormap for phasor histogram',...
        'String',{'Jet';'Hot';'Gray';'HSV'});
    if ismac
        h.PhasorColor.ForegroundColor = [0 0 0];
        h.PhasorColor.BackgroundColor = [1 1 1];
    end
    %%% Center of Mass display controls
    h.Phasor_Center = uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.07 0.21 0.1],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag','PhasorColor',...
        'FontSize',10,...
        'Value', 1,...
        'Style', 'popupmenu',...
        'Callback',{@Update_CoM,0,1:2},...
        'ToolTipString', 'Toggle display of the center of mean in the phasor plot',...
        'String',{'No CoM display';'Photon weighted CoM';'Pixel weighted CoM'});
    if ismac
        h.Phasor_Center.ForegroundColor = [0 0 0];
        h.Phasor_Center.BackgroundColor = [1 1 1];
    end
    h.Phasor_CoM_Menu = uicontextmenu;
    h.Phasor_CoM_Size = uimenu(...
        'Parent',h.Phasor_CoM_Menu,...
        'Label','Set Marker Size',...
        'Callback',{@Update_CoM,0,4});
    h.Phasor_CoM_Line = uimenu(...
        'Parent',h.Phasor_CoM_Menu,...
        'Label','Set LineWidth',...
        'Callback',{@Update_CoM,0,5});
    h.Phasor_CoM_LineColor = uimenu(...
        'Parent',h.Phasor_CoM_Menu,...
        'Label','Set Marker Color',...
        'Callback',{@Update_CoM,0,6});
    h.Phasor_CoM_FillColor = uimenu(...
        'Parent',h.Phasor_CoM_Menu,...
        'Label','Set Marker Fill Color',...
        'Callback',{@Update_CoM,0,7});
    h.Phasor_CoM_FillTransparent = uimenu(...
        'Parent',h.Phasor_CoM_Menu,...
        'Label','Set Marker Fill Transparent',...
        'Callback',{@Update_CoM,0,8});
    
    h.Phasor_CoM_Marker = uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'Position',[0.23 0.07 0.16 0.1],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag','PhasorColor',...
        'FontSize',10,...
        'Value', 1,...
        'Style', 'popupmenu',...
        'UIContextMenu',h.Phasor_CoM_Menu,...
        'Callback',{@Update_CoM,0,3},...
        'Visible','off',...
        'ToolTipString', 'Select Center of Mass marker type. <br> Rightlick: change marker properties',...
        'String',{'+','none','o','*','.','x','square','diamond','v','^','<','>','pentagram','hexagram'});
    if ismac
        h.Phasor_CoM_Marker.ForegroundColor = [0 0 0];
        h.Phasor_CoM_Marker.BackgroundColor = [1 1 1];
    end
    
    h.List_Menu = uicontextmenu;
    h.Average_Data = uimenu(...
        'Parent',h.List_Menu,...
        'Label','Average Pixels',...
        'Tag','E_Button',...
        'Callback',@List_Callback);
    h.Export_ROIs = uimenu(...
        'Parent',h.List_Menu,...
        'Label','Export ROIs',...
        'Tag','ExportROIs',...
        'Callback',@List_Callback);
    h.Export_Fraction = uimenu(...
        'Parent',h.List_Menu,...
        'Label','Export Fraction',...
        'Tag','ExportROIs',...
        'Callback',@List_Callback);
    h.Export_Hist = uimenu(...
        'Parent',h.List_Menu,...
        'Label','Export Phasor Histogram',...
        'Tag','ExportROIs',...
        'Callback',@List_Callback);
    h.Export_LifetimeIm = uimenu(...
        'Parent',h.List_Menu,...
        'Label','Export Lifetime Images',...
        'Tag','ExportLifetimeImages',...
        'Callback',@List_Callback);    
    %%% Listbox of all loaded files
    h.List = uicontrol(...
        'Parent',h.Settings_Panel,...
        'Units','normalized',...
        'BackgroundColor', Look.List,...
        'ForegroundColor', Look.ListFore,...
        'KeyPressFcn',@List_Callback,...
        'Callback',{@Plot_Phasor,1,1:10},...
        'Max',5,...
        'FontSize',12,...
        'Value',0,...
        'UIContextMenu',h.List_Menu,...
        'Position',[0.41 0.01 0.58 0.98],...
        'Style','listbox',...
        'ToolTipString', ['<html>File List: <br>',...
                '<font color = 0000FF><b>Displayed:</b></font> Active files displayed as image <br>'...
                '<font color = FF0000><b>Active:</b></font> Active files used for Phasor histogram, but not displayed as image <br>'...
                '<font color = 888888><b>Inactive:</b></font> Inactive file not used for displaying/calculation <br>'...
                'Controls: <br>'...
                '<b>"delete":</b> Removes selected files from list<br>'...
                '<b>"leftarrow":</b> Turns selected files inactive<br>'...
                '<b>"rightarrow":</b> Displays selected files<br>'...
                '<b>"+":</b> Turns selected files active, but does not display them'],...
        'Tag','List'); 


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Tab ROI and fraction setting
    h.ROI_Tab=uitab(...
        'title','ROI & Fraction',...
        'Tag','ROI_Tab'); 
    %%% Panel for ROI and Fraction controls
    h.ROI_Panel = uibuttongroup(...
        'Parent',h.ROI_Tab,...
        'Units','normalized',...
        'BackgroundColor',Look.Back,...
        'ForegroundColor',Look.Fore,...
        'HighlightColor',Look.Control,...
        'ShadowColor',Look.Shadow,...
        'Position',[0 0 1 1],...
        'Tag','ROI_Panel'); 
    %%% Text for ROI linewidth
    uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.12 0.92 0.1 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','center',...
        'FontSize',11,...
        'Style', 'text',...
        'String','Width');
    %%% Text for ROI linestyle
    uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.23 0.92 0.1 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','center',...
        'FontSize',11,...
        'Style', 'text',...
        'String','Style');
    %%% Text for ROI linestyle
    uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.34 0.92 0.1 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','center',...
        'FontSize',11,...
        'Style', 'text',...
        'String','Size');
    
    h.ROI_Live = uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.46 0.92 0.25 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'Tag','ROI_Live',...
        'FontSize',12,...
        'Style', 'check',...
        'Value',0,...
        'ToolTipString', ['<html>Live ROI Update: <br>',...
            'Toggle live update for ROIs and Fraction<br>'],...
        'String','Live Update');
    
    for i=1:6
        %%% Box to change ROI color
        h.ROI_Color{i} = uicontrol(...
            'Parent',h.ROI_Panel,...
            'Units','normalized',...
            'Position',[0.01 0.9-0.1*i 0.1 0.09],...
            'BackgroundColor', UserValues.Phasor.Settings_ROIColor(i,:),...
            'ForegroundColor', repmat(~(sum(UserValues.Phasor.Settings_ROIColor(i,:))>=1.5),[1 3]),...
            'Tag',['ROI_Color',num2str(i)],...
            'FontSize',12,...
            'Enable','inactive',...
            'Style', 'edit',...
            'ButtonDownFcn',{@ROI_Look,1,i},...
            'ToolTipString', ['<html>Activate ROI: <br>',...
                '<b>Left mouse button:</b> Toggle rectangular ROI<br>'...
                '<b>Right mouse button:</b> Toggle ellipsoid ROI<br>'...
                '<b>Middle mouse button:</b> Change ROI color<br>'],...
            'String',['ROI ' num2str(i)]);
        %%% Box to change ROI linewidth
        h.ROI_Width{i} = uicontrol(...
            'Parent',h.ROI_Panel,...
            'Units','normalized',...
            'Position',[0.12 0.9-0.1*i 0.08 0.09],...
            'BackgroundColor', Look.Control,...
            'ForegroundColor', Look.Fore,...
            'Tag',['ROI_Width',num2str(i)],...
            'FontSize',12,...
            'Style', 'edit',...
            'Callback',{@ROI_Look,2,i},...
            'String',UserValues.Phasor.Settings_ROIWidth{i});
        %%% Box to change ROI linestyle
        h.ROI_Style{i} = uicontrol(...
            'Parent',h.ROI_Panel,...
            'Units','normalized',...
            'Position',[0.21 0.9-0.1*i 0.08 0.09],...
            'BackgroundColor', Look.Control,...
            'ForegroundColor', Look.Fore,...
            'Tag',['ROI_Style',num2str(i)],...
            'FontSize',12,...
            'Style', 'edit',...
            'Callback',{@ROI_Look,3,i},...
            'ToolTipString', '<html>Possible ROI Styles: "-", ":", "--", "-.", "none",<br>',...
            'String',UserValues.Phasor.Settings_ROIStyle{i});
        %%% Box to change ROI extend
        h.ROI_Size{i} = uicontrol(...
            'Parent',h.ROI_Panel,...
            'Units','normalized',...
            'Position',[0.3 0.9-0.1*i 0.08 0.09],...
            'BackgroundColor', Look.Control,...
            'ForegroundColor', Look.Fore,...
            'Tag',['ROI_Size',num2str(i)],...
            'FontSize',12,...
            'Style', 'edit',...
            'Callback',{@ROI_Look,4,i},...
            'ToolTipString', '<html>Diameter of ROI ellipsoid: <br>',...
            'String',UserValues.Phasor.Settings_ROISize{i});
    end
    
    %%% Box to change Fraction color
    h.ROI_Color{7} = uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.9-0.1*7 0.1 0.09],...
        'BackgroundColor', UserValues.Phasor.Settings_ROIColor(7,:),...
        'ForegroundColor', repmat(~(sum(UserValues.Phasor.Settings_ROIColor(7,:))>=1.5),[1 3]),...
        'Tag',['ROI_Color',num2str(7)],...
        'FontSize',12,...
        'Enable','inactive',...
        'Style', 'edit',...
        'ButtonDownFcn',{@ROI_Look,1,7},...
        'ToolTipString', ['<html>Activate ROI: <br>',...
            '<b>Left/Right mouse button:</b> Toggle fraction Line<br>'...
            '<b>Middle mouse button:</b> Change Fraction line color (not the associated colormap)<br>'],...
        'String','Fraction');
    %%% Box to change Fraction linewidth
    h.ROI_Width{7} = uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.12 0.9-0.1*7 0.08 0.09],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag',['ROI_Width',num2str(7)],...
        'FontSize',12,...
        'Style', 'edit',...
        'Callback',{@ROI_Look,2,7},...
        'String',UserValues.Phasor.Settings_ROIWidth{7});
    %%% Box to change Fraction linestyle
    h.ROI_Style{7} = uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.21 0.9-0.1*7 0.08 0.09],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag',['ROI_Style',num2str(7)],...
        'FontSize',12,...
        'Style', 'edit',...
        'Callback',{@ROI_Look,3,7},...
        'ToolTipString', '<html>Possible Fraction Line Styles: "-", ":", "--", "-.", "none",<br>',...
        'String',UserValues.Phasor.Settings_ROIStyle{7});
    %%% Box to change Fraction extend
    h.ROI_Size{7} = uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.3 0.9-0.1*7 0.08 0.09],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag',['ROI_Size',num2str(7)],...
        'FontSize',12,...
        'Style', 'edit',...
        'Callback',{@ROI_Look,4,7},...
        'ToolTipString', '<html>Maximal distance from line, so that pixels are still colorcoded: <br>',...
        'String',UserValues.Phasor.Settings_ROISize{7});
    %%% Selects Fraction colormap
    h.Fraction_Color = uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.39 0.22 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Tag','ImageColor',...
        'FontSize',10,...
        'Callback',{@Plot_Phasor,0,1:10},...
        'Style', 'popupmenu',...
        'Value', UserValues.Phasor.Settings_LineColor,...
        'ToolTipString', '<html>Colormap used to indicate position of pixels on line <br>',...
        'String',{'Jet';'Hot';'HSV';'GreenRed';'Custom'});      
    if ismac
        h.Fraction_Color.ForegroundColor = [0 0 0];
        h.Fraction_Color.BackgroundColor = [1 1 1];
    end
    %%% Text for ROI linestyle
    uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.5 0.2 0.08 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','Left',...
        'FontSize',11,...
        'Style', 'text',...
        'String','Pos:');
    %%% Boxes for fraction line start/stop positions:
    for i=1:4        
        h.ROI_Line_Pos{i} = uicontrol(...
            'Parent',h.ROI_Panel,...
            'Units','normalized',...
            'Position',[0.5+i*0.09 0.20 0.08 0.09],...
            'BackgroundColor', Look.Control,...
            'ForegroundColor', Look.Fore,...
            'Tag',['ROI_Line_Pos',num2str(i)],...
            'Callback', {@Phasor_Move,6.1,[],[]},...
            'FontSize',12,...
            'Style', 'edit',...
            'String','0');
    end
    
    %%% Box to change Triangle color
    h.ROI_Color{8} = uicontrol(...
        'Parent',h.ROI_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.1 0.1 0.09],...
        'BackgroundColor', UserValues.Phasor.Settings_ROIColor(7,:),...
        'ForegroundColor', repmat(~(sum(UserValues.Phasor.Settings_ROIColor(7,:))>=1.5),[1 3]),...
        'Tag',['ROI_Color',num2str(7)],...
        'FontSize',12,...
        'Enable','inactive',...
        'Style', 'edit',...
        'ButtonDownFcn',{@ROI_Look,1,8},...
        'ToolTipString', ['<html>Activate ROI: <br>',...
        '<b>Left/Right mouse button:</b> Toggle Triangle<br>'...
        '<b>Middle mouse button:</b> Change Triangle line color (not the associated colormap)<br>'],...
        'String','Triangle');
    
    %% Tab for FRET calculations
    h.FRET_Tab=uitab(...
        'title','FRET',...
        'Tag','FRET_Tab');
    %%% Panel for FRET controls
    h.FRET_Panel = uibuttongroup(...
        'Parent',h.FRET_Tab,...
        'Units','normalized',...
        'BackgroundColor',Look.Back,...
        'ForegroundColor',Look.Fore,...
        'HighlightColor',Look.Control,...
        'ShadowColor',Look.Shadow,...
        'Position',[0 0 1 1],...
        'Tag','FRET_Panel');
    %%% Text BG ratio
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.91 0.16 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Background:');
    %%% Slider for Background ratio
    h.FRET_BG_Slider = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.17 0.91 0.2 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'slider',...
        'Min',0,...
        'Max',100,...
        'SliderStep',[0.01 0.1],...
        'Callback',{@Calc_FRET,3});
    %%% Editbox for Background ratio
    h.FRET_BG_Edit = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.38 0.91 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String','0',...
        'Callback',{@Calc_FRET,4});
    %%% Text Donor only ratio
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.82 0.16 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Donor only:');
    %%% Slider for Donor only ratio
    h.FRET_DO_Slider = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.17 0.82 0.2 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'slider',...
        'Min',0,...
        'Max',100,...
        'SliderStep',[0.01 0.1],...
        'Callback',{@Calc_FRET,5});
    %%% Editbox for Donor only ratio
    h.FRET_DO_Edit = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.38 0.82 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String','0',...
        'Callback',{@Calc_FRET,6});
    %%% Text FRET value
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.73 0.16 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',12,...
        'Style', 'text',...
        'String','FRET value:');
    %%% Slider for Donor only ratio
    h.FRET_Value_Slider = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.17 0.73 0.2 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'slider',...
        'Min',0,...
        'Max',100,...
        'SliderStep',[0.01 0.1],...
        'Callback',{@Calc_FRET,7});
    %%% Editbox for Donor only ratio
    h.FRET_Value_Edit = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.38 0.73 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String','0',...
        'Callback',{@Calc_FRET,8});
    %%% Texts for linewith, lynestyle, makrer size and style
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.17 0.64 0.10 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','center',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Width');
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.28 0.64 0.10 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','center',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Style');
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.39 0.64 0.10 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','center',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Marker');
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.50 0.64 0.10 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','center',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Size');
    
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'Position',[0.65 0.64 0.10 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','center',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Position');
        %% Controls for Donor FRET line and marker
    h.FRET_Line(1,1) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.01 0.55 0.15 0.07],...
        'BackgroundColor', UserValues.Phasor.Settings_FRETColor(1,:),...
        'ForegroundColor', repmat(~(sum(UserValues.Phasor.Settings_FRETColor(1,:))>=1.5),[1 3]),...
        'Style', 'edit',...
        'Enable','inactive',...
        'String','Donor',...
        'ButtonDownFcn',{@FRET_Look,1,1});
    h.FRET_Line(1,2) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.17 0.55 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETWidth{1},...
        'Callback',{@FRET_Look,2,1});
    h.FRET_Line(1,3) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.28 0.55 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETStyle{1},...
        'Callback',{@FRET_Look,3,1});
    h.FRET_Line(1,4) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.39 0.55 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETMarker{1},...
        'Callback',{@FRET_Look,4,1});
    h.FRET_Line(1,5) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.50 0.55 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETSize{1},...
        'Callback',{@FRET_Look,5,1});
    %%% Controls for mixture line and marker
    h.FRET_Line(2,1) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.01 0.46 0.15 0.07],...
        'BackgroundColor', UserValues.Phasor.Settings_FRETColor(2,:),...
        'ForegroundColor', repmat(~(sum(UserValues.Phasor.Settings_FRETColor(2,:))>=1.5),[1 3]),...
        'Style', 'edit',...
        'Enable','inactive',...
        'String','FRET',...
        'ButtonDownFcn',{@FRET_Look,1,2});
    h.FRET_Line(2,2) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.17 0.46 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETWidth{2},...
        'Callback',{@FRET_Look,2,2});
    h.FRET_Line(2,3) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.28 0.46 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
                'String',UserValues.Phasor.Settings_FRETStyle{2},...
        'Callback',{@FRET_Look,3,2});
    h.FRET_Line(2,4) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.39 0.46 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETMarker{2},...
        'Callback',{@FRET_Look,4,2});
    h.FRET_Line(2,5) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.50 0.46 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETSize{2},...
        'Callback',{@FRET_Look,5,2});
    %%% Controls for background line and marker
    h.FRET_Line(3,1) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.01 0.37 0.15 0.07],...
        'BackgroundColor', UserValues.Phasor.Settings_FRETColor(3,:),...
        'ForegroundColor', repmat(~(sum(UserValues.Phasor.Settings_FRETColor(3,:))>=1.5),[1 3]),...
        'Style', 'edit',...
        'Enable','inactive',...
        'String','Background',...
        'ButtonDownFcn',{@FRET_Look,1,3});
    h.FRET_Line(3,2) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.17 0.37 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETWidth{3},...
        'Callback',{@FRET_Look,2,3});
    h.FRET_Line(3,3) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.28 0.37 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETStyle{3},...
        'Callback',{@FRET_Look,3,3});
    h.FRET_Line(3,4) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.39 0.37 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETMarker{3},...
        'Callback',{@FRET_Look,4,3});
    h.FRET_Line(3,5) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.50 0.37 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETSize{3},...
        'Callback',{@FRET_Look,5,3});
    %%% Controls for fret line and marker
    h.FRET_Line(4,1) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.01 0.28 0.15 0.07],...
        'BackgroundColor', UserValues.Phasor.Settings_FRETColor(4,:),...
        'ForegroundColor', repmat(~(sum(UserValues.Phasor.Settings_FRETColor(4,:))>=1.5),[1 3]),...
        'Style', 'edit',...
        'Enable','inactive',...
        'String','Mixture',...
        'ButtonDownFcn',{@FRET_Look,1,4});
    h.FRET_Line(4,2) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.17 0.28 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETWidth{4},...
        'Callback',{@FRET_Look,2,4});
    h.FRET_Line(4,3) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.28 0.28 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETStyle{4},...
        'Callback',{@FRET_Look,3,4});
    h.FRET_Line(4,4) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.39 0.28 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETMarker{4},...
        'Callback',{@FRET_Look,4,4});
    h.FRET_Line(4,5) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.50 0.28 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Settings_FRETSize{4},...
        'Callback',{@FRET_Look,5,4});
    
    h.FRET_Pos(1,1) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.61 0.55 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String','0',...
        'Callback',{@Calc_FRET,9});
    h.FRET_Pos(1,2) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.72 0.55 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String','0',...
        'Callback',{@Calc_FRET,9});
    
    h.FRET_Pos(2,1) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.61 0.37 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String','0',...
        'Callback',{@Calc_FRET,9});
    h.FRET_Pos(2,2) = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.72 0.37 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'edit',...
        'String','0',...
        'Callback',{@Calc_FRET,9});
        %% FRET colormap setting
    %%% Determins FRET coloring type
    h.FRET_Use = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.01 0.19 0.20 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'popupmenu',...
        'String',{'No Color';'FRET Line';'FRET Spot'},...
        'Callback',{@Calc_FRET,8});
    if ismac
        h.FRET_Use.ForegroundColor = [0 0 0];
        h.FRET_Use.BackgroundColor = [1 1 1];
    end
    %%% Determins FRET colormap
    h.FRET_Color = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.22 0.19 0.1 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'popupmenu',...
        'Value', UserValues.Phasor.Settings_FRETLineColor,...
        'String',{'Jet';'Hot';'HSV';'Custom'},...
        'Callback',{@Calc_FRET,8});
    if ismac
        h.FRET_Color.ForegroundColor = [0 0 0];
        h.FRET_Color.BackgroundColor = [1 1 1];
    end
    %%% Determins minimum and maximum for FRET colormap
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.33 0.17 0.06 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'Style', 'text',...
        'String','Min:');
    h.FRET_Min = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.4 0.17 0.06 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'Edit',...
        'String','0',...
        'Callback',{@Calc_FRET,8});
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.47 0.17 0.06 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'Style', 'text',...
        'String','Max:');
    h.FRET_Max = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.54 0.17 0.06 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'Edit',...
        'String','30',...
        'Callback',{@Calc_FRET,8});
    uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.61 0.17 0.08 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'Style', 'text',...
        'String','Radius:');
    h.FRET_Size = uicontrol(...
        'Parent',h.FRET_Panel,...
        'Units','normalized',...
        'FontSize',12,...
        'Position',[0.70 0.17 0.06 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'Style', 'Edit',...
        'String', UserValues.Phasor.Settings_FRETRadius,...
        'Callback',{@Calc_FRET,8});
    %% Export settings tab
    h.Export_Tab=uitab(...
        'title','Export Settings',...
        'Tag','Export_Tab');
    %%% Panel for Export controls
    h.Export_Panel = uibuttongroup(...
        'Parent',h.Export_Tab,...
        'Units','normalized',...
        'BackgroundColor',Look.Back,...
        'ForegroundColor',Look.Fore,...
        'HighlightColor',Look.Control,...
        'ShadowColor',Look.Shadow,...
        'Position',[0 0 1 1],...
        'Tag','Export_Panel');
    %%% Text for export sizes
    uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.91 0.2 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Export size [px]:');  
    %%% Export axes size X
    h.Export_SizeX = uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.22 0.91 0.07 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'FontSize',12,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Export_SizeX,...
        'Callback', @(src,event) LSUserValues(1,src,{'String','Phasor','Export_SizeX'}));
    %%% Export axes size Y
    h.Export_SizeY = uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.30 0.91 0.07 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'FontSize',12,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Export_SizeY,...
        'Callback', @(src,event) LSUserValues(1,src,{'String','Phasor','Export_SizeY'}));
    %%% Text for export g limits
    uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.82 0.2 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Export g limits:');  
    %%% Export axes g limit low
    h.Export_GMin = uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.22 0.82 0.07 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'FontSize',12,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Export_GMin,...
        'Callback', @(src,event) LSUserValues(1,src,{'String','Phasor','Export_GMin'}));
    %%% Export axes g limit high
    h.Export_GMax = uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.30 0.82 0.07 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'FontSize',12,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Export_GMax,...
        'Callback', @(src,event) LSUserValues(1,src,{'String','Phasor','Export_GMax'}));
    %%% Text for export s limits
    uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.73 0.2 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Export s limits:');  
    %%% Export axes s limit low
    h.Export_SMin = uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.22 0.73 0.07 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'FontSize',12,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Export_SMin,...
        'Callback', @(src,event) LSUserValues(1,src,{'String','Phasor','Export_SMin'}));
    %%% Export axes s limit high
    h.Export_SMax = uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.30 0.73 0.07 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'FontSize',12,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Export_SMax,...
        'Callback', @(src,event) LSUserValues(1,src,{'String','Phasor','Export_SMax'}));
    %%% Text for Font name
 
    %%% Export Font Name
    h.Export_Font = uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'FontSize',UserValues.Phasor.Export_Font.FontSize,...
        'FontName',UserValues.Phasor.Export_Font.FontName,...
        'FontWeight',UserValues.Phasor.Export_Font.FontWeight,...
        'FontAngle',UserValues.Phasor.Export_Font.FontAngle,...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...        
        'Style','push',...
        'Callback',@Misc,...
        'String',UserValues.Phasor.Export_Font.FontString,...
        'UserData',UserValues.Phasor.Export_Font,...
        'Position',[0.01 0.58 0.36 0.13]);
    
    %%% Text for line export
    uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.41 0.91 0.25 0.07],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Line Export Points:');  
    %%% Export axes size X
    h.Export_Line_Points = uicontrol(...
        'Parent',h.Export_Panel,...
        'Units','normalized',...
        'Position',[0.67 0.91 0.07 0.07],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'FontSize',12,...
        'Style', 'edit',...
        'String',UserValues.Phasor.Export_LinePoints,...
        'Callback', @(src,event) LSUserValues(1,src,{'String','Phasor','Export_LinePoints'}));
    
%% Tabs for displaying images and other plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%% Tab container for image tabs
    h.Main_Tab=uitabgroup(...
        'Parent',h.Phasor,...
        'Tag','Main_Tab',...
        'Units','normalized',...
        'SelectionChangedFcn',{@Plot_Phasor,1,1:10},...
        'Position',[0 0.01 0.545 0.98]);
    
    %%% UiContextmenu associated with image plots
    h.Plots_Menu = uicontextmenu;
    %%% Exports Image as TIFF
    h.Export_Tif = uimenu(...
        'Parent',h.Plots_Menu,...
        'Label','Export image as TIFF',...
        'Tag','Export_Tif',...
        'Callback',{@Plots_Menu_Callback,1});
    h.Export_Fig = uimenu(...
        'Parent',h.Plots_Menu,...
        'Label','Export image to new figure',...
        'Tag','Export_Fig',...
        'Callback',{@Plots_Menu_Callback,2});
    %% Tab containing main plots
    h.Plots_Tab= uitab(...
        'Parent',h.Main_Tab,...
        'title','Plots',...
        'ToolTipString', ['<html>'...
                        'Displays up to 9 selected images (blue font) at once <br>',...
                        'Data is calculated for all enabled files (blue and red font)'],...
        'Tag','Plots_Tab'); 
    %%% Panel containing all plots
    h.Plots_Panel = uibuttongroup(...
        'Parent',h.Plots_Tab,...
        'Units','normalized',...
        'BackgroundColor',Look.Back,...
        'ForegroundColor',Look.Fore,...
        'HighlightColor',Look.Control,...
        'ShadowColor',Look.Shadow,...
        'Position',[0 0 1 1],...
        'Tag','Plots_Panel');

    for i=1:9
        %%% Panel containing Image Plot i
        h.Image_Panel(i) = uibuttongroup(...
            'Parent',h.Plots_Panel,...
            'Units','normalized',...
            'Title',num2str(i),...
            'BackgroundColor',Look.Back,...
            'ForegroundColor',Look.Fore,...
            'HighlightColor',Look.Control,...
            'ShadowColor',Look.Shadow,...
            'Position',[0.01+(mod(i-1,3))*0.33 0.67-(floor((i-1)/3))*0.33 0.32 0.32],...
            'Tag',['Image_Panel_' num2str(i)]);
        %%% Axes for plotig image i
        h.Image_Plot(i,1) = axes(...
            'Parent',h.Image_Panel(i),...
            'Units','normalized',...
            'Position',[0.02 0.02 0.96 0.96],...
            'UIContextMenu',h.Plots_Menu,...
            'Tag',['Imagage_Plot' num2str(i)]);
        h.Image_Plot(i,2)=image(zeros(1,1,3),'HitTest','off');   
        h.Image_Plot(i,1).DataAspectRatio=[1 1 1];
        h.Image_Plot(i,1).XTick=[];
        h.Image_Plot(i,1).YTick=[];
    end
    %% Tab containing Single plot
    h.Single_Tab= uitab(...
        'Parent',h.Main_Tab,...
        'title','Single',...
        'ToolTipString', ['<html>'...
                        'Displays only first selected file <br>',...
                        'Data is calculated only for this file <br>'...
                        'If a subregion is selected, data is only calculated for subregion'],...
        'Tag','Single_Tab'); 
    %%% Panel containing Single plot 
    h.Single_Panel = uibuttongroup(...
        'Parent',h.Single_Tab,...
        'Units','normalized',...
        'BackgroundColor',Look.Back,...
        'ForegroundColor',Look.Fore,...
        'HighlightColor',Look.Control,...
        'ShadowColor',Look.Shadow,...
        'Position',[0 0 1 1],...
        'Tag','Single_Panel');
    %%% Axis for Single plot
    h.Image_Plot(10,1) = axes(...
        'Parent',h.Single_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.21 0.98 0.78],...
        'UIContextMenu',h.Plots_Menu,...
        'Tag','Imagage_Plot10');
    h.Image_Plot(10,2)=image(zeros(1,1,3),'HitTest','off');
    h.Image_Plot(10,1).DataAspectRatio=[1 1 1];
    h.Image_Plot(10,1).XTick=[];
    h.Image_Plot(10,1).YTick=[];
    h.Image_Plot(10,1).ButtonDownFcn=@Select_Region;
    %%% Text for Selection size
    uicontrol(...
        'Parent',h.Single_Panel,...
        'Units','normalized',...
        'Position',[0.01 0.17 0.15 0.025],...
        'BackgroundColor', Look.Back,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','left',...
        'FontSize',12,...
        'Style', 'text',...
        'String','Selection Size:');
    %%% Text for Selection size
    h.Single_Selection_Size = uicontrol(...
        'Parent',h.Single_Panel,...
        'Units','normalized',...
        'Position',[0.16 0.17 0.1 0.025],...
        'BackgroundColor', Look.Control,...
        'ForegroundColor', Look.Fore,...
        'HorizontalAlignment','center',...
        'FontSize',12,...
        'Style', 'edit',...
        'String','10');
    %% Tab for displaying intensity distribution
    h.Int_Tab= uitab(...
        'Parent',h.Main_Tab,...
        'title','Intensity',...
        'ToolTipString', ['<html>Displays plots for intensity dependence of parameters'],...
        'Tag','Int_Tab'); 
    %%% Panel containing Intensity plot 
    h.Int_Panel = uibuttongroup(...    
        'Parent',h.Int_Tab,...
        'Units','normalized',...
        'BackgroundColor',Look.Back,...
        'ForegroundColor',Look.Fore,...
        'HighlightColor',Look.Control,...
        'ShadowColor',Look.Shadow,...
        'Position',[0 0 1 1],...
        'Tag','Int_Panel');
    %%% Axis for Intensity plot
    h.Int_Plot(1) = axes(...
        'Parent',h.Int_Panel,...
        'Units','normalized',...
        'Nextplot','add',...
        'XColor',Look.Fore,...
        'YColor',Look.Fore,...
        'Position',[0.09 0.21 0.89 0.76]);
    h.Int_Plot(1).XLabel.String = 'Counts per pixel';
    h.Int_Plot(1).YLabel.String = 'Frequency [Pixels]';
    h.Int_Plot(1).XLabel.Color = Look.Fore;
    h.Int_Plot(1).YLabel.Color = Look.Fore;
    
    h.Int_Plot(2) = plot([0 1], [0 0],'Color','k');
    h.Int_Plot(3) = plot([0 1], [0 0],'Color','r');
    h.Int_Plot(4) = plot([0 1], [0 0],'Color','g');
    h.Int_Plot(5) = plot([0 1], [0 0],'Color','b');
    h.Int_Plot(6) = plot([0 1], [0 0],'Color','m');
    h.Int_Plot(7) = plot([0 1], [0 0],'Color','y');
    h.Int_Plot(8) = plot([0 1], [0 0],'Color','c');
    h.Int_Plot(9) = imagesc(...
        'Parent',h.Int_Plot(1),...
        'Visible','off',...
        'CData',zeros(1));
    
    h.Int_Type = uicontrol(...
        'Parent',h.Int_Tab,...
        'Units','normalized',...
        'BackgroundColor',Look.Control,...
        'ForegroundColor',Look.Fore,...
        'Style','popup',...
        'String',{'Frequency','Mean G','Mean S','G','S'},...
        'Callback', {@Plot_Phasor,0,[]},...
        'Position',[0.01 0.14 0.22 0.025]);
    if ismac
        h.Int_Type.ForegroundColor = [0 0 0];
        h.Int_Type.BackgroundColor = [1 1 1];
    end
    h.Int_Norm = uicontrol(...
        'Parent',h.Int_Tab,...
        'Units','normalized',...
        'BackgroundColor',Look.Control,...
        'ForegroundColor',Look.Fore,...
        'Style','popup',...
        'String',{'No normalization','Area normalization','Maximum normalization'},...
        'Callback', {@Plot_Phasor,0,[]},...
        'Position',[0.01 0.105 0.22 0.025]);
    if ismac
        h.Int_Norm.ForegroundColor = [0 0 0];
        h.Int_Norm.BackgroundColor = [1 1 1];
    end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%     

%% Mac upscaling of Font Sizes
if ismac
    scale_factor = 1.3;
    fields = fieldnames(h); %%% loop through h structure
    for i = 1:numel(fields)
        if numel(h.(fields{i})) == 1
            if isprop(h.(fields{i}),'FontSize')
                h.(fields{i}).FontSize = (h.(fields{i}).FontSize)*scale_factor;
            end
        else
            for j = 1:numel(h.(fields{i}))
                 if isprop(h.(fields{i})(j),'FontSize')
                h.(fields{i})(j).FontSize = (h.(fields{i})(j).FontSize)*scale_factor;
            end
            end
        end
    end
end
%% Initializes global Variables and setting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PhasorData=[];
PhasorData.Data=[];
PhasorData.Files={};
PhasorData.List={};
PhasorData.Selected=[];
PhasorData.Plot=zeros(10,1);
PhasorData.PlotType=0;
PhasorData.Timer=cputime;
PhasorData.Selected_Region=[];
PhasorData.Type = 1;

%%% Applies ROI settings to ROIS
for i=1:6
    h.Phasor_ROI(i,1).EdgeColor=h.ROI_Color{i}.BackgroundColor;
    h.Phasor_ROI(i,2).Color=h.ROI_Color{i}.BackgroundColor;
    h.Phasor_ROI(i,1).LineWidth=str2double(h.ROI_Width{i}.String);
    h.Phasor_ROI(i,2).LineWidth=str2double(h.ROI_Width{i}.String);
    h.Phasor_ROI(i,1).LineStyle=h.ROI_Style{i}.String;
    h.Phasor_ROI(i,2).LineStyle=h.ROI_Style{i}.String;
    h.Phasor_ROI(i,2).UserData = [0 0.1 0 0.1];
end
h.Phasor_Fraction.Color=h.ROI_Color{7}.BackgroundColor;
h.Phasor_Fraction.LineWidth=str2double(h.ROI_Width{7}.String);
h.Phasor_Fraction.LineStyle=h.ROI_Style{7}.String;
%%% Applies FRET settings to lines
for i=1:4
    h.Phasor_FRET(i,1).LineWidth=str2double(h.FRET_Line(i,2).String);
    h.Phasor_FRET(i,1).LineStyle=h.FRET_Line(i,3).String;
    h.Phasor_FRET(i,2).Marker=h.FRET_Line(i,4).String;
    h.Phasor_FRET(i,1).MarkerSize=str2double(h.FRET_Line(i,5).String);
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Defines custom cursor shapes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

PhasorData.Cursor=[];
    %%%%1
    Point=zeros(16);
    Point(1:8,1:2)=1;
    Point(1:2,1:8)=1;
    Point(5,8:11)=1;
    Point(6,7:11)=1;
    Point(7,6:11)=1;
    Point(8,[5:7 10:11])=1;
    Point(9,[5:6 10:11])=1;
    Point(10:14,10:11)=1;
    Point(15:16,7:14)=1; 
    Point(Point==0)=NaN;
    PhasorData.Cursor{1}=Point;

    %%%%2
    Point=zeros(16);
    Point(1:8,1:2)=1;
    Point(1:2,1:8)=1;
    Point([5:6 10:11 15:16],5:11)=1;
    Point(10:16,5:6)=1;
    Point(5:11,10:11)=1;
    Point(Point==0)=NaN;
    PhasorData.Cursor{2}=Point;
            
    %%%%3 
    Point=zeros(16);
    Point(1:8,1:2)=1;
    Point(1:2,1:8)=1;
    Point([5:6 10:11 15:16],5:11)=1;
    Point(5:16,10:11)=1;
    Point(Point==0)=NaN;
    PhasorData.Cursor{3}=Point;
    
    %%%%4
    Point=zeros(16);
    Point(1:8,1:2)=1;
    Point(1:2,1:8)=1;
    Point(5:16,10:11)=1;
    Point(5:11,5:6)=1;
    Point(10:11,5:11)=1;
    Point(Point==0)=NaN;
    PhasorData.Cursor{4}=Point; 
    
    %%%%5
    Point=zeros(16);
    Point(1:8,1:2)=1;
    Point(1:2,1:8)=1;
    Point([5:6 10:11 15:16],5:11)=1;
    Point(5:11,5:6)=1;
    Point(11:16,10:11)=1;
    Point(Point==0)=NaN;
    PhasorData.Cursor{5}=Point;
    
    %%%%6
    Point=zeros(16);
    Point(1:8,1:2)=1;
    Point(1:2,1:8)=1;
    Point([5:6 10:11 15:16],5:11)=1;
    Point(5:16,5:6)=1;
    Point(11:16,10:11)=1;
    Point(Point==0)=NaN;
    PhasorData.Cursor{6}=Point;  
    
    %%%%7 display R
    Point=zeros(16);
%     Point(1:8,1:2)=1;
%     Point(1:2,1:8)=1;
%     Point(5:6,5:11)=1;
%     Point(5:16,10:11)=1;
    Point(1:8,1:2)=1;
    Point(1:2,1:8)=1;
    Point(4:16,5:6)=1;
    Point(4:5,5:16)=1;
    Point(4:10,15:16)=1;
    Point(11:12,5:16)=1;
    Point(12,6:8)=1;
    Point(13,8:10)=1;
    Point(14,10:12)=1;
    Point(15,12:14)=1;
    Point(16,14:16)=1;
    Point(Point==0)=NaN;
    PhasorData.Cursor{7}=Point;
    
    %%%%8 display G
     Point=zeros(16);
%     Point(1:8,1:2)=1;
%     Point(1:2,1:8)=1;
%     Point([5:6 10:11 15:16],5:11)=1;
%     Point(5:16,10:11)=1;
%     Point(5:16,5:6)=1;
    Point(1:8,1:2)=1;
    Point(1:2,1:8)=1;
    Point(4:16,5:6)=1;
    Point(4:5,5:16)=1;
    Point(15:16,5:16)=1;
    Point(4:7,15:16)=1;
    Point(11:16,15:16)=1;
    Point(11:12,11:16)=1;
%     Point(1:5,14:16)=1;
%     Point(9:16,14:16)=1;
%     Point(9:11,10:16)=1;

     Point(Point==0)=NaN;
    PhasorData.Cursor{8}=Point;  
    
    %%%%9 display B
    Point=zeros(16);
%     Point(1:8,1:2)=1;
%     Point(1:2,1:8)=1;
%     Point([5:6 10:11 15:16],5:11)=1;
%     Point(5:10,5:6)=1;
%     Point(5:16,10:11)=1;
    Point(1:8,1:2)=1;
    Point(1:2,1:8)=1;
    Point(4:16,5:6)=1;
    Point(4:5,5:16)=1;
    Point(15:16,5:16)=1;
    Point(4:9,15:16)=1;
    Point(11:16,15:16)=1;
    Point(9:11,5:14)=1;
    Point(9,16)=0;
    Point(4,16)=0;
    Point(11,16)=0;
    Point(16,16)=0;
    Point(Point==0)=NaN;
    PhasorData.Cursor{9}=Point;  
%%    
guidata(h.Phasor,h); 




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Loades referenced files %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Load_Phasor_Data(~,~)
h = guidata(findobj('Tag','Phasor'));
global PhasorData UserValues
LSUserValues(0);

%%% Choose files to load
[FileName,PathName,Type] = uigetfile({'*.phr'; '*.phs'}, 'Choose a referenced data file', UserValues.File.PhasorPath, 'MultiSelect', 'on');
%%% Tranforms to cell array, if only one file was selected
if ~iscell(FileName)
    FileName = {FileName};
end
%%% Only esecutes, if at least one file was selected
if all(FileName{1}==0)
    return
end
%%% Saves Path
UserValues.File.PhasorPath=PathName;
LSUserValues(1);

%%% Removes Lifetime/Spectral data if the other was loaded
if PhasorData.Type ~= Type
    PhasorData.Data=[];
    PhasorData.Files={};
    PhasorData.List={};
    PhasorData.Selected=[];
    PhasorData.Plot=zeros(10,1);
    PhasorData.PlotType=0;
    PhasorData.Timer=cputime;
    PhasorData.Selected_Region=[];
    PhasorData.Type = Type;
    switch PhasorData.Type
        case 1
            h.Phasor_Plot.XLim = [-0.1 1.2];
            h.Phasor_Plot.YLim = [-0.1 1.2];
        case 2
            h.Phasor_Plot.XLim = [-1 1];
            h.Phasor_Plot.YLim = [-1 1];
    end
end

free=[];
for i=1:numel(FileName)
    %%% Loades Data
    PhasorData.Data{end+1}=load([PathName FileName{i}],'-mat');
    
    
    %%% Saves filename in global data
    PhasorData.Files{end+1,1}=FileName{i};
    PhasorData.Files{end,2}=PathName;
    %%% Global variable for selectiong individual regions
    PhasorData.Selected_Region{end+1}=false(size(PhasorData.Data{end}.g));
    %%% Uses file for phasor calculation
    PhasorData.Selected(end+1)=1;
    if sum(PhasorData.Plot~=0)<=9
        %%% Plots file in first free image plot
        free(end+1)=find(PhasorData.Plot==0,1,'first'); %#ok<AGROW>
        PhasorData.Plot(free(end))=numel(PhasorData.Data);
        %%% Changes filename to blue, to indicate that it is plotted
        PhasorData.List{end+1}=['<HTML><FONT color="blue">' FileName{i} ' Plot: ' num2str(free(end)) '</Font></html>'];
    else
        %%% Changes filename to red, if no free plots are available
        PhasorData.List{end+1}=['<HTML><FONT color="red">' FileName{i} '</Font></html>'];
    end
    %%% Create a Center of Mass entry
    PhasorData.CoM{numel(PhasorData.List)} = scatter(0.5,0.5,'+','Parent',h.Phasor_Plot,'CData',[1 1 1], 'LineWidth',3','SizeData',200);
    Update_CoM([],[],numel(PhasorData.List),1:2);
end
%%% Updates list
h.List.String=PhasorData.List;
%%% Selects the last enty in list
h.List.Value=size(PhasorData.Files,1);

%%% Starts plotting; plots phasor and the new images (free)
Plot_Phasor([],[],1,[free 10]);



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Deletes\Selects\Unselects files for plotting %%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function List_Callback(Obj,e)
h = guidata(findobj('Tag','Phasor'));
global PhasorData UserValues
%%% Only executes if a valid key was pressed
if ~isempty(h.List.String) && isprop(e,'Key') && any(strcmp(e.Key,{'delete','rightarrow','leftarrow','add'}))
    
    %%% Finds selected files
    selected=h.List.Value;  
    %%% Inverts files for deleting
    if strcmp(e.Key, 'delete')
        selected=sort(selected,2,'descend');
    end
    %%% Selects first file, if none was selected (to prevent errors)
    if isempty(selected)
        selected=1;
    end    
    free=[];
    %%% For each selected file
    for i=selected
        switch e.Key
            case 'delete' 
                %% Deletes files
                plotted=find(PhasorData.Plot(1:9)==i,1,'first');
                %%% Removes plot
                if ~isempty(plotted)
                    h.Image_Plot(plotted,2).CData=zeros(1,1,3);
                    h.Image_Plot(plotted,1).XLim=[0.5,1.5];
                    h.Image_Plot(plotted,1).YLim=[0.5,1.5];
                    h.Image_Panel(plotted).Title=num2str(plotted);
                    PhasorData.Plot(plotted)=0;
                end
                %%% Remove file information
                PhasorData.Data(i)=[];
                PhasorData.Files(i,:)=[];
                PhasorData.Selected(i)=[];
                PhasorData.List(i)=[];
                PhasorData.Selected_Region(i)=[];
                %%% Changes plot pointer to new file list
                PhasorData.Plot(PhasorData.Plot>i)=PhasorData.Plot(PhasorData.Plot>i)-1;
                delete(PhasorData.CoM{i});
                PhasorData.CoM(i)=[];
            case 'rightarrow'
                %% Plots file
                PhasorData.Selected(i)=1;
                plotted=find(PhasorData.Plot(1:9)==i,1,'first');
                %%% Plots file if free plot is available
                if isempty(plotted) && any(PhasorData.Plot==0)
                    free(end+1)=find(PhasorData.Plot==0,1,'first');
                    PhasorData.Plot(free(end))=i;                    
                    PhasorData.List{i}=['<HTML><FONT color="blue">' PhasorData.Files{i,1} ' Plot: ' num2str(free(end)) '</Font></html>'];
                %%% Only uses file for phasor plot, if no free plot is available
                elseif isempty(plotted)
                    PhasorData.List{i}=['<HTML><FONT color="red">' PhasorData.Files{i,1} '</Font></html>'];     
                end
            case 'leftarrow' 
                %% Unselects file
                plotted=find(PhasorData.Plot(1:9)==i,1,'first');
                %%% Removes plot
                if ~isempty(plotted)
                    h.Image_Plot(plotted,2).CData=zeros(1,1,3);
                    h.Image_Plot(plotted,1).XLim=[0.5,1.5];
                    h.Image_Plot(plotted,1).YLim=[0.5,1.5];
                    h.Image_Panel(plotted).Title=num2str(plotted);
                    PhasorData.Plot(plotted)=0;                
                end
                %%% Does not use file for phasor calculation
                PhasorData.Selected(i)=0;
                PhasorData.List{i}=PhasorData.Files{i,1};                
            case 'add'
                %% Uses file for phasor plot, but not for plotting
                plotted=find(PhasorData.Plot(1:9)==i,1,'first');
                %%% Removes plot
                if ~isempty(plotted)
                    h.Image_Plot(plotted,2).CData=zeros(1,1,3);
                    h.Image_Plot(plotted,1).XLim=[0.5,1.5];
                    h.Image_Plot(plotted,1).YLim=[0.5,1.5];
                    h.Image_Panel(plotted).Title=num2str(plotted);
                    PhasorData.Plot(plotted)=0;                                
                end
                PhasorData.Selected(i)=1;
                PhasorData.List{i}=['<HTML><FONT color="red">' PhasorData.Files{i,1} '</Font></html>'];                
        end
    end
    %%% Updates list
    h.List.String= PhasorData.List;
    %%% Makes sure, not nonexistent file is selected
    if max(h.List.Value)>numel(PhasorData.List)
        h.List.Value=numel(PhasorData.List);        
    end
    
    %%% Starts plotting; plots phasor and the new images (free)
    Plot_Phasor(h.List,[],1,[free 10]);   
elseif ~isempty(h.List.String) && ~isprop(e,'Key') %%% UIContextMenu
    switch Obj
        case h.Average_Data %%% Moving average of phasor data
            %%% Finds selected files
            Sel = h.List.Value;
            for i = Sel
                %%% Loades Data
                PhasorData.Data{end+1} = PhasorData.Data{i};
                PhasorData.Files{end+1,1} = [PhasorData.Files{i,1} ' (Avg)'];
                PhasorData.Files{end,2} = PhasorData.Files{i,2};
                PhasorData.Selected_Region{end+1} = false(size(PhasorData.Data{end}.g));
                
                G = PhasorData.Data{end}.g; G(end+2,end+2) = 0;
                S = PhasorData.Data{end}.s; S(end+2,end+2) = 0;
                Int = PhasorData.Data{end}.Intensity; Int(end+2,end+2) = 0;
                
                g=zeros(size(G));
                s=zeros(size(G));
                int=zeros(size(Int));
                
                %%% Applies moving average to data
                for j=0:2
                    for k=0:2
                        g=g+circshift(G.*Int,[j,k,0]);
                        s=s+circshift(S.*Int,[j,k,0]);
                        int=int+circshift(Int,[j,k,0]);
                    end
                end
                g=g./int; g(isnan(g))=0;
                s=s./int; s(isnan(s))=0;
                PhasorData.Data{end}.g=g(2:end-1,2:end-1);
                PhasorData.Data{end}.s=s(2:end-1,2:end-1);
                %%% Uses file for phasor calculation
                PhasorData.Selected(end+1)=1;
                if sum(PhasorData.Plot(1:9)~=0)<9
                    %%% Plots file in first free image plot
                    free=find(PhasorData.Plot(1:9)==0,1,'first');
                    PhasorData.Plot(free)=numel(PhasorData.Data);
                    %%% Changes filename to blue, to indicate that it is plotted
                    PhasorData.List{end+1}=['<HTML><FONT color="blue">' PhasorData.Files{end,1} ' Plot: ' num2str(free(end)) '</Font></html>'];
                else
                    %%% Changes filename to red, if no free plots are available
                    free = [];
                    PhasorData.List{end+1}=['<HTML><FONT color="red">' PhasorData.Files{end,1} '</Font></html>'];
                end
                %%% Updates list
                h.List.String=PhasorData.List;
                %%% Selects the last enty in list
                h.List.Value=size(PhasorData.Files,1);
                
                %%% Create a Center of Mass entry
                PhasorData.CoM{numel(PhasorData.List)} = scatter(0.5,0.5,'+','Parent',h.Phasor_Plot,'CData',[1 1 1], 'LineWidth',3','SizeData',200);
                %%% Starts plotting; plots phasor and the new images (free)
                Plot_Phasor(h.List,[],1,[free 10]);
            end
        case h.Export_ROIs %%% Reloads raw data and saves the selected ROI photons
            %%% Finds first selected file
            Sel = h.List.Value(1);
            
%             Pam = findobj('Tag','Pam');
%             if ~isempty(Pam);
%                 close(Pam);
%             end
            
            global TcspcData FileInfo %#ok<TLEV>
            UserValues.File.Path = PhasorData.Data{Sel}.Path;
            LSUserValues(1);
            %%% Loads original data
            if isfield(PhasorData.Data{Sel},'Type')
                LoadTcspc([],[],[],[],[],0,h.Phasor,PhasorData.Data{Sel}.FileNames,PhasorData.Data{Sel}.Type)
            else
                LoadTcspc([],[],[],[],[],0,h.Phasor)
            end
            
            
            %%% Extracts mask for ROIs
            Pixel=str2double(h.Phasor_Res.String);
            THmin=str2double(h.THmin.String);
            THmax=str2double(h.THmax.String);
            Mask = cell(6,1);
            for j=1:6
                if strcmp(h.Phasor_ROI(j,1).Visible,'on')
                    %% Rectangular ROI
                    Pos=h.Phasor_ROI(j,1).Position;
                    %%% Generates ROI map
                    ROI= PhasorData.Data{Sel}.g>=Pos(1) &...
                        PhasorData.Data{Sel}.g<=(Pos(1)+Pos(3)) &...
                        PhasorData.Data{Sel}.s>=Pos(2) &...
                        PhasorData.Data{Sel}.s<=(Pos(2)+Pos(4)) &...
                        PhasorData.Data{Sel}.Intensity >= THmin &...
                        PhasorData.Data{Sel}.Intensity <= THmax;
                    ROI = ROI & ~PhasorData.Selected_Region{Sel};
                    Mask{j} = find(flip(ROI',2));
                elseif strcmp(h.Phasor_ROI(j,2).Visible,'on')
                    %% Ellipoid ROI
                    %%% Determins position of ROI
                    x=round(Pixel*(h.Phasor_ROI(j,2).XData+0.1));
                    y=round(Pixel*(h.Phasor_ROI(j,2).YData+0.1));
                    x(x<1)=1; y(y<1)=1;
                    Map=zeros(1.3*Pixel);
                    %%% Transforms ROI position into pixelmap
                    Map(sub2ind(size(Map),x,y))=1;
                    %%% Fills ROI pixelmap
                    Map=mod(cumsum(Map),2);
                    %%% Finds valid pixel
                    G=round((PhasorData.Data{Sel}.g+0.1)*Pixel);
                    G(isnan(G) | G<1)=1;
                    S=round((PhasorData.Data{Sel}.s+0.1)*Pixel);
                    S(isnan(S) | S<1)=1;
                    %%% Generates ROI map
                    ROI=Map(sub2ind(size(Map),G,S))==1 &...
                        PhasorData.Data{Sel}.Intensity >= THmin &...
                        PhasorData.Data{Sel}.Intensity <= THmax;
                    Mask{j} = find(flip(ROI',2));
                end
            end
%             %%% Calculate pixel times
%             Pixeltimes=0;
%             for j=1:FileInfo.Lines
%                 Pixeltimes(end:(end+FileInfo.Lines))=linspace(FileInfo.LineTimes(j),FileInfo.LineTimes(j+1),FileInfo.Lines+1);
%             end
            
            %%% Extracts photons for each ROI
            Mask_MT = cell(numel(TcspcData.MT),6);
            Mask_MI = cell(numel(TcspcData.MI),6);
            for i=1:numel(TcspcData.MT)
                if ~isempty(TcspcData.MT{i})
                    [~,Bin] = CalculateImage(TcspcData.MT{i}.*FileInfo.ClockPeriod,2);
                    for k=1:6
                        if ~isempty(Mask{k})
                            Bin_ROI = Bin;
                            Bin_ROI(~ismember(Bin_ROI,Mask{k}))=0;
                            Mask_MT{i,k}=TcspcData.MT{i}(Bin_ROI~=0);
                            Mask_MI{i,k}=TcspcData.MI{i}(Bin_ROI~=0);
                        end
                    end
                end
            end
            %%% Saves Files
            for i=1:6
                if ~isempty(Mask{i})
                    MT = reshape(Mask_MT(:,i),size(TcspcData.MT));
                    MI = reshape(Mask_MI(:,i),size(TcspcData.MI));
                    Info = FileInfo;
                    save(fullfile(PhasorData.Files{Sel,2},[PhasorData.Files{Sel,1}(1:end-4) '_ROI' num2str(i) '.ppf']),'MT','MI','Info');
                end
            end
        case h.Export_Fraction %%% Exports histogram along fraction line
           
            if strcmp(h.Phasor_FRET(2,1).Visible, 'on') %%%FRET line
                
                Pixel=str2double(h.Phasor_Res.String);
                THmin=str2double(h.THmin.String);
                THmax=str2double(h.THmax.String);
                Sel = h.List.Value;

                %%% Calculate Map
                Width=str2double(h.ROI_Size{7}.String);
                
                x=h.Phasor_FRET(2,1).XData;
                y=h.Phasor_FRET(2,1).YData;
                PT=interparc(str2double(h.Export_Line_Points.String),x,y);
                x=PT(:,1); y=PT(:,2);
                
                step=1/Pixel;
                X=-0.1:step:1.2; X = single(reshape(X,[1, numel(X),1]));
                Y=-0.1:step:1.2; Y = single(reshape(Y,[numel(Y),1 ,1]));
                Z1 = single(reshape(x,[1, 1,numel(x)]));
                Z2 = single(reshape(y,[1, 1,numel(y)]));
                
                Dist =  (repmat(X,size(Y,1),1,size(Z1,3))-repmat(Z1,size(Y,1),size(X,2),1)).^2;
                Dist = sqrt(Dist + (repmat(Y,1,size(X,2),size(Z2,3))-repmat(Z2,size(Y,1),size(X,2),1)).^2);
                
                [Min,Ind]=min(double(Dist),[],3);
                Map=(Ind.*(Min<=Width))';
                
                j=1;
                for i=Sel
                    %%% Finds valid pixel
                    G=round((PhasorData.Data{i}.g+0.1)*Pixel);
                    G(isnan(G) | G<1)=1;
                    S=round((PhasorData.Data{i}.s+0.1)*Pixel);
                    S(isnan(S) | S<1)=1;
                    %%% Generates ROI map
                    roi=Map(sub2ind(size(Map),G,S));
                    roi = roi.*(~PhasorData.Selected_Region{i} &...
                        PhasorData.Data{i}.Intensity >= THmin &...
                        PhasorData.Data{i}.Intensity <= THmax);
                    Fraction.ROI = roi;
                    Fraction.Hist = hist(roi(roi>0),1:str2double(h.Export_Line_Points.String))';
                    Fraction.Lim = [x(1) y(1) x(end) y(end) THmin THmax Width];
                    
                    AVG=0;
                    Name=PhasorData.Files{i,1};
                    while numel(Name)>5 && strcmp(Name((end-5):end),' (Avg)')
                        AVG=AVG+1;
                        Name=Name(1:end-6);
                    end
                    
                    if ~isstrprop(Name(1), 'alpha')
                        Name = ['File_' Name];
                    end
                    
                    if AVG==0
                        assignin('base',[Name(1:end-4) '_Fraction'],Fraction);
                    else
                        assignin('base',[Name(1:end-4) '_AVG' num2str(AVG) '_Fraction'],Fraction);
                    end
                    
                    Fraction_Total(:,j)=Fraction.Hist; j=j+1; %#ok<AGROW>
                end
                assignin('base','Fraction_Total',Fraction_Total);
            elseif strcmp(h.Phasor_Fraction.Visible,'on') %%% Fraction Line
                %%% Rotation with complex numbers
                THmin=str2double(h.THmin.String);
                THmax=str2double(h.THmax.String);
                Sel = h.List.Value;
                Width=str2double(h.ROI_Size{7}.String);
                
                x=h.Phasor_Fraction.XData;
                y=h.Phasor_Fraction.YData;
                Fraction.Lim = [x(1) y(1) x(end) y(end) THmin THmax Width];
                %%% transforms phasor to complex number
                Complex_Line = x+sqrt(-1)*y;
                
                %%% Calculates rotation coefficients
                k=diff(x)/diff(y); Scale = 1/sqrt(k^2+1);
                %%% Rotats fraction line
                Complex_Line = Complex_Line*Scale*(1+k*sqrt(-1));
                %%% transforms complex number to phasor
                x = real(Complex_Line);
                y = imag(Complex_Line);
  
                
                %%% Calculates position for each selected file
                j=1;
                for i=Sel
                   %%% Transforms phasor into a complex number
                   Complex = PhasorData.Data{i}.g + sqrt(-1)*PhasorData.Data{i}.s;
                   %%% Rotates Phasor
                   Complex = Complex*Scale*(1+k*sqrt(-1));
                   %%% transforms complex back to phasor
                   g = real(Complex);
                   s = imag(Complex);
                   
                   %%% Position relative to the line
                   Pos = (s-y(1))/(y(2)-y(1));
                   Dist = abs(x(1)-g);
                   
                   %%% Removes pixels below threshold and too far away
                   Pos(PhasorData.Data{i}.Intensity < THmin |...
                       PhasorData.Data{i}.Intensity > THmax |...
                       Dist > Width) = NaN;
                   
                   Fraction.ROI = Pos;
                   Fraction.Hist = histcounts(Pos,linspace(0,1,str2double(h.Export_Line_Points.String)+1))';
                   
                   %%% adjusts name for exporting
                   AVG=0;
                   Name=PhasorData.Files{i,1};
                   while numel(Name)>5 && strcmp(Name((end-5):end),' (Avg)')
                       AVG=AVG+1;
                       Name=Name(1:end-6);
                   end
                   if ~isstrprop(Name(1), 'alpha')
                       Name = ['File_' Name];
                   end
                   
                   %%% exports individual data to workspace
                   if AVG==0
                       assignin('base',[Name(1:end-4) '_Fraction'],Fraction);
                   else
                       assignin('base',[Name(1:end-4) '_AVG' num2str(AVG) '_Fraction'],Fraction);
                   end
                   
                   %%% exports collected data to workspace
                   Fraction_Total(:,j)=Fraction.Hist; j=j+1; %#ok<AGROW>
                   assignin('base','Fraction_Total',Fraction_Total);
                end
            end           
        case h.Export_Hist %%% Exports full histogram to workspace
            Pixel=str2double(h.Phasor_Res.String);
            THmin=str2double(h.THmin.String);
            THmax=str2double(h.THmax.String);
            Sel = h.List.Value;
            
            for i=Sel                
                g=PhasorData.Data{i}.g(...
                    PhasorData.Data{i}.Intensity>=THmin &...
                    PhasorData.Data{i}.Intensity<=THmax &...
                    ~PhasorData.Selected_Region{i});
                s=PhasorData.Data{i}.s(...
                    PhasorData.Data{i}.Intensity>=THmin &...
                    PhasorData.Data{i}.Intensity<=THmax &...
                    ~PhasorData.Selected_Region{i});
                %%%% Removes all pixels oudside of reasonable bounds
                s=s(g>-0.1); g=g(g>-0.1);
                s=s(g<=1.2); g=g(g<=1.2);
                g=g(s>-0.1); s=s(s>-0.1);
                g=g(s<=1.2); s=s(s<=1.2);
                %%% Removes all pixel at (0,0) (usually NaN)
                NaNs=~(s==0 & g==0);
                g=g(NaNs); s=s(NaNs);
                %%% Histograms phasor plot
                g=floor(Pixel*(g+0.1));
                s=floor(Pixel*(s+0.1));
                Hist=g+1.3*Pixel*s;
                Hist=histc(Hist,0:((1.3*Pixel)^2-1));
                %%% Reshape pixels
                PhasorImage=reshape(Hist,1.3*Pixel,1.3*Pixel);
                PhasorImage=permute(PhasorImage,[2 1]);
                
                AVG=0;
                Name=PhasorData.Files{i,1};
                while numel(Name)>5 && strcmp(Name((end-5):end),' (Avg)')
                    AVG=AVG+1;
                    Name=Name(1:end-6);
                end
                
                if ~isstrprop(Name(1), 'alpha')
                    Name = ['File_' Name];
                end
                
                if AVG==0
                    assignin('base',[Name(1:end-4) '_Phasor'],PhasorImage);
                else
                    assignin('base',[Name(1:end-4) '_AVG' num2str(AVG) '_Phasor'],PhasorImage);
                end
            end
            
            XData = linspace(-0.1,1.2,1.3*Pixel);
            YData = linspace(-0.1,1.2,1.3*Pixel);
            assignin('base','XData',XData);
            assignin('base','YData',YData);
            
            XData = h.Universal_Circle.XData;
            YData = h.Universal_Circle.YData;
            assignin('base','Circle_XData',XData);
            assignin('base','Circle_YData',YData);
        case h.Export_LifetimeIm %%% Exports TauM, TauP and Intensity Values
            Sel = h.List.Value;           
            for i=Sel                
                TauP=PhasorData.Data{i}.TauP;
                TauM=PhasorData.Data{i}.TauM;
                Intensity=PhasorData.Data{i}.Intensity;
                [FileName,Path] = uiputfile('*.mat', PhasorData.Files{i, 1}, PhasorData.Files{i, 2});
                if ~(isequal(FileName,0) || isequal(Path,0))
                    f = strcat(Path,FileName);
                    save(f,'TauP', 'TauM','Intensity');
                end
            end
    end
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Callbacks for mouseclicks in the phasor plot %%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Normal:
%   Left:           Pans plot
%   Right:          Opens context menu
%   Middle/Both:    Resets axes limits
%   Double:         Copies plot to new figure
%%% Key 1-6:
%   Left:           Rectangular ROI
%   Right:          Ellipoidal ROI
%%% Key 0:          Fraction Line
function Phasor_Plot_Callback(~,~,Key)
global UserValues
h=guidata(findobj('Tag','Phasor'));

%%% Checks, which mouse button was clicked
Type=h.Phasor.SelectionType;
if isempty(Key)
    %% Normal mouse clicks    
    switch Type
        case 'normal' %%% Left mouse button
            %% Pans plot while holding left mouse button
            %%% Gets starting position
            Pos=h.Phasor_Plot.CurrentPoint;
            %%% Disables further mouse click callbacks
            h.Phasor_Plot.ButtonDownFcn=[];
            %%% Changes mouse move callback to panning
            h.Phasor.WindowButtonMotionFcn={@Phasor_Move,2,Pos(1,1:2),[]};  
        case 'alt' %%% Right mouse button
            %% Opens a contextmenu
            %%% Determins current point and figure size
            Pos=h.Phasor.CurrentPoint;
            Size=getpixelposition(h.Phasor);  
            %%% Move menu to right position
            h.Phasor_Plot_Menu.Position=Pos.*[Size(3) Size(4)];
            %%% Opens menu
            h.Phasor_Plot_Menu.Visible='on';
        case 'extend' %%% Middle mouse button\ left+right mouse buttons
            %% Resets limits by pressing middle mouse button
            h.Phasor_Plot.XLim=[0 1];
            h.Phasor_Plot.YLim=[0 1];
        case 'open' %%% Copies whole axes to new figure
            %% Defines parameters
            Size = [str2double(h.Export_SizeX.String) str2double(h.Export_SizeY.String)];
            GLim = [str2double(h.Export_GMin.String) str2double(h.Export_GMax.String)];
            SLim = [str2double(h.Export_SMin.String) str2double(h.Export_SMax.String)];
            FontSize = UserValues.Phasor.Export_Font.FontSize;

            
            %% Finds all children of the current axes
            a=get(gca,'Children');
            %% Creates new figure and axes
            Exp.Fig=figure(...
                'Units','points',...
                'Position',[50 150 Size(1)+30+FontSize*5.2 Size(2)+25+FontSize*2.5]);
            Exp.Axes=axes(...
                'Parent',Exp.Fig,...
                'Units','points',...
                'FontName',UserValues.Phasor.Export_Font.FontName,...
                'FontSize',UserValues.Phasor.Export_Font.FontSize,...
                'FontWeight',UserValues.Phasor.Export_Font.FontWeight,...
                'FontAngle',UserValues.Phasor.Export_Font.FontAngle,...
                'Layer','top',...
                'DataAspectRatio',[1 1 1],...
                'YLim', SLim,...
                'XLim', GLim,...
                'Position',[10+FontSize*3 10+FontSize*2.5 Size(1) Size(2)]);
            if  diff(GLim)>=0.6
                Exp.Axes.XTick = 0:0.2:1;
            else
                Exp.Axes.XTick = 0:0.25:1;                               
            end
            Exp.Axes.YTick = 0:0.25:0.5;
            Exp.Axes.YTickLabel = cellfun(@num2str,num2cell(Exp.Axes.YTick),'UniformOutput',false);
            Exp.Axes.XTickLabel = cellfun(@num2str,num2cell(Exp.Axes.XTick),'UniformOutput',false); 
            Exp.Axes.XLabel.String = 'g';
            Exp.Axes.YLabel.String = 's';            
            %% Copies all objects one by one
            for i=1:numel(a)
                if strcmp(a(i).Visible,'on')
                    Exp.Child(i)=copyobj(a(i),Exp.Axes);
                    %%% moves phasor histogram (=image) to bottom
                    if strcmp(get(Exp.Child(i),'Type'),'image')
                        uistack(Exp.Child(i),'bottom');
                    end
                    Exp.Child(i).HitTest = 'on';
                end
            end          
            %% Adds colorbar
            %%% Defines phasor colormap
            switch h.PhasorColor.Value
                case 1
                    Color=jet(128);
                case 2
                    Color=hot(128);
                case 3
                    Color=gray(128);
                case 4
                    Color=hsv(128);
                otherwise
                    Color=jet(128);
            end
            colormap(Exp.Axes,Color);
            Exp.Colbar = colorbar(...
                'peer',Exp.Axes,...
                'FontName',UserValues.Phasor.Export_Font.FontName,...
                'FontSize',UserValues.Phasor.Export_Font.FontSize,...
                'FontWeight',UserValues.Phasor.Export_Font.FontWeight,...
                'FontAngle',UserValues.Phasor.Export_Font.FontAngle,...
                'Units','points',...
                'Ticks',[1 128],...
                'TickLabels',{'Low';'High'},...
                'Position', [Size(1)+15+3*FontSize 10+FontSize*2.5 10 Size(2)],...
                'Location','eastoutside');
            Exp.Colbar.YLabel.String = 'Occurrence';
            Exp.Colbar.YLabel.Units = 'points';
            Exp.Colbar.YLabel.Position = [15 (Size(2))/2];
                      
    end
elseif Key>0 && Key <=6
   %% ROI selection mouse clicks
   switch Type
       case 'normal' %%% Rectangular ROI selection
           h.Phasor_ROI(Key,1).Position=[h.Phasor_Plot.CurrentPoint(1,1:2) 0 0];
           [h.Phasor_FRET(1:4,:).Visible,h.Phasor_FRET(5,1).Visible, h.Phasor_ROI(Key,:).Visible,h.Phasor_Fraction.Visible,h.Phasor_Triangle.Visible] = deal('off');
           h.Phasor.WindowButtonMotionFcn={@Phasor_Move,4,h.Phasor_Plot.CurrentPoint(1,1:2),Key};          
       case 'alt' %%% Ellipsoid ROI
           [h.Phasor_FRET(1:4,:).Visible,h.Phasor_FRET(5,1).Visible, h.Phasor_ROI(Key,:).Visible,h.Phasor_Fraction.Visible,h.Phasor_Triangle.Visible] = deal('off');
           h.Phasor.WindowButtonMotionFcn={@Phasor_Move,5,h.Phasor_Plot.CurrentPoint(1,1:2),Key};
   end
elseif Key>=7
    %% Triangle selection
    switch Key
        case 7
            h.Phasor_Triangle.XData([1 4]) = h.Phasor_Plot.CurrentPoint(1,1);
            h.Phasor_Triangle.YData([1 4]) = h.Phasor_Plot.CurrentPoint(1,2);
        case 8
            h.Phasor_Triangle.XData(2) = h.Phasor_Plot.CurrentPoint(1,1);
            h.Phasor_Triangle.YData(2) = h.Phasor_Plot.CurrentPoint(1,2);
        case 9
            h.Phasor_Triangle.XData(3) = h.Phasor_Plot.CurrentPoint(1,1);
            h.Phasor_Triangle.YData(3) = h.Phasor_Plot.CurrentPoint(1,2);
    end
    h.Phasor_Triangle.Visible = 'on';
    [h.Phasor_FRET(1:4,:).Visible,h.Phasor_FRET(5,1).Visible, h.Phasor_ROI(:).Visible,h.Phasor_Fraction.Visible] = deal('off');
    Plot_Phasor([],[],0,1:10);
elseif Key==0
    [h.Phasor_FRET(1:4,:).Visible,h.Phasor_FRET(5,1).Visible, h.Phasor_ROI.Visible,h.Phasor_Fraction.Visible,h.Phasor_Triangle.Visible] = deal('off');
    switch Type
        case 'normal'
            h.Phasor.WindowButtonMotionFcn={@Phasor_Move,6,h.Phasor_Plot.CurrentPoint(1,1:2)};
        case 'alt'
            h.Phasor.WindowButtonMotionFcn={@Phasor_Move,6.5,h.Phasor_Plot.CurrentPoint(1,1:2)};
    end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Tracks mouse/wheel movement %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% 1: Gets info about current point
%%% 2: Pans plot, when left mouse button is held
%%% 3: Zooms via wheel scroll
%%% 4: Left mouse click for ROI rectangles
%%% 5: Right mous clock for ellipoidal ROIs
%%% 6: Fraction line selection
%%% 7: Selection/Deselection of regions in the single image plot
function Phasor_Move(~,e,mode,Start,Key)
global PhasorData
%%% Only executes, if Phasor is the current figure
Fig = gcf;
if strcmp('Phasor',get(Fig,'Tag'))
    h=guidata(Fig);
    Pos=h.Phasor_Plot.CurrentPoint(1,1:2);
    switch mode
        case 1 %%% Shows info about current cursor position
            %%% Disables callback, to avoit multiple executions
            h.Phasor.WindowButtonMotionFcn=[];
            %%% Calculates current cursor position relative to limits
            XLim=h.Phasor_Plot.XLim;
            YLim=h.Phasor_Plot.YLim;
            %%% Only ecexutes inside plot bounds
            if Pos(1)>XLim(1) && Pos(1)<XLim(2) && Pos(2)>YLim(1) && Pos(2)<XLim(2)
                %%%Calculates info and updates text fields
                if ~isempty(PhasorData.Data)
                    Freq=PhasorData.Data{1}.Freq;
                else
                    Freq=25000000;
                end
                TauP=(Pos(1,2)/Pos(1,1))/(2*pi*Freq);
                TauM=sqrt((1/(Pos(1,2)^2+Pos(1,1)^2))-1)/(2*pi*Freq);
                h.G_Text.String=['G = ',num2str(Pos(1,1))];
                h.S_Text.String=['S = ',num2str(Pos(1,2))];
                h.TauP_Text.String=['TauP = ',num2str(TauP*10^9),' ns'];
                h.TauM_Text.String=['TauM = ',num2str(TauM*10^9),' ns'];
            end
            %%% Enables callback
            h.Phasor.WindowButtonMotionFcn={@Phasor_Move,1,[],[]};
        case 2 %%% Pans the plot around (hold left mouse button)
            h.Phasor_Plot.XLim=h.Phasor_Plot.XLim-(Pos(1)-Start(1));
            h.Phasor_Plot.YLim=h.Phasor_Plot.YLim-(Pos(2)-Start(2));
            pause(0.01);
        case 3 %%% Zooms (via mouse scroll
            %%% Calculates current cursor position relative to limits
            XLim=h.Phasor_Plot.XLim;
            YLim=h.Phasor_Plot.YLim;
            %%% Only ecexutes inside plot bounds
            if (Pos(1)>XLim(1) && Pos(1)<XLim(2) && Pos(2)>YLim(1) && Pos(2)<YLim(2))
                %%% Zooms in by sqrt(2)
                if e.VerticalScrollCount<0
                    h.Phasor_Plot.XLim=[mean(XLim)-diff(XLim)/sqrt(8),mean(XLim)+diff(XLim)/sqrt(8)];
                    h.Phasor_Plot.YLim=[mean(YLim)-diff(YLim)/sqrt(8),mean(YLim)+diff(YLim)/sqrt(8)];
                    %%% Zooms out by sqrt(2)
                elseif e.VerticalScrollCount>0
                    h.Phasor_Plot.XLim=[mean(XLim)-diff(XLim)/sqrt(2),mean(XLim)+diff(XLim)/sqrt(2)];
                    h.Phasor_Plot.YLim=[mean(YLim)-diff(YLim)/sqrt(2),mean(YLim)+diff(YLim)/sqrt(2)];
                end
            end
        case 4 %%% Generates a rectangular ROI
            %%% Disables callback, to avoit multiple executions
            h.Phasor.WindowButtonMotionFcn=[];
            %%% Resizes ROI rectangle         
            h.Phasor_ROI(Key,1).Position=[min([Start(1) Pos(1)]),min([Start(2) Pos(2)]),abs(Start(1)-Pos(1)),abs(Start(2)-Pos(2))];
            
            %%% Make ROI rectangle visible
            if all(h.Phasor_ROI(Key,1).Position(3:4)>0)
                h.Phasor_ROI(Key,1).Visible='on';
                if h.ROI_Live.Value
                    tic;
                    Plot_Phasor([],[],0,1:10)
                    pause(toc);
                end
            else
                h.Phasor_ROI(Key,1).Visible='off';
            end
            %%% Enables callback
            h.Phasor.WindowButtonMotionFcn={@Phasor_Move,4,Start,Key}; 
        case 5 %%% Generates a elliposidal ROI
            %%% Disables callback, to avoit multiple executions
            h.Phasor.WindowButtonMotionFcn=[];
            %%% Ony executes, if mouse moved
            if all((Pos-Start)~=0)
                
                Pixel=str2double(h.Phasor_Res.String');
                Width=str2double(h.ROI_Size{Key}.String);
                
                %%% Generates vector, connecting start and end
                x1=linspace(Start(1),Pos(1),Pixel);
                y1=linspace(Start(2),Pos(2),Pixel);
                
                %%% Creates circle
                x=cos(2*pi*(0:0.01:1));
                y=sin(2*pi*(0:0.01:1));
                x2=[];y2=[];
               
                %%% Applies circle around each point on line
                for i=1:Pixel;
                    x2(end+1:end+numel(x))=round(Pixel*(Width*x+x1(i)));
                    y2(end+1:end+numel(y))=round(Pixel*(Width*y+y1(i)));
                end
                %%% Transforms points to integers
                Xmin=min(x2)-1; x2=x2-Xmin;
                Ymin=min(y2)-1; y2=y2-Ymin;
                %%% Draws circles into a pixelmap
                Map1=zeros(max(x2),max(y2));
                Map1(sub2ind(size(Map1),x2,y2))=1;
                %%% Only uses edgepoints in map
                Map2=zeros(size(Map1));
                for j=1:size(Map1,2)
                    Map2(find(Map1(:,j),1,'first'),j)=1;
                    Map2(find(Map1(:,j),1,'last'),j)=1;
                end
                %%% Transforms pixelmat to coordinates
                [x,y]=find(Map2);
                %%% Shifts coordinates to right position
                x=(x+Xmin)/Pixel; 
                y=(y+Ymin)/Pixel;
                %%% Updates ROI object
                h.Phasor_ROI(Key,2).XData=[x(1:2:end); flipud(x(2:2:end)); x(1)];
                h.Phasor_ROI(Key,2).YData=[y(1:2:end); flipud(y(2:2:end)); y(1)];
                h.Phasor_ROI(Key,2).UserData = [Start, Pos];
                %%% Makes ROI visible
                h.Phasor_ROI(Key,2).Visible='on';
                if h.ROI_Live.Value
                    tic;
                    Plot_Phasor([],[],0,1:10)
                    pause(toc);
                end
            else
                %%% Hides ROI, if no ROI was selected
                h.Phasor_ROI(Key,2).Visible='off';
            end
            %%% Enables callback            
            h.Phasor.WindowButtonMotionFcn={@Phasor_Move,5,Start,Key}; 
        case {6, 6.1, 6.5} %%% Fraction line
            %%% Disables callback, to avoit multiple executions
            h.Phasor.WindowButtonMotionFcn=[];
            h.Phasor_Fraction.UserData = 0;
            %%% Ony executes, if mouse moved
            if mode==6.1
                h.Phasor_Fraction.XData=[str2double(h.ROI_Line_Pos{1}.String) str2double(h.ROI_Line_Pos{3}.String)];
                h.Phasor_Fraction.YData=[str2double(h.ROI_Line_Pos{2}.String) str2double(h.ROI_Line_Pos{4}.String)];
                h.Phasor_Fraction.Visible='on';
                Stop_All;
                Plot_Phasor([],[],0,1:10);
                return;
            elseif any((Pos-Start)~=0)
                h.Phasor_Fraction.XData=[Start(1) Pos(1)];
                h.Phasor_Fraction.YData=[Start(2) Pos(2)];
                
                if mode==6
                    h.ROI_Line_Pos{1}.String = num2str(Start(1));
                    h.ROI_Line_Pos{2}.String = num2str(Start(2));
                    h.ROI_Line_Pos{3}.String = num2str(Pos(1));
                    h.ROI_Line_Pos{4}.String = num2str(Pos(2));
                else
                    h.ROI_Line_Pos{3}.String = num2str(Start(1));
                    h.ROI_Line_Pos{4}.String = num2str(Start(2));
                    h.ROI_Line_Pos{1}.String = num2str(Pos(1));
                    h.ROI_Line_Pos{2}.String = num2str(Pos(2));
                end
                
                h.Phasor_Fraction.Visible='on';
                if h.ROI_Live.Value
                    tic;
                    Plot_Phasor([],[],0,1:10)
                    pause(toc);
                end
            else
                %%% Hides Fraction line,
                h.Phasor_Fraction.Visible='off';
            end
            h.Phasor.WindowButtonMotionFcn={@Phasor_Move,mode,Start};
        case 7 %%% Select individual regions in Single plot
            h.Phasor.WindowButtonMotionFcn=[];
            %%% Calculates current cursor position relative to limits
            Pos=round(h.Image_Plot(10,1).CurrentPoint(1,1:2)+0.5);
            XLim=h.Image_Plot(10,1).XLim;
            YLim=h.Image_Plot(10,1).YLim;
            %%% Only ecexutes inside plot bounds
            if Pos(1)>XLim(1) && Pos(1)<XLim(2) && Pos(2)>YLim(1) && Pos(2)<XLim(2)
               Size=str2double(h.Single_Selection_Size.String);
               X=max([Pos(1)-Size,1]):min([Pos(1)+Size,size(PhasorData.Selected_Region{h.List.Value(1)},1)]);
               Y=max([Pos(2)-Size,1]):min([Pos(2)+Size,size(PhasorData.Selected_Region{h.List.Value(1)},2)]);
               PhasorData.Selected_Region{h.List.Value(1)}(Y,X)=Key;
               Plot_Phasor(h.Image_Plot(10,1),[],1,10);
            end
            h.Phasor.WindowButtonMotionFcn={@Phasor_Move,7,[],Key};
    end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Tracks key press events %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% 0:      Fraction line definition
%%% 1-6:    ROI selection
%%% 7:      Triangle selection
function Phasor_Key(~,e,mode)
h=guidata(findobj('Tag','Phasor'));
global PhasorData
switch mode
    case 1
        %% Key press callback
        %%% Makes numpad and normal number keys equal
        if ~isempty(strfind(e.Key,'numpad'))
            Key=str2double(e.Key(7:end));
        else
            Key=str2double(e.Key);
        end
        %%% Checks, if keys 0-6 were pressed
        if ~isnan(Key) && Key<=9 && Key>=0
            %%% Defines key release callback to stop
            h.Phasor.KeyReleaseFcn={@Phasor_Key,2};
            %%% Disables further key press callbacks
            h.Phasor.KeyPressFcn=[];
            %%% Changes cursor shape
            if Key~=0
                h.Phasor.Pointer='custom';
                h.Phasor.PointerShapeCData=PhasorData.Cursor{Key};
                h.Phasor_Plot.ButtonDownFcn={@Phasor_Plot_Callback,Key};
            else
                h.Phasor.Pointer='crosshair';
                h.Phasor_Plot.ButtonDownFcn={@Phasor_Plot_Callback,Key};
            end
        end
        
    otherwise
        %% Key Release callback
        h.Phasor.KeyReleaseFcn=[];
        h.Phasor.KeyPressFcn={@Phasor_Key,1};        
        h.Phasor.Pointer='arrow';
        h.Phasor_Plot.ButtonDownFcn={@Phasor_Plot_Callback,[]};
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Mouse button release callback %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Stop_All(~,~)
figure(findobj('Tag','Phasor'));
h=guidata(findobj('Tag','Phasor'));
%%% Sets standard mouse click callback (in case it was changed/disabled)
h.Phasor_Plot.ButtonDownFcn={@Phasor_Plot_Callback,[]};
%%% Updates plot, if new ROI was selected
if ~isempty(h.Phasor.WindowButtonMotionFcn) && any(h.Phasor.WindowButtonMotionFcn{2}==[4,5,6,6.5])
    %%% Inverts fraction line
    if h.Phasor.WindowButtonMotionFcn{2}==6.5
        h.Phasor_Fraction.XData = h.Phasor_Fraction.XData([2,1]);
        h.Phasor_Fraction.YData = h.Phasor_Fraction.YData([2,1]);
    end
    h.Phasor.Pointer='arrow';
    Plot_Phasor([],[],0,1:10);
end
%%% Sets standard mouse move callback (in case it was changed/disabled)
h.Phasor.WindowButtonMotionFcn={@Phasor_Move,1,[],[]};



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Generates trajectories for FRET %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
function Calc_FRET(~,~,mode)
h = guidata(findobj('Tag','Phasor'));
global UserValues

Pos=h.Phasor_Plot.CurrentPoint(1,1:2);

%%% Updates the right values
switch mode
    case 1
        %% Donor Position was changed
        Donor_Pos=Pos;
        h.FRET_Pos(1,1).String = num2str(Pos(1));
        h.FRET_Pos(1,2).String = num2str(Pos(2));
        BG_Pos=[h.Phasor_FRET(3).XData(2), h.Phasor_FRET(3).YData(2)];
    case 2
        %% Background Position was changed
        h.FRET_Pos(2,1).String = num2str(Pos(1));
        h.FRET_Pos(2,2).String = num2str(Pos(2));
        Donor_Pos=[h.Phasor_FRET(3).XData(1), h.Phasor_FRET(3).YData(1)];
        BG_Pos=Pos;
    case 3
        %% Background slider was changed
        Donor_Pos=[h.Phasor_FRET(3).XData(1), h.Phasor_FRET(3).YData(1)];
        BG_Pos=[h.Phasor_FRET(3).XData(2), h.Phasor_FRET(3).YData(2)];
        h.FRET_BG_Edit.String=num2str(h.FRET_BG_Slider.Value);
        %%% Keeps signal at >0%
        if (h.FRET_DO_Slider.Value+h.FRET_BG_Slider.Value)>100
            h.FRET_DO_Slider.Value=100-h.FRET_BG_Slider.Value;
            h.FRET_DO_Edit.String=num2str(h.FRET_DO_Slider.Value);
        end
    case 4
        %% Background editbox was changed
        Donor_Pos=[h.Phasor_FRET(3).XData(1), h.Phasor_FRET(3).YData(1)];
        BG_Pos=[h.Phasor_FRET(3).XData(2), h.Phasor_FRET(3).YData(2)];
        h.FRET_BG_Slider.Value=str2double(h.FRET_BG_Edit.String);
        %%% Keeps signal at >0%
        if (h.FRET_DO_Slider.Value+h.FRET_BG_Slider.Value)>100
            h.FRET_DO_Slider.Value=100-h.FRET_BG_Slider.Value;
            h.FRET_DO_Edit.String=num2str(h.FRET_DO_Slider.Value);
        end
    case 5
        %% Donor only slider was changed
        Donor_Pos=[h.Phasor_FRET(3).XData(1), h.Phasor_FRET(3).YData(1)];
        BG_Pos=[h.Phasor_FRET(3).XData(2), h.Phasor_FRET(3).YData(2)];        
        h.FRET_DO_Edit.String=num2str(h.FRET_DO_Slider.Value);
        %%% Keeps signal at >0%
        if (h.FRET_DO_Slider.Value+h.FRET_BG_Slider.Value)>100
            h.FRET_BG_Slider.Value=100-h.FRET_DO_Slider.Value;
            h.FRET_BG_Edit.String=num2str(h.FRET_BG_Slider.Value);
        end
    case 6
        %% Donor only editbox was changed
        Donor_Pos=[h.Phasor_FRET(3).XData(1), h.Phasor_FRET(3).YData(1)];
        BG_Pos=[h.Phasor_FRET(3).XData(2), h.Phasor_FRET(3).YData(2)];
        h.FRET_DO_Slider.Value=str2double(h.FRET_DO_Edit.String);
        %%% Keeps signal at >0%
        if (h.FRET_DO_Slider.Value+h.FRET_BG_Slider.Value)>100
            h.FRET_BG_Slider.Value=100-h.FRET_DO_Slider.Value;
            h.FRET_BG_Edit.String=num2str(h.FRET_BG_Slider.Value);
        end
    case 7
        %% FRET value slider was change
        Donor_Pos=[h.Phasor_FRET(3).XData(1), h.Phasor_FRET(3).YData(1)];
        BG_Pos=[h.Phasor_FRET(3).XData(2), h.Phasor_FRET(3).YData(2)];
        h.FRET_Value_Edit.String=num2str(h.FRET_Value_Slider.Value);
    case 8
        %% FRET value editbox was changed
        Donor_Pos=[h.Phasor_FRET(3).XData(1), h.Phasor_FRET(3).YData(1)];
        BG_Pos=[h.Phasor_FRET(3).XData(2), h.Phasor_FRET(3).YData(2)];
        h.FRET_Value_Slider.Value=str2double(h.FRET_Value_Edit.String);
    case 9
        %% Donor Position edit was changed
        h.Phasor_FRET(3).XData(1) = str2double(h.FRET_Pos(1,1).String);
        h.Phasor_FRET(3).YData(1) = str2double(h.FRET_Pos(1,2).String);
        Donor_Pos=[h.Phasor_FRET(3).XData(1), h.Phasor_FRET(3).YData(1)];
        BG_Pos=[h.Phasor_FRET(3).XData(2), h.Phasor_FRET(3).YData(2)];
    case 10
        %% Background Position edit was changed
        h.Phasor_FRET(3).XData(2) = str2double(h.FRET_Pos(2,1).String);
        h.Phasor_FRET(3).YData(2) = str2double(h.FRET_Pos(2,2).String);
        Donor_Pos=[h.Phasor_FRET(3).XData(1), h.Phasor_FRET(3).YData(1)];
        BG_Pos=[h.Phasor_FRET(3).XData(2), h.Phasor_FRET(3).YData(2)];
        
end

%%% Background and Donor only percentage
DO=h.FRET_DO_Slider.Value;
BG=h.FRET_BG_Slider.Value;
FRET=101-h.FRET_Value_Slider.Value;

%%% Calculates mono-exponential position
%%% For non mono-exponential decays it is not possible to calculate the
%%% trajectory. Therefor it is approximated via a decay with 0 Lifetime and
%%% a mono-exponential decay
G=1/(1+((1-Donor_Pos(1))/Donor_Pos(2))^2);
S=sqrt(G*(1-G));
Scale=Donor_Pos(2)/S;

%%% Calculates FRET trajectory of mono-exponential decay in 1% steps
g=1./(1+(0:0.01:1).^2*(1/G-1));
s=(0:0.01:1)*sqrt((1/G)-1)./(1+(0:0.01:1).^2*(1/G-1));

%%% Rescales to original phasor position
s=s*Scale;
g=1-(Scale*(1-g));

%%% Calculates mixture position of background and donor only
BGDO_Pos=(BG*BG_Pos+DO*Donor_Pos)/(BG+DO);

%%% Calculates mixture trajectory 
if BG+DO==0
    g_BG=g;
    s_BG=s;
else
    g_BG=((100-BG-DO)*(0:0.01:1).*g+(BG+DO)*BGDO_Pos(1))./((100-BG-DO)*(0:0.01:1)+(BG+DO));
    s_BG=((100-BG-DO)*(0:0.01:1).*s+(BG+DO)*BGDO_Pos(2))./((100-BG-DO)*(0:0.01:1)+(BG+DO));
end

%%% Extrapolates g and s for non integer FRET values
FRET_Pos(1)=(1-mod(FRET,1))*g_BG(floor(FRET))+mod(FRET,1)*g_BG(ceil(FRET));
FRET_Pos(2)=(1-mod(FRET,1))*s_BG(floor(FRET))+mod(FRET,1)*s_BG(ceil(FRET));

%%% Updates FRET plot
if h.FRET_Use.Value==2
    Min=str2double(h.FRET_Min.String);
    Max=str2double(h.FRET_Max.String);
    if Max>100;Max=100;end
    if Min<0;Min=0;end
    g_BG=flip(g_BG);
    s_BG=flip(s_BG);
    h.Phasor_FRET(2,1).XData=g_BG(round(Min+1):round(Max+1));
    h.Phasor_FRET(2,1).YData=s_BG(round(Min+1):round(Max+1));
else
    h.Phasor_FRET(2,1).XData=g_BG;
    h.Phasor_FRET(2,1).YData=s_BG;
end
h.Phasor_FRET(1,1).XData=g;
h.Phasor_FRET(1,1).YData=s;
h.Phasor_FRET(3,1).XData=[Donor_Pos(1) BG_Pos(1)];
h.Phasor_FRET(3,1).YData=[Donor_Pos(2) BG_Pos(2)];
h.Phasor_FRET(4,1).XData=[BGDO_Pos(1) FRET_Pos(1)];
h.Phasor_FRET(4,1).YData=[BGDO_Pos(2) FRET_Pos(2)];
h.Phasor_FRET(1,2).XData=g(end);
h.Phasor_FRET(1,2).YData=s(end);
h.Phasor_FRET(2,2).XData=BGDO_Pos(1);
h.Phasor_FRET(2,2).YData=BGDO_Pos(2);
h.Phasor_FRET(3,2).XData=BG_Pos(1);
h.Phasor_FRET(3,2).YData=BG_Pos(2);
h.Phasor_FRET(4,2).XData=FRET_Pos(1);
h.Phasor_FRET(4,2).YData=FRET_Pos(2);
Radius=str2double(h.FRET_Size.String);
UserValues.Phasor.Settings_FRETRadius = h.FRET_Size.String;
LSUserValues(1);
h.Phasor_FRET(5,1).XData=Radius*cos(0:0.01:2*pi)+FRET_Pos(1);
h.Phasor_FRET(5,1).YData=Radius*sin(0:0.01:2*pi)+FRET_Pos(2);

%%% Activate FRET plot
[h.Phasor_FRET(1:4,:).Visible]=deal('on');
if h.FRET_Use.Value==3
    h.Phasor_FRET(4,2).Visible='off';
    h.Phasor_FRET(5,1).Visible='on';
else
    h.Phasor_FRET(4,2).Visible='on';
    h.Phasor_FRET(5,1).Visible='off';
end

%%% Deactivate ROIs and Fraction line
[h.Phasor_ROI.Visible,h.Phasor_Fraction.Visible,h.Phasor_Triangle.Visible]=deal('off');
%%% Updates Images
Plot_Phasor([],[],0,1:10);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Button click callback for Single image %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% left:   Deselect all/select region
%%% middle: Select region
%%% double: Select all
%%% right: open context menu (see Plots_Menu_Callback)
function Select_Region(~,~)
global PhasorData
h = guidata(findobj('Tag','Phasor'));
Type=h.Phasor.SelectionType;

if ~isempty(h.List.String)
    switch Type
        case 'normal'
            %% Starts region selection
            %%% Deselects all pixel if clicked for the first time
            if ~any(any(PhasorData.Selected_Region{h.List.Value(1)}));
                PhasorData.Selected_Region{h.List.Value(1)}=~PhasorData.Selected_Region{h.List.Value(1)};
            end
            h.Phasor.WindowButtonMotionFcn={@Phasor_Move,7,[],false};
            Plot_Phasor(h.Image_Plot(10,1),[],1,10);
        case 'alt'
            %% Opens context menu (see Plots_Menu_Callback)
        case 'extend'
            %% Starts region deselection
            h.Phasor.WindowButtonMotionFcn={@Phasor_Move,7,[],true};
            Plot_Phasor(h.Image_Plot(10,1),[],1,10);
        case 'open'
            %% Selects everything
            PhasorData.Selected_Region{h.List.Value(1)}=false(size(PhasorData.Selected_Region{h.List.Value(1)}));
            Plot_Phasor(h.Image_Plot(10,1),[],1,10);
    end
end





%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Updates all plots %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Plot_Phasor(Obj,~,Main,Images)
h = guidata(findobj('Tag','Phasor'));
global PhasorData UserValues
global Phasor_Colormap

Pixel=str2double(h.Phasor_Res.String);
THmin=str2double(h.THmin.String);
THmax=str2double(h.THmax.String);
if ~isempty(h.List.String)
    PhasorData.Plot(10)=h.List.Value(1);
else
    PhasorData.Plot(10)=0;
end
%% Calculates and plots phasor histogram
if Main
    
    %%% Updates Center of Mass cursor positions
    if ~isempty(Obj)
        if any(Obj == [h.THmin, h.THmax])
            Update_CoM([],[],1:numel(PhasorData.CoM),1)
        elseif Obj==h.Image_Plot(10,1)
            Update_CoM([],[],h.List.Value(1),1);
        elseif Obj==h.List || Obj==h.Main_Tab
            Update_CoM([],[],0,0:2);
        end
    end
    
    %%% Defines phasor colormap
    switch h.PhasorColor.Value
        case 1
            PhasorColor=[1 1 1;jet(128)];
        case 2
            PhasorColor=[1 1 1;hot(128)];
        case 3
            PhasorColor=[1 1 1;gray(128)];
        case 4
            PhasorColor=[1 1 1;hsv(128)];
        otherwise
            PhasorColor=[1 1 1;jet(128)];
    end

    if h.Main_Tab.SelectedTab == h.Single_Tab && numel(PhasorData.Data)>0
        %% Single selected plot
        g=PhasorData.Data{PhasorData.Plot(10)}.g(...
            PhasorData.Data{PhasorData.Plot(10)}.Intensity>=THmin &...
            PhasorData.Data{PhasorData.Plot(10)}.Intensity<=THmax &...
            ~PhasorData.Selected_Region{PhasorData.Plot(10)});
        s=PhasorData.Data{PhasorData.Plot(10)}.s(...
            PhasorData.Data{PhasorData.Plot(10)}.Intensity>=THmin &...
            PhasorData.Data{PhasorData.Plot(10)}.Intensity<=THmax &...
            ~PhasorData.Selected_Region{PhasorData.Plot(10)});
    else   
        %% Generates one string of phasor data from all selected images
        g=[]; s=[];
        for i=1:numel(PhasorData.Data)
            if PhasorData.Selected(i)
                G=PhasorData.Data{i}.g(PhasorData.Data{i}.Intensity>=THmin & PhasorData.Data{i}.Intensity<=THmax);
                S=PhasorData.Data{i}.s(PhasorData.Data{i}.Intensity>=THmin & PhasorData.Data{i}.Intensity<=THmax);
                g=[g;G];
                s=[s;S];
            end
        end
    end
    %%%% Removes all pixels oudside of reasonable bounds
    switch PhasorData.Type
        case 1 %%% Lifetime Data
            s=s(g>-0.1); g=g(g>-0.1);
            s=s(g<=1.2); g=g(g<=1.2);
            g=g(s>-0.1); s=s(s>-0.1);
            g=g(s<=1.2); s=s(s<=1.2);
        case 2 %%% Spectral Data
            s=s(g>-1); g=g(g>-1);
            s=s(g<=1); g=g(g<=1);
            g=g(s>-1); s=s(s>-1);
            g=g(s<=1); s=s(s<=1);            
    end
    %%% Removes all pixel at (0,0) (usually NaN)
    NaNs=~(s==0 & g==0);
    g=g(NaNs); s=s(NaNs);
      
    if ~isempty(g)
        %%% Histograms phasor plot
        switch PhasorData.Type
            case 1 %%% Lifetime Data
                g=floor(Pixel*(g+0.1));
                s=floor(Pixel*(s+0.1));
                Hist=g+1.3*Pixel*s;
                Phasor=histc(Hist,0:((1.3*Pixel)^2-1));
                %%% Applies colormap to phasor
                Phasor=ceil(128*Phasor/max(Phasor)+1);
                PhasorImage=reshape(PhasorColor(Phasor,:),1.3*Pixel,1.3*Pixel,3);
                h.Phasor_Hist.XData = linspace(-0.1,1.2,size(PhasorImage,2));
                h.Phasor_Hist.YData = linspace(-0.1,1.2,size(PhasorImage,1));
                h.Universal_Circle.XData = 0:0.01:1;
                h.Universal_Circle.YData = sqrt((0:0.01:1)-(0:0.01:1).^2);
            case 2 %%% Spectral Data
                g=floor(Pixel*(g+1)/2);
                s=floor(Pixel*(s+1)/2);
                Hist=g+Pixel*s;
                Phasor=histcounts(Hist,0:(Pixel)^2);
                %%% Applies colormap to phasor
                Phasor=ceil(128*Phasor/max(Phasor)+1);
                PhasorImage=reshape(PhasorColor(Phasor,:),Pixel,Pixel,3);
                h.Phasor_Hist.XData = linspace(-1,1,size(PhasorImage,2));
                h.Phasor_Hist.YData = linspace(-1,1,size(PhasorImage,1));
                h.Universal_Circle.XData = [-1:0.01:1, 1:-0.01:-1];
                h.Universal_Circle.YData = [sqrt(1-(-1:0.01:1).^2), -sqrt(1-(1:-0.01:-1).^2)];
        end
        %%% Updates phasor plot
        h.Phasor_Hist.CData=permute(PhasorImage,[2 1 3]); 
    end
    
end
 
%% Calculates and plots phasor images
%%% Generates selected colormap for images
switch h.ImageColor.Value
    case 1
        ImageColor=gray(128);
    case 2
        ImageColor=jet(128);
    case 3
        ImageColor=hot(128);
    case 4
        ImageColor=hsv(128);
    case 5
        ImageColor=zeros(128,3);
end    
%%% Only plot Multiple or Single Plot
if h.Main_Tab.SelectedTab == h.Plots_Tab
    Images=Images(~(Images==10));
elseif h.Main_Tab.SelectedTab == h.Single_Tab
    Images=Images(Images==10);
else
    Images = [];
end
Map=cell(6,1);
for i=Images %%% Plots Phasor Data
    if PhasorData.Plot(i)~=0 
        %%% Changes the plot title
        if i<10
           h.Image_Panel(i).Title=PhasorData.Files{PhasorData.Plot(i),1}; 
        end
        Int=PhasorData.Data{PhasorData.Plot(i)}.Intensity;
        %%% Scales images to scale bounds, if autoscale is deselected
        if ~h.Autoscale.Value
            Int(Int>str2double(h.ASmax.String))=str2double(h.ASmax.String);
            Int(Int<str2double(h.ASmin.String))=str2double(h.ASmin.String);
            Int(end)=str2double(h.ASmax.String);
        end
        %%% Transforms intensity image to 64 bits
        Int=round(127*(Int-min(min(Int)))/(max(max(Int))-min(min(Int))))+1;
        %%% Applies colormap
        Image=reshape(ImageColor(Int(:),:),size(Int,1),size(Int,2),3);
        
        %%% Selects, which masks are applied
        if strfind(cell2mat({h.Phasor_ROI.Visible}),'on')>0 
            %% ROIs selected
            Mask=zeros(size(Image));
            roi=zeros(size(Image,1),size(Image,2),6);
            for j=1:6
                if strcmp(h.Phasor_ROI(j,1).Visible,'on')
                    %% Rectangular ROI
                    Pos=h.Phasor_ROI(j,1).Position;
                    %%% Generates ROI map
                    roi(:,:,j)= PhasorData.Data{PhasorData.Plot(i)}.g>=Pos(1) &...
                        PhasorData.Data{PhasorData.Plot(i)}.g<=(Pos(1)+Pos(3)) &...
                        PhasorData.Data{PhasorData.Plot(i)}.s>=Pos(2) &...
                        PhasorData.Data{PhasorData.Plot(i)}.s<=(Pos(2)+Pos(4)) &...
                        PhasorData.Data{PhasorData.Plot(i)}.Intensity >= THmin &...
                        PhasorData.Data{PhasorData.Plot(i)}.Intensity <= THmax;  
                    
                    %%% Applies ROI color
                    Mask(:,:,1)=Mask(:,:,1)+roi(:,:,j)*h.ROI_Color{j}.BackgroundColor(1);
                    Mask(:,:,2)=Mask(:,:,2)+roi(:,:,j)*h.ROI_Color{j}.BackgroundColor(2);
                    Mask(:,:,3)=Mask(:,:,3)+roi(:,:,j)*h.ROI_Color{j}.BackgroundColor(3);
                elseif strcmp(h.Phasor_ROI(j,2).Visible,'on')
                    %% Ellipoid ROI
                    if isempty(Map{j})
                        %%% Determins position of ROI
                        x=round(Pixel*(h.Phasor_ROI(j,2).XData+0.1));
                        y=round(Pixel*(h.Phasor_ROI(j,2).YData+0.1));
                        x(x<1)=1; y(y<1)=1;
                        Map{j}=zeros(1.3*Pixel);
                        %%% Transforms ROI position into pixelmap
                        Map{j}(sub2ind(size(Map{j}),x,y))=1;
                        %%% Fills ROI pixelmap
                        Map{j}=mod(cumsum(Map{j}),2);
                    end
                    %%% Finds valid pixel
                    G=round((PhasorData.Data{PhasorData.Plot(i)}.g+0.1)*Pixel);
                    G(isnan(G) | G<1)=1;
                    S=round((PhasorData.Data{PhasorData.Plot(i)}.s+0.1)*Pixel);
                    S(isnan(S) | S<1)=1;  
                    Index=sub2ind(size(Map{j}),G,S);
                    %%% Generates ROI map
                    roi(:,:,j)=Map{j}(Index) &...
                        PhasorData.Data{PhasorData.Plot(i)}.Intensity >= THmin &...
                        PhasorData.Data{PhasorData.Plot(i)}.Intensity <= THmax;                            
                    %%% Applies ROI color
                    Mask(:,:,1)=Mask(:,:,1)+roi(:,:,j)*h.ROI_Color{j}.BackgroundColor(1);
                    Mask(:,:,2)=Mask(:,:,2)+roi(:,:,j)*h.ROI_Color{j}.BackgroundColor(2);
                    Mask(:,:,3)=Mask(:,:,3)+roi(:,:,j)*h.ROI_Color{j}.BackgroundColor(3);                    
                end
            end
            a=squeeze(sum(sum(roi(:,:,1:2))));
            %%% Generates total ROI map
            ROI=repmat(sum(roi,3),[1 1 3]);
            %%% Averages ROI color
            ROI=ROI>0;
            Mask(ROI)=Mask(ROI)./ROI(ROI);
        elseif strcmp(h.Phasor_Fraction.Visible,'on') 
            %% Fraction line
            %%% Determines Fraction line colormap
            switch h.Fraction_Color.Value
                case 1
                    FractionColor=[0 0 0; jet(32)];
                case 2
                    FractionColor=[0 0 0; hot(32)];
                case 3
                    FractionColor=[0 0 0; hsv(32)];
                case 4
                    FractionColor(:,1) = [0; linspace(0,1,16)';ones(16,1) ];
                    FractionColor(:,2) = [0; ones(16,1); linspace(1,0,16)'];
                    FractionColor(:,3) = zeros(33,1);
                case 5
                    if ~isempty(Phasor_Colormap) && size(Phasor_Colormap,1)>1 && size(Phasor_Colormap,2)==3 %%% Uses new colormap
                        FractionColor=[0 0 0; Phasor_Colormap];
                        UserValues.Phasor.Colormap = Phasor_Colormap;
                        LSUserValues(1);
                        Phasor_Colormap = [];
                    else%%% Uses saved colormap
                        FractionColor=[0 0 0; UserValues.Phasor.Colormap];
                    end
            end
            %%% Rotation with complex numbers
            Width=str2double(h.ROI_Size{7}.String);
            
            x=h.Phasor_Fraction.XData;
            y=h.Phasor_Fraction.YData;
            %%% transforms phasor to complex number
            Complex_Line = x+sqrt(-1)*y;
            
            %%% Calculates rotation coefficients
            k=diff(x)/diff(y); Scale = 1/sqrt(k^2+1);
            %%% Rotates fraction line
            Complex_Line = Complex_Line*Scale*(1+k*sqrt(-1));
            %%% transforms complex number to phasor
            x = real(Complex_Line);
            y = imag(Complex_Line);
            
            %%% Transforms phasor into a complex number
            Complex = PhasorData.Data{PhasorData.Plot(i)}.g + sqrt(-1)*PhasorData.Data{PhasorData.Plot(i)}.s;
            %%% Rotates Phasor
            Complex = Complex*Scale*(1+k*sqrt(-1));
            %%% transforms complex back to phasor
            g = real(Complex);
            s = imag(Complex);
            
            %%% position relative to line
            roi = ceil((s-y(1))/(y(2)-y(1))*(size(FractionColor,1)-1));
            %%% removes points too far away
            Dist = abs(x(1)-g);
            
            roi(roi<0 | roi > size(FractionColor,1)-1 | Dist > Width ) = 0;
            
            %%% Removes pixels below threshold
            ROI=roi>0 &...
                PhasorData.Data{PhasorData.Plot(i)}.Intensity >= THmin &...
                PhasorData.Data{PhasorData.Plot(i)}.Intensity <= THmax;
            ROI=repmat(ROI,[1 1 3]);
            Mask=reshape(FractionColor(roi+1,:),size(Image));
        elseif strcmp(h.Phasor_Triangle.Visible,'on')
            for t=1:3
                %%% Reference point
                x_ref = h.Phasor_Triangle.XData(mod(t+1,3)+1);
                y_ref = h.Phasor_Triangle.YData(mod(t+1,3)+1);
                
                %%% Opposite line
                x=h.Phasor_Triangle.XData(t:(t+1));
                y=h.Phasor_Triangle.YData(t:(t+1));
                
                
                %%% transforms phasor to complex number
                Complex_Line = x+sqrt(-1)*y;
                Complex_Ref = x_ref+sqrt(-1)*y_ref;
                
                %%% Calculates rotation coefficients
                k=diff(x)/diff(y); Scale = 1/sqrt(k^2+1);
                %%% Rotates line and point
                Complex_Line = Complex_Line*Scale*(1+k*sqrt(-1));
                Complex_Ref = Complex_Ref*Scale*(1+k*sqrt(-1));
                
                %%% transforms complex number to phasor
                x = real(Complex_Line);
                y = imag(Complex_Line);
                
                x_ref = real(Complex_Ref);
                y_ref = imag(Complex_Ref);
                
                %%% Transforms phasor into a complex number
                Complex = PhasorData.Data{PhasorData.Plot(i)}.g + sqrt(-1)*PhasorData.Data{PhasorData.Plot(i)}.s;
                %%% Rotates Phasor
                Complex = Complex*Scale*(1+k*sqrt(-1));
                %%% transforms complex back to phasor
                g = real(Complex);
                s = imag(Complex);
                
                Dist_ref = x(1)-x_ref;
                F(:,:,mod(t+1,3)+1) = (x(1)-g)/Dist_ref;
            end
            R = F(:,:,1);
            G = F(:,:,2);
            B = F(:,:,3);
            clear F;
            
            R(G>=1 | B>=1)=0; R(R<0)=0;
            G(R>=1 | B>=1)=0; G(G<0)=0;
            B(G>=1 | R>=1)=0; B(B<0)=0;
            
            Mask(:,:,1) = R;
            Mask(:,:,2) = G;
            Mask(:,:,3) = B;
            Mask = Mask.*repmat(1./sum(Mask,3),1,1,3);
            %%% Applies contrast
            %Mask = sqrt(Mask);
            %Mask = log10(Mask*9+1);
            %Mask = Mask./repmat(max(Mask,[],3),1,1,3);
            %Mask = Mask(max(Mask(:)));
            
            ROI = repmat(PhasorData.Data{PhasorData.Plot(i)}.Intensity >= THmin &...
                  PhasorData.Data{PhasorData.Plot(i)}.Intensity <= THmax,1,1,3);
            
        elseif strcmp(h.Phasor_FRET(1,1).Visible,'on') && h.FRET_Use.Value==2
            %% FRET line
            
            %%% Determines FRET colormap
            switch h.FRET_Color.Value
                case 1
                    FractionColor=[0 0 0; jet(20)];
                case 2
                    FractionColor=[0 0 0; hot(20)];
                case 3
                    FractionColor=[0 0 0; hsv(20)];
                case 4 %%% Custom Colormap
                    if ~isempty(Phasor_Colormap) && size(Phasor_Colormap,1)>1 && size(Phasor_Colormap,2)==3 %%% Uses new colormap
                        FractionColor=[0 0 0; Phasor_Colormap];
                        UserValues.Phasor.Colormap = Phasor_Colormap;
                        LSUserValues(1);
                        Phasor_Colormap = [];
                    else%%% Uses saved colormap
                        FractionColor=[0 0 0; UserValues.Phasor.Colormap];
                    end
            end
            
            %%% Determines which FRET range to use
            Width=str2double(h.ROI_Size{7}.String);
            x=h.Phasor_FRET(2,1).XData;
            y=h.Phasor_FRET(2,1).YData;

            %%% Reduces number of points to 20 for the colormap
            while numel(x)>(size(FractionColor,1)-1)
               dist=diff(x).^2+diff(y).^2;
               x(find(dist==min(dist),1,'last')+1)=[];
               y(find(dist==min(dist),1,'last')+1)=[];
            end
            
            %%% Calculated Map
            step=1/Pixel;
            X=-0.1:step:1.2;
            Y=-0.1:step:1.2;
            
            [X1,Y1,Z1]=meshgrid(X,Y,x);
            [~,~,Z2]=meshgrid(X,Y,y);
            Dist=sqrt((X1-Z1).^2+(Y1-Z2).^2);
            [Min,Ind]=min(Dist,[],3);
            Map=(Ind.*(Min<=Width))';
            %%% Finds valid pixel
            G=round((PhasorData.Data{PhasorData.Plot(i)}.g+0.1)*Pixel);
            G(isnan(G) | G<1)=1;
            S=round((PhasorData.Data{PhasorData.Plot(i)}.s+0.1)*Pixel);
            S(isnan(S) | S<1)=1;
            %%% Generates ROI map
            roi=Map(sub2ind(size(Map),G,S));
            ROI=roi>0 &...
                PhasorData.Data{PhasorData.Plot(i)}.Intensity >= THmin &...
                PhasorData.Data{PhasorData.Plot(i)}.Intensity <= THmax;
            ROI=repmat(ROI,[1 1 3]);
            Mask=reshape(FractionColor(roi+1,:),size(Image));  
        elseif strcmp(h.Phasor_FRET(1,1).Visible,'on') && h.FRET_Use.Value==3
            %% FRET spot
            %%% Extracts circle radius and position
            Radius=str2double(h.FRET_Size.String);
            g=h.Phasor_FRET(4,2).XData;
            s=h.Phasor_FRET(4,2).YData;
            
            Color(1,1,1:3)=h.FRET_Line(4,1).BackgroundColor;
            %%% Calculates Phasor positions relative to center of circle
            G=PhasorData.Data{PhasorData.Plot(i)}.g-g;
            S=PhasorData.Data{PhasorData.Plot(i)}.s-s;
            roi=sqrt(G.^2+S.^2)<Radius;
            ROI=roi>0 &...
                PhasorData.Data{PhasorData.Plot(i)}.Intensity >= THmin &...
                PhasorData.Data{PhasorData.Plot(i)}.Intensity <= THmax;
            ROI=repmat(ROI,[1 1 3]);
            Mask=ROI.*repmat(Color,[size(ROI,1),size(ROI,2),1]);

            
        else
            %% Plain image
            Mask=ones(size(Image));
            ROI=false(size(Image));            
        end

        if h.ImageColor.Value==1
            %%% Scales mask color with intensity for gray colormap
            Image(ROI)=Image(ROI).*Mask(ROI);
        else
            %%% Uses flat mask color for all other colormaps
            Image(ROI)=Mask(ROI);
        end
        clear Mask;
        
        %%% Uses applies selected region to Single plot
        if i==10
           Image(repmat(PhasorData.Selected_Region{PhasorData.Plot(10)},[1 1 3]))=1-Image(repmat(PhasorData.Selected_Region{PhasorData.Plot(10)},[1 1 3]));
        end
        
        %%% Update images
        h.Image_Plot(i,2).CData=Image;
        h.Image_Plot(i,1).XLim=[0,size(Image,2)]+0.5;
        h.Image_Plot(i,1).YLim=[0,size(Image,1)]+0.5;
    else
        if i<10
           h.Image_Panel(i).Title=num2str(i); 
        end
    end
end

%% Calculates and plots Intensity information
if isempty(Images) %%% Plots Intensity plot
    %%% Extracts Intensity, g and s data
    Sel = h.List.Value;    
    Int = cell(7,1); g = cell(7,1); s = cell(7,1);
    for i = Sel(Sel>0)
        %%% All Pixels
        Int{1} = [Int{1}; PhasorData.Data{i}.Intensity(:)];
        g{1} = [g{1}; PhasorData.Data{i}.g(:)];
        s{1} = [s{1}; PhasorData.Data{i}.s(:)];
        %%% ROIs
        for j=1:6
            if strcmp(h.Phasor_ROI(j,1).Visible,'on') %%% Rectangular ROI                
                Pos = h.Phasor_ROI(j,1).Position;
                %%% Generates ROI map
                Int{j+1} =[Int{j+1}; PhasorData.Data{i}.Intensity(...
                    PhasorData.Data{i}.g>=Pos(1) &...
                    PhasorData.Data{i}.g<=(Pos(1)+Pos(3)) &...
                    PhasorData.Data{i}.s>=Pos(2) &...
                    PhasorData.Data{i}.s<=(Pos(2)+Pos(4)))];
                g{j+1} =[g{j+1}; PhasorData.Data{i}.g(...
                    PhasorData.Data{i}.g>=Pos(1) &...
                    PhasorData.Data{i}.g<=(Pos(1)+Pos(3)) &...
                    PhasorData.Data{i}.s>=Pos(2) &...
                    PhasorData.Data{i}.s<=(Pos(2)+Pos(4)))];
                s{j+1} =[s{j+1}; PhasorData.Data{i}.s(...
                    PhasorData.Data{i}.g>=Pos(1) &...
                    PhasorData.Data{i}.g<=(Pos(1)+Pos(3)) &...
                    PhasorData.Data{i}.s>=Pos(2) &...
                    PhasorData.Data{i}.s<=(Pos(2)+Pos(4)))];
            elseif strcmp(h.Phasor_ROI(j,2).Visible,'on') %%% Ellipoid ROI
                %%% Determins position of ROI
                x = round(Pixel*(h.Phasor_ROI(j,2).XData+0.1));
                y = round(Pixel*(h.Phasor_ROI(j,2).YData+0.1));
                x(x<1) = 1; y(y<1) = 1;
                Map = zeros(1.3*Pixel);
                %%% Transforms ROI position into pixelmap
                Map(sub2ind(size(Map),x,y))=1;
                %%% Fills ROI pixelmap
                Map=mod(cumsum(Map),2);
                %%% Finds valid pixel
                G = round((PhasorData.Data{i}.g+0.1)*Pixel);
                G(isnan(G) | G<1) = 1;
                S = round((PhasorData.Data{i}.s+0.1)*Pixel);
                S(isnan(S) | S<1) = 1;
                %%% Generates ROI map
                Int{j+1} = [Int{j+1}; PhasorData.Data{i}.Intensity(Map(sub2ind(size(Map),G,S))==1)];
                g{j+1} = [g{j+1}; PhasorData.Data{i}.g(Map(sub2ind(size(Map),G,S))==1)];
                s{j+1} = [s{j+1}; PhasorData.Data{i}.s(Map(sub2ind(size(Map),G,S))==1)];
            end
        end
    end
    
    %%% Calculates bins for intensity axis
    Max = str2double(h.THmax.String);
    Min = str2double(h.THmin.String);
    Scale = max([ceil(log10(Max))-2,0]);
    XData = (floor(Min/10^Scale)*10^Scale):10^Scale:max(Max);
    
    
    if h.Int_Type.Value<4 %%% Updates lineplots
        for i=1:7 %%% Updates plots for and
            h.Int_Plot(1,i+1).XData = XData;
            if ~isempty(Int{i})
                switch h.Int_Type.Value
                    case 1 %%% Frequency vs. Int
                        YData = histc(Int{i},XData);
                        switch h.Int_Norm.Value
                            case 1 %%% No normalization
                                h.Int_Plot(1,i+1).YData = YData;
                            case 2 %%% Area normalization
                                h.Int_Plot(1,i+1).YData = YData./sum(YData);
                            case 3 %%% Maximum normalization
                                h.Int_Plot(1,i+1).YData = YData./max(YData);
                        end
                    case 2 %%% mean g vs int
                        [Int{i},Index] = sort(Int{i});
                        Int{i} = [0; Int{i}];
                        g{i} = [0; cumsum(g{i}(Index))];
                        k=1;
                        for j = 1:numel(XData)
                            Bin = find(Int{i}>=XData(j),1,'first');
                            if ~isempty(Bin)
                                YData(j) = (g{i}(Bin)-g{i}(k))/(Bin-k);
                                k = Bin;
                            else
                                YData(j) = 0;
                            end
                        end
                        h.Int_Plot(1,i+1).YData = YData;
                    case 3 %%% mean s vs int
                        [Int{i},Index] = sort(Int{i});
                        Int{i} = [0; Int{i}];
                        s{i} = [0; cumsum(s{i}(Index))];
                        k=1;
                        for j = 1:numel(XData)
                            Bin = find(Int{i}>=XData(j),1,'first');
                            if ~isempty(Bin)
                                YData(j) = (s{i}(Bin)-s{i}(k))/(Bin-k);
                                k = Bin;
                            else
                                YData(j) = 0;
                            end
                        end
                        h.Int_Plot(1,i+1).YData = YData;
                        
                end
                
            else
                h.Int_Plot(1,i+1).YData = 0*XData;
            end
        end
        h.Int_Plot(9).Visible = 'off';
        h.Int_Plot(1).YLimMode = 'auto';
    else %%% g/s vs int histogram   
        %%% Determins g\s resolution
        Pixel=str2double(h.Phasor_Res.String);
        %%% Uses last selected ROI or total for plotting
        ROI = find(~cellfun(@isempty,Int),1,'last');
        %%% Exits function, if no file is loaded
        if isempty(ROI)
            return;
        end
        %%% Removes unused intensity pixels
        Int = Int{ROI};
        Int(Int<Min) = NaN; Int((Max+10^Scale)) = NaN;
        %%% Calculates 2D histogram as long vector for speed
        switch h.Int_Type.Value
            case 4 %%% g vs Int
                g = floor((g{ROI}+0.1)*Pixel)-1;
                g(g<0) = NaN; g(g>=1.3*Pixel) = NaN;
                Int = Int+g*XData(end);
            case 5 %%% s vs Int
                s = floor((s{ROI}+0.1)*Pixel)-1;
                s(s<0) = NaN; s(s>=1.3*Pixel) = NaN;
                Int = Int+s*XData(end);
        end        
        Bins = repmat(XData',[1,1.3*Pixel])+repmat(((0:(1.3*Pixel-1))*XData(end)),[numel(XData),1]);       
        Image = histc(Int,Bins(:));
        %%% Reshapes 2D histogram
        Image = reshape(Image,[numel(XData),1.3*Pixel])';
        %%% Performs binwise mormalization
        if h.Int_Norm.Value==2
            Image = Image./repmat(sum(Image),[size(Image,1),1]);
        elseif h.Int_Norm.Value==3
            Image = Image./repmat(max(Image),[size(Image,1),1]);
        end
        Image(isnan(Image)) = 0;   

        %%% Transforms 2D histogram to phasor colormap
        Image = ceil(Image/max(max(Image))*128)+1;        
        switch h.PhasorColor.Value
            case 1
                PhasorColor=[1 1 1;jet(128)];
            case 2
                PhasorColor=[1 1 1;hot(128)];
            case 3
                PhasorColor=[1 1 1;gray(128)];
            case 4
                PhasorColor=[1 1 1;hsv(128)];
            otherwise
                PhasorColor=[1 1 1;jet(128)];
        end       
        CData = reshape(PhasorColor(Image(:),:),[size(Image,1),size(Image,2),3]);
        
        %%% Plots 2D histogram and makes it visible
        h.Int_Plot(9).CData = CData;
        h.Int_Plot(9).Visible = 'on';
        uistack(h.Int_Plot(9),'top');
        h.Int_Plot(9).XData = XData;
        h.Int_Plot(9).YData = -0.1:1/Pixel:(1.3);
        h.Int_Plot(1).XLim = [XData(1) XData(end)];
        h.Int_Plot(1).YLim = [-0.1 1.3];
    end
    h.Int_Plot(1).XLim = [XData(1) XData(end)];
end

%% Saves UserValues

UserValues.Phasor.Settings_THMin = h.THmin.String;
UserValues.Phasor.Settings_THMax = h.THmax.String;
UserValues.Phasor.Settings_Use_AS = h.Autoscale.Value;
UserValues.Phasor.Settings_ASMin = h.ASmin.String;
UserValues.Phasor.Settings_ASMax = h.ASmax.String;
UserValues.Phasor.Settings_ImageColor = h.ImageColor.Value;
UserValues.Phasor.Settings_Resolution = h.Phasor_Res.String;
UserValues.Phasor.Settings_PhasorColor = h.PhasorColor.Value;
UserValues.Phasor.Settings_LineColor = h.Fraction_Color.Value;
LSUserValues(1);
  



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Changes ROI appearance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% 1: Enables\Disables ROIs or Changes ROI color
%%% 2: Changes ROI linewidth
%%% 3: Changes ROI linestyle
function ROI_Look(~,~,mode,ROI)   
h = guidata(findobj('Tag','Phasor'));
global UserValues

switch mode
    case 1 %% ROI main control click
        Type=h.Phasor.SelectionType; 
        switch Type
            case 'normal'
                %% Left click:      Enables\Disables rectangular ROI\Fraction line
                if ROI<7
                    if strcmp(h.Phasor_ROI(ROI,1).Visible,'on')
                        h.Phasor_ROI(ROI,1).Visible='off';
                    else
                        h.Phasor_ROI(ROI,1).Visible='on';
                    end
                    h.Phasor_ROI(ROI,2).Visible='off';
                    h.Phasor_Fraction.Visible='off';
                    h.Phasor_Triangle.Visible ='off';
                elseif ROI==7
                    if strcmp(h.Phasor_Fraction.Visible,'on')
                        h.Phasor_Fraction.Visible='off';
                    else
                        h.Phasor_Fraction.Visible='on';
                    end
                    for i=1:6
                        h.Phasor_ROI(i,1).Visible='off';
                        h.Phasor_ROI(i,2).Visible='off';
                    end
                    h.Phasor_Triangle.Visible ='off';
                elseif ROI==8
                    if strcmp(h.Phasor_Triangle.Visible,'on')
                        h.Phasor_Triangle.Visible='off';
                    else
                        h.Phasor_Triangle.Visible='on';
                    end
                    for i=1:6
                        h.Phasor_ROI(i,1).Visible='off';
                        h.Phasor_ROI(i,2).Visible='off';
                    end
                    h.Phasor_Fraction.Visible ='off';
                end
                [h.Phasor_FRET(1:4,:).Visible,h.Phasor_FRET(5,1).Visible] = deal('off');
                Plot_Phasor([],[],0,1:10);
            case 'alt'
                %% Right click:     Enables\Disables ellipoidal ROI\Fraction line
                if ROI<7
                    if strcmp(h.Phasor_ROI(ROI,2).Visible,'on')
                        h.Phasor_ROI(ROI,2).Visible='off';
                    else
                        h.Phasor_ROI(ROI,2).Visible='on';
                    end
                    h.Phasor_ROI(ROI,1).Visible='off';
                    h.Phasor_Fraction.Visible='off';
                elseif ROI==7
                    if strcmp(h.Phasor_Fraction.Visible,'on')
                        h.Phasor_Fraction.Visible='off';
                    else
                        h.Phasor_Fraction.Visible='on';
                    end
                    for i=1:6
                        h.Phasor_ROI(i,1).Visible='off';
                        h.Phasor_ROI(i,2).Visible='off';
                    end
                elseif ROI==8
                    if strcmp(h.Phasor_Triangle.Visible,'on')
                        h.Phasor_Triangle.Visible='off';
                    else
                        h.Phasor_Triangle.Visible='on';
                    end
                    for i=1:6
                        h.Phasor_ROI(i,1).Visible='off';
                        h.Phasor_ROI(i,2).Visible='off';
                    end
                    h.Phasor_Fraction.Visible ='off';
                end
                [h.Phasor_FRET(1:4,:).Visible,h.Phasor_FRET(5,1).Visible,h.Phasor_Triangle.Visible] = deal('off');
                Plot_Phasor([],[],0,1:10);               
            case 'extend'
                %% Middle click:    Changes ROI\Fraction line color 
                Color=uisetcolor;
                if numel(Color)==3
                    if ROI==7
                        h.Phasor_Fraction.Color=Color;
                    else
                        h.Phasor_ROI(ROI,1).EdgeColor=Color;
                        h.Phasor_ROI(ROI,2).Color=Color;
                    end
                    h.ROI_Color{ROI}.BackgroundColor=Color;
                    if sum(Color)>1.5
                        h.ROI_Color{ROI}.ForegroundColor=[0 0 0];
                    else
                        h.ROI_Color{ROI}.ForegroundColor=[1 1 1];
                    end
                    UserValues.Phasor.Settings_ROIColor (ROI,1:3) = Color;
                    Plot_Phasor([],[],0,1:10);           
                end
        end
    case 2 %% ROI linewidth
        if ROI==7
            h.Phasor_Fraction.LineWidth=str2double(h.ROI_Width{ROI}.String);
        else
            h.Phasor_ROI(ROI,1).LineWidth=str2double(h.ROI_Width{ROI}.String);
            h.Phasor_ROI(ROI,2).LineWidth=str2double(h.ROI_Width{ROI}.String);
        end
        UserValues.Phasor.Settings_ROIWidth{ROI} = h.ROI_Width{ROI}.String;
    case 3 %% ROI linestyle
        if ROI==7
            h.Phasor_Fraction.LineStyle=h.ROI_Style{ROI}.String;
        else
            h.Phasor_ROI(ROI,1).LineStyle=h.ROI_Style{ROI}.String;
            h.Phasor_ROI(ROI,2).LineStyle=h.ROI_Style{ROI}.String;
        end
        UserValues.Phasor.Settings_ROIStyle{ROI} = h.ROI_Style{ROI}.String;
    case 4 %% Width of ellipsoid selection
        UserValues.Phasor.Settings_ROISize{ROI} = h.ROI_Size{ROI}.String;
        if ROI<7
            
            Pixel=str2double(h.Phasor_Res.String');
            Width=str2double(h.ROI_Size{ROI}.String);
            
            
            %%% Generates vector, connecting start and end
            x1=linspace(h.Phasor_ROI(ROI,2).UserData(1), h.Phasor_ROI(ROI,2).UserData(3),Pixel);
            y1=linspace(h.Phasor_ROI(ROI,2).UserData(2), h.Phasor_ROI(ROI,2).UserData(4),Pixel);
            
            %%% Creates circle
            x=cos(2*pi*(0:0.01:1));
            y=sin(2*pi*(0:0.01:1));
            x2=[];y2=[];
            
            %%% Applies circle around each point on line
            for i=1:Pixel;
                x2(end+1:end+numel(x))=round(Pixel*(Width*x+x1(i)));
                y2(end+1:end+numel(y))=round(Pixel*(Width*y+y1(i)));
            end
            %%% Transforms points to integers
            Xmin=min(x2)-1; x2=x2-Xmin;
            Ymin=min(y2)-1; y2=y2-Ymin;
            %%% Draws circles into a pixelmap
            Map1=zeros(max(x2),max(y2));
            Map1(sub2ind(size(Map1),x2,y2))=1;
            %%% Only uses edgepoints in map
            Map2=zeros(size(Map1));
            for j=1:size(Map1,2)
                Map2(find(Map1(:,j),1,'first'),j)=1;
                Map2(find(Map1(:,j),1,'last'),j)=1;
            end
            %%% Transforms pixelmat to coordinates
            [x,y]=find(Map2);
            %%% Shifts coordinates to right position
            x=(x+Xmin)/Pixel;
            y=(y+Ymin)/Pixel;
            %%% Updates ROI object
            h.Phasor_ROI(ROI,2).XData=[x(1:2:end); flipud(x(2:2:end)); x(1)];
            h.Phasor_ROI(ROI,2).YData=[y(1:2:end); flipud(y(2:2:end)); y(1)];
        else
            
        end
        Plot_Phasor([],[],0,1:10);

        
    otherwise
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Changes FRET appearance %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function FRET_Look(~,~,mode,Line)
h=guidata(findobj('Tag','Phasor'));
global UserValues
switch mode
    case 1 %% Changes FRET line color
        Type=h.Phasor.SelectionType;
        switch Type                
            case 'extend'
                %% Middle click:    Changes FRET line color
                Color=uisetcolor;
                if numel(Color)==3
                    h.FRET_Line(Line).BackgroundColor=Color;
                    if sum(Color)>1.5
                        h.FRET_Line(Line).ForegroundColor=[0 0 0];
                    else
                        h.FRET_Line(Line).ForegroundColor=[1 1 1];
                    end
                    h.Phasor_FRET(Line,1).Color=Color;
                    h.Phasor_FRET(Line,2).Color=Color;
                    if Line==4
                        h.Phasor_FRET(5,1).Color=Color;
                    end
                    UserValues.Phasor.Settings_FRETColor (Line,1:3) = Color;
                end
        end
    case 2 %% Changes FRET line width
        h.Phasor_FRET(Line,1).LineWidth=str2double(h.FRET_Line(Line,2).String);
        if Line==4
            h.Phasor_FRET(5,1).LineWidth=str2double(h.FRET_Line(4,2).String);
        end
        UserValues.Phasor.Settings_FRETWidth{Line} = h.FRET_Line(Line,2).String;
    case 3 %% Changes FRET line style
        h.Phasor_FRET(Line,1).LineStyle=h.FRET_Line(Line,3).String;
        UserValues.Phasor.Settings_FRETStyle{Line} = h.FRET_Line(Line,3).String;
    case 4 %% Changes FRET marker style
        h.Phasor_FRET(Line,2).Marker=h.FRET_Line(Line,4).String;
        UserValues.Phasor.Settings_FRETMarker{Line} = h.FRET_Line(Line,4).String;
    case 5 %% Changes FRET marker size
        h.Phasor_FRET(Line,2).MarkerSize=str2double(h.FRET_Line(Line,5).String); 
        UserValues.Phasor.Settings_FRETSize{Line} = h.FRET_Line(Line,5).String;
end
LSUserValues(1);


       
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Callbacks of Plots_Menu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% 1: Exports current figure as TIFF
%%% 2: Exports current figure to new figure
function Plots_Menu_Callback (~,~,mode)
global UserValues
obj=gca;
switch mode
    case 1 %%% Exports current figure as TIFF
        [FileName,PathName] = uiputfile({'*.tif'}, 'Save TIFF as', UserValues.File.ExportPath);
        if FileName~=0
            UserValues.File.ExportPath=PathName;
            LSUserValues(1)
            imwrite(obj.Children(1).CData,fullfile(PathName,FileName));
        end
    case 2 %%% Exports current image to new figure
        figure;A=axes;
        obj=copyobj(obj.Children(1),A);
        A.DataAspectRatio=[1 1 1];
        A.XLim=[0.5 size(obj.CData,1)+0.5];
        A.YLim=[0.5 size(obj.CData,2)+0.5];
        A.XTick=[];
        A.YTick=[];
        A.YDir='reverse';
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Recalculates the center of mean of a file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Update_CoM(~,~,File,mode)
global PhasorData
h=guidata(findobj('Tag','Phasor'));

if isempty(PhasorData.Data)
    return;
end
if h.Phasor_Center.Value == 1
    h.Phasor_CoM_Marker.Visible = 'off';
else
    h.Phasor_CoM_Marker.Visible = 'on';
end

%%% Updates settings
if any(mode == 0)
    Marker = 2;
    for i=1:numel(h.Phasor_CoM_Marker.String)
        if strcmp(h.Phasor_CoM_Marker.String{i},PhasorData.CoM{h.List.Value(1)}.Marker)
            Marker = i;
            break;
        end
    end
    h.Phasor_CoM_Marker.Value = Marker;
    h.Phasor_CoM_Marker.ForegroundColor = PhasorData.CoM{h.List.Value(1)}.CData;
end

%%% Calculates position
if any(mode == 1)
    if File == 0
        File = 1:numel(PhasorData.CoM);
    end
    
    switch h.Phasor_Center.Value
        
        case 1 %%% Do not show
            
        case 2 %%% Photon weighted CoM
            TH_Max = str2double(h.THmax.String);
            TH_Min = str2double(h.THmin.String);
            for i=File
                g = PhasorData.Data{i}.g(:);
                s = PhasorData.Data{i}.s(:);
                Int = PhasorData.Data{i}.Intensity(:);
                    
                %%% Remove unselected pixels and pixels outside of
                %%% threshold
                Int(PhasorData.Data{i}.Intensity<TH_Min | PhasorData.Data{i}.Intensity>TH_Max | PhasorData.Selected_Region{i})=NaN;
                %%% Remove pixels as (0,0), usually 0 photon pixel or from
                %%% particle selection
                Int(g==0 & s==0)=NaN;
                
                g(isnan(Int))=NaN;
                s(isnan(Int))=NaN;
                
                x=nanmean(g(:).*Int(:))/nanmean(Int(:));
                y=nanmean(s(:).*Int(:))/nanmean(Int(:));
                PhasorData.CoM{i}.XData=x;
                PhasorData.CoM{i}.YData=y;
            end
        case 3 %%% Pixel Weighted CoM
            TH_Max = str2double(h.THmax.String);
            TH_Min = str2double(h.THmin.String);
            for i=File
                g = PhasorData.Data{i}.g(:);
                s = PhasorData.Data{i}.s(:);
                
                %%% Remove unselected pixels and pixels outside of
                %%% threshold
                g(PhasorData.Data{i}.Intensity<TH_Min | PhasorData.Data{i}.Intensity>TH_Max | PhasorData.Selected_Region{i})=NaN;
                %%% Remove pixels as (0,0), usually 0 photon pixel or from
                %%% particle selection                
                g(g==0 & s==0)=NaN;
                s(isnan(g))=NaN;
                
                x=nanmean(g(:));
                y=nanmean(s(:));
                PhasorData.CoM{i}.XData=x;
                PhasorData.CoM{i}.YData=y;
            end
    end
end

%%% Updates visibility
if any(mode == 2)
    if File == 0
        File = 1:numel(PhasorData.CoM);
    end
    for i = File
        if h.Phasor_Center.Value == 1 || ((h.Main_Tab.SelectedTab == h.Single_Tab) && (i ~= h.List.Value(1))) || ((h.Main_Tab.SelectedTab ~= h.Single_Tab) && (PhasorData.Selected(i) == 0))
            PhasorData.CoM{i}.Visible = 'off';
        else
            PhasorData.CoM{i}.Visible = 'on';
        end
    end
    
end

%%% Updates marker type
if any(mode == 3)
    for i = h.List.Value
        PhasorData.CoM{i}.Marker = h.Phasor_CoM_Marker.String{h.Phasor_CoM_Marker.Value}; 
    end
end
%%% Updates marker size
if any(mode == 4)
   
        Size = inputdlg('Set Marker Size','Marker Size',1,{num2str(PhasorData.CoM{h.List.Value(1)}.SizeData)});
        for i = h.List.Value
            PhasorData.CoM{i}.SizeData = str2double(Size);
        end
end
%%% Updates line width
if any(mode == 5)
    Width = inputdlg('Set Line Width','Line Width',1,{num2str(PhasorData.CoM{h.List.Value(1)}.LineWidth)});
    for i = h.List.Value
        PhasorData.CoM{i}.LineWidth = str2double(Width);
    end
end

%%% Updates line color
if any(mode == 6)
    Color = uisetcolor(PhasorData.CoM{h.List.Value(1)}.CData);
    if numel(Color)==3
        for i = h.List.Value
            PhasorData.CoM{i}.CData = Color;
            h.Phasor_CoM_Marker.ForegroundColor = PhasorData.CoM{h.List.Value(1)}.CData;
        end
    else
        for i = h.List.Value
            PhasorData.CoM{i}.CData = 'none';
            h.Phasor_CoM_Marker.ForegroundColor = [1 1 1];
        end
        
    end
end

%%% Updates line color
if any(mode == 7)
    Color = uisetcolor(PhasorData.CoM{h.List.Value(1)}.MarkerFaceColor);
    if numel(Color)==3
        for i = h.List.Value
            PhasorData.CoM{i}.MarkerFaceColor = Color;
        end
    else
        for i = h.List.Value
            PhasorData.CoM{i}.MarkerFaceColor = 'none';
        end
    end
end
%%% Make fill transparent
if any(mode == 8)
    for i = h.List.Value
        PhasorData.CoM{i}.MarkerFaceColor = 'none';
    end
end


function Misc(obj,e,mode)
global UserValues
h = guidata(findobj('Tag','Phasor'));

if nargin<3 %%% Single source functions
   switch obj %%% Export Font Selection
       case h.Export_Font
           f = uisetfont;
           if ~isstruct(f)
               return;
           end
           f.FontString = ['Export Font: ' f.FontName];
           if strcmp(f.FontWeight, 'bold')
               f.FontString = [f.FontString ', b'];
           end
           if strcmp(f.FontAngle, 'italic')
               f.FontString = [f.FontString ', i'];
           end
           f.FontString = [f.FontString ' ,' num2str(f.FontSize)];
           
           obj.UserData = f;
           obj.String = f.FontString;
           obj.FontSize = f.FontSize;
           obj.FontName = f.FontName;
           obj.FontWeight = f.FontWeight;
           obj.FontAngle = f.FontAngle;
           
           UserValues.Phasor.Export_Font = f;
           LSUserValues(1);
   end
end





  
    
    
    