classdef EASYSTEM_V1065_2ndPublishedVersion < matlab.apps.AppBase

    % Properties that correspond to app components
    properties (Access = public)
        UIFigure                        matlab.ui.Figure
        ImageAxes                       matlab.ui.control.UIAxes
        LoadSERFilesButton              matlab.ui.control.Button
        ShowRawImageCheckBox            matlab.ui.control.CheckBox
        ColormapsDropDownLabel          matlab.ui.control.Label
        ColormapsDropDown               matlab.ui.control.DropDown
        Filters                         matlab.ui.container.TabGroup
        GaussianTab                     matlab.ui.container.Tab
        GaussianFilterUnitPixelsSliderLabel  matlab.ui.control.Label
        GaussianFilterUnitPixelsSlider  matlab.ui.control.Slider
        FFTTab                          matlab.ui.container.Tab
        FFTAxes                         matlab.ui.control.UIAxes
        FFTFilterSliderLabel            matlab.ui.control.Label
        FFTFilterSlider                 matlab.ui.control.Slider
        DeconvolutionTab                matlab.ui.container.Tab
        BlindDeconvIterationsEditFieldLabel  matlab.ui.control.Label
        BlindDeconvIterationsEditField  matlab.ui.control.NumericEditField
        RLDeconvIterationsEditFieldLabel  matlab.ui.control.Label
        RLDeconvIterationsEditField     matlab.ui.control.NumericEditField
        DeconvoluteImageButton          matlab.ui.control.Button
        ContrastBrightness              matlab.ui.container.TabGroup
        FlatFieldTab                    matlab.ui.container.Tab
        FlatFieldUnevenBrightnessCheckBox  matlab.ui.control.CheckBox
        FlatFieldCorrectionSigmaSliderLabel  matlab.ui.control.Label
        FlatFieldCorrectionSigmaSlider  matlab.ui.control.Slider
        IntensityInTab                  matlab.ui.container.Tab
        LowInSliderLabel                matlab.ui.control.Label
        LowInSlider                     matlab.ui.control.Slider
        HighInSliderLabel               matlab.ui.control.Label
        HighInSlider                    matlab.ui.control.Slider
        IntensityOutTab                 matlab.ui.container.Tab
        LowOutSliderLabel               matlab.ui.control.Label
        LowOutSlider                    matlab.ui.control.Slider
        HighOutSliderLabel              matlab.ui.control.Label
        HighOutSlider                   matlab.ui.control.Slider
        GammaTab                        matlab.ui.container.Tab
        GammaLabel                      matlab.ui.control.Label
        GammaSlider                     matlab.ui.control.Slider
        Quantify_ScaleBar               matlab.ui.container.TabGroup
        AtomPositionTab                 matlab.ui.container.Tab
        ThresholdsigmaEditFieldLabel    matlab.ui.control.Label
        ThresholdsigmaEditField         matlab.ui.control.NumericEditField
        MinDistanceEditFieldLabel       matlab.ui.control.Label
        MinDistanceEditField            matlab.ui.control.NumericEditField
        CalculateLatticeButton          matlab.ui.control.Button
        OriginXEditFieldLabel           matlab.ui.control.Label
        OriginXEditField                matlab.ui.control.NumericEditField
        YEditFieldLabel                 matlab.ui.control.Label
        OriginYEditField                matlab.ui.control.NumericEditField
        LatNumPlotEditFieldLabel        matlab.ui.control.Label
        LatNumPlotEditField             matlab.ui.control.NumericEditField
        LatFracUEditFieldLabel          matlab.ui.control.Label
        LatFracUEditField               matlab.ui.control.NumericEditField
        LatFracVEditFieldLabel          matlab.ui.control.Label
        LatFracVEditField               matlab.ui.control.NumericEditField
        FindInitialPositionsButton      matlab.ui.control.Button
        ShowInitialpositionsCheckBox    matlab.ui.control.CheckBox
        SpotsColorDropDownLabel         matlab.ui.control.Label
        InitialSpotsColorDropDown       matlab.ui.control.DropDown
        ShowLatticepositionsCheckBox    matlab.ui.control.CheckBox
        RefinePositionsButton           matlab.ui.control.Button
        ShowrefinedpositionsCheckBox    matlab.ui.control.CheckBox
        SpotsColorDropDown_2Label       matlab.ui.control.Label
        RefinedSpotsColorDropDown       matlab.ui.control.DropDown
        MpfitOverlapsButton             matlab.ui.control.Button
        MPfitpositionsCheckBox          matlab.ui.control.CheckBox
        CrossColorLabel                 matlab.ui.control.Label
        CrossColorDropDown              matlab.ui.control.DropDown
        CrossColorDropDown_2Label       matlab.ui.control.Label
        RefinedCrossColorDropDown       matlab.ui.control.DropDown
        AddMissingPointsButton          matlab.ui.control.Button
        DefineAreaofInterestButton      matlab.ui.control.Button
        UendXEditFieldLabel             matlab.ui.control.Label
        UendXEditField                  matlab.ui.control.NumericEditField
        YEditFieldLabel_2               matlab.ui.control.Label
        UendYEditField                  matlab.ui.control.NumericEditField
        VendXEditFieldLabel             matlab.ui.control.Label
        VendXEditField                  matlab.ui.control.NumericEditField
        YEditFieldLabel_3               matlab.ui.control.Label
        VendYEditField                  matlab.ui.control.NumericEditField
        RemoveExtraPointsButton         matlab.ui.control.Button
        SaveAtomPositionsButton         matlab.ui.control.Button
        FileLocationTextBox             matlab.ui.control.TextArea
        FindOriginButton                matlab.ui.control.Button
        FindUButton                     matlab.ui.control.Button
        FindVButton                     matlab.ui.control.Button
        QuantifyTab                     matlab.ui.container.Tab
        CalculateBondLengthBasedonNearNeighborButton  matlab.ui.control.Button
        IfShowBondLengthMapCheckBox     matlab.ui.control.CheckBox
        CalculateBondLengthBasedonLatticeButton  matlab.ui.control.Button
        ColormapsDropDown_2Label        matlab.ui.control.Label
        BondLengthColormapsDropDown     matlab.ui.control.DropDown
        InvertBondColorCheckBox         matlab.ui.control.CheckBox
        MeanDistanceEditFieldLabel      matlab.ui.control.Label
        MeanDistanceEditField           matlab.ui.control.NumericEditField
        MeasurementRangeEditFieldLabel  matlab.ui.control.Label
        MeasurementRangeEditField       matlab.ui.control.NumericEditField
        LineStyleDropDownLabel          matlab.ui.control.Label
        LineStyleDropDown               matlab.ui.control.DropDown
        LineWidthSlider_2Label          matlab.ui.control.Label
        LineWidthSlider_2               matlab.ui.control.Slider
        GenerateBondLengthHistogramButton  matlab.ui.control.Button
        CalculateStrainbasedonatomicpositionsButton  matlab.ui.control.Button
        StrainUpperLowerLimitEditFieldLabel  matlab.ui.control.Label
        StrainUpperLowerLimitEditField  matlab.ui.control.NumericEditField
        Atom_SeparateTab                matlab.ui.container.Tab
        SeparateAtomsCheckBox           matlab.ui.control.CheckBox
        SeparateAtomSpeciesButton       matlab.ui.control.Button
        ThresholdSliderLabel            matlab.ui.control.Label
        ThresholdSlider                 matlab.ui.control.Slider
        PlotNNDistributionButton        matlab.ui.control.Button
        PairDistributionFunctionButton  matlab.ui.control.Button
        XAxisLimitEditFieldLabel        matlab.ui.control.Label
        XAxisLimitEditField_PDF         matlab.ui.control.NumericEditField
        XAxisLimitEditField_2Label      matlab.ui.control.Label
        XAxisLimitEditField_NN          matlab.ui.control.NumericEditField
        NeighborsEditFieldLabel         matlab.ui.control.Label
        NeighborsEditField_NN           matlab.ui.control.NumericEditField
        NeighborsEditFieldLabel_2       matlab.ui.control.Label
        NeighborsEditField_PDF          matlab.ui.control.NumericEditField
        Find_Trios                      matlab.ui.control.Button
        Find_Triangles                  matlab.ui.control.Button
        Find_Monos                      matlab.ui.control.Button
        FindNumNeighbors_W              matlab.ui.control.Button
        FindNumNeighbors_Mo             matlab.ui.control.Button
        NoteTextAreaLabel               matlab.ui.control.Label
        NoteTextArea                    matlab.ui.control.TextArea
        ScaleBarTab                     matlab.ui.container.Tab
        PositionYSlider                 matlab.ui.control.Slider
        YSlider                         matlab.ui.control.Slider
        ScaleBarSwitch                  matlab.ui.control.Switch
        ScaleBarTextCheckBox            matlab.ui.control.CheckBox
        TxtColorDropDown                matlab.ui.control.DropDown
        PositionXYSliderLabel           matlab.ui.control.Label
        PositionXYSlider                matlab.ui.control.Slider
        LengthnmEditFieldLabel          matlab.ui.control.Label
        LengthnmEditField               matlab.ui.control.NumericEditField
        FontSizeEditFieldLabel          matlab.ui.control.Label
        FontSizeEditField               matlab.ui.control.NumericEditField
        TextPositionXYSliderLabel       matlab.ui.control.Label
        TextPositionXYSlider            matlab.ui.control.Slider
        LineWidthSliderLabel            matlab.ui.control.Label
        LineWidthSlider                 matlab.ui.control.Slider
        RotateBy90Button                matlab.ui.control.Button
        NoteTextArea_2Label             matlab.ui.control.Label
        NoteTextArea_2                  matlab.ui.control.TextArea
        InverseColorImageCheckBox       matlab.ui.control.CheckBox
        resetButton                     matlab.ui.control.Button
        LoadImageFileButton             matlab.ui.control.Button
        LoadAtomPositionsButton         matlab.ui.control.Button
        CalibrationLabel                matlab.ui.control.Label
        CalibrationEditField            matlab.ui.control.NumericEditField
        ImageCalibrationEditFieldLabel_2  matlab.ui.control.Label
    end

    
    properties (Access = public)
        x = 1800;    % Description
        y = 1900;
        L = 1;
        Line_Width = 5;
        fft_img = []; 
        img = [];
        img_disp = [];
        ser = [];
        off_x = 100;
        off_y = -100;
        font_size = 15;
        ON_OFF = 'off';
        Switch_State = 1;
        Check_Box = 1;
        Raw = [];
        flat = [];
        inverse = [];
        flat_strength = 30;
        if_raw = 0;        
        if_flat = 0;
        if_inverse = 0;
        ScaleBar_Color = [1 1 1];
        in_low = 0;
        in_high = 1;
        out_low = 0;
        out_high = 1;
        gamma = 1;
        
        blind_deconv_iter = 125;
        RL_deconv_iter = 4;
        
        
        % Quantify Functions
        min_dist = 10;
        threshold = 0;
        pos = [];
        posRefineM = [];
        posRefineMPfit = [];
        output = [];
        High_Z_Atom_Pos = [];
        Low_Z_Atom_Pos = [];
        
        if_show_initial = 1;
        initial_spot_color = [1 1 0];
        if_show_refined = 1;
        refined_spot_color = [1 0 0];
        if_show_lat = 1;
        lat_cross_color = [1 0 0];
        ref_lat_cross_color = [0 1 0]
        if_mpfit_exist = 0;
        if_show_ref_lat = 1;
        if_add_missing_pts = 0;
        
        lat = [100 100;100 0;0 100];
        origin_x = 1024;
        origin_y = 1024;        
        U_end_x = 1124;
        U_end_y = 1024;
        V_end_x = 1024;
        V_end_y = 1124;
        
        U_length = 100;
        U_angle = 0;
        V_length = 100;
        V_angle = 90;

        latSiteFrac = [3,3];
        LatNumPlot = 3;
        
        % Bond Length
        xx = [];
        yy = [];
        Line_Color = [];
        Strain_lim = 0.05;
        if_show_bond = 1;
        if_bond_exist = 0;
        newmap = bluewhitered_v3(256);
        mean_disp = 329;
        measure_range = 60;
        bondlength_width = 1;
        bondlength_style = '-';
        
        if_show_separate = 1;
        Sepa_Threshold = 70;
        NN_xaxis_lim = 4;
        PDF_xaxis_lim = 4;
        Num_neighbor_NN = 4;
        Num_neighbor_PDF = 100;
    end
    
    methods (Access = private)
        
        
        function updateimage(app,imagefile)
            
            % For corn.tif, read the second image in the file
            if strcmp(imagefile,'EASYSTEM logo cap.png')
                im = imread('EASYSTEM logo cap.png');                
            else      
                try
                    im = imread(imagefile);
                    
                catch ME
                    % If problem reading image, display error message
                    uialert(app.UIFigure, ME.message, 'Image Error');
                    return;
                end            
            end 
            
            % Create histograms based on number of color channels
            switch size(im,3)
                case 1
                    % Display the grayscale image
                    imagesc(app.ImageAxes,im);
                case 3
                    % Display the truecolor image
                    imagesc(app.ImageAxes,im);                    
                otherwise
                    % Error when image is not grayscale or truecolor
                    uialert(app.UIFigure, 'Image must be grayscale or truecolor.', 'Image Error');
                    return;
            end
         
        end
        
        function plot_ser(app)
%             hold(app.ImageAxes);
%             imagesc(app.ImageAxes,img);
            if app.if_raw == 1 
                app.img_disp = app.Raw;
                imagesc(app.ImageAxes,app.img_disp);
            elseif app.if_flat == 1
                app.flat = imflatfield(app.img,app.flat_strength);
                app.img_disp = imadjust(app.flat,[app.in_low app.in_high],[app.out_low app.out_high],app.gamma);
                imagesc(app.ImageAxes,app.img_disp);
                
            else
                size(app.img);
                app.img_disp = imadjust(ImNorm(app.img),[app.in_low app.in_high],[app.out_low app.out_high],app.gamma);
                imagesc(app.ImageAxes,app.img_disp);   
            end
            
            if app.if_inverse == 1
                
                if (isempty(app.img_disp)) || app.if_raw == 1
                    app.inverse = ImNorm(-app.Raw);
                else
                app.inverse = ImNorm(-app.img_disp);
                end
                imagesc(app.ImageAxes,app.inverse);            
            end
            
     
        
            
            if app.if_show_initial == 1 && ~(isempty(app.pos))
                    hold(app.ImageAxes,'on');
                    scatter(app.ImageAxes,app.pos(:,2),app.pos(:,1),'.','MarkerEdgeColor',app.initial_spot_color);
                    hold(app.ImageAxes,'off');
            end          

            if app.if_show_separate == 1 && ~(isempty(app.High_Z_Atom_Pos)) && ~(isempty(app.Low_Z_Atom_Pos))
                    hold(app.ImageAxes,'on');
                    scatter(app.ImageAxes,app.High_Z_Atom_Pos(:,4),app.High_Z_Atom_Pos(:,3),'.','MarkerEdgeColor',[1 0 0]);
                    scatter(app.ImageAxes,app.Low_Z_Atom_Pos(:,4),app.Low_Z_Atom_Pos(:,3),'.','MarkerEdgeColor',[0 0 1]);
%                     scatter(app.ImageAxes,app.High_Z_Atom_Pos(:,4),app.High_Z_Atom_Pos(:,3),'bo','filled');
%                     scatter(app.ImageAxes,app.Low_Z_Atom_Pos(:,4),app.Low_Z_Atom_Pos(:,3),'wo','filled');

                    hold(app.ImageAxes,'off');
            end                      
            
            if app.if_show_refined == 1 && ~(isempty(app.posRefineM))
                    hold(app.ImageAxes,'on');
                    scatter(app.ImageAxes,app.posRefineM(:,4),app.posRefineM(:,3),'.','MarkerEdgeColor',app.refined_spot_color);
                    hold(app.ImageAxes,'off');
            end               
            
            if app.if_show_lat == 1 && ~(isempty(app.pos))
            hold(app.ImageAxes,'on');
            scatter(app.ImageAxes,app.pos(:,6),app.pos(:,5),'+','MarkerEdgeColor',app.lat_cross_color);
            hold(app.ImageAxes,'off');   
            end
            
            if app.if_show_lat == 1 && ~(isempty(app.pos))
            hold(app.ImageAxes,'on');
            quiver(app.ImageAxes,app.lat(1,2),app.lat(1,1),app.lat(2,2)*app.LatNumPlot,app.lat(2,1)*app.LatNumPlot,'LineWidth',4,'Color',[1 0.2 0],'MaxHeadSize',0.3,'AutoScale',"off");            
            quiver(app.ImageAxes,app.lat(1,2),app.lat(1,1),app.lat(3,2)*app.LatNumPlot,app.lat(3,1)*app.LatNumPlot,'LineWidth',4,'Color',[0 0.2 1],'MaxHeadSize',0.3,'AutoScale',"off");
            hold(app.ImageAxes,'off');
            end
            
            if app.if_show_ref_lat == 1 && app.if_mpfit_exist == 1
            hold(app.ImageAxes,'on');
            scatter(app.ImageAxes,app.posRefineMPfit(:,4),app.posRefineMPfit(:,3),'+','MarkerEdgeColor',app.ref_lat_cross_color);
            hold(app.ImageAxes,'off');
            end           
            
            if app.if_show_bond == 1 && app.if_bond_exist == 1
                hold(app.ImageAxes,'on');  
                for kk = 1:length(app.xx)
                    dbstop if error
                        line(app.ImageAxes,app.xx(kk,:),app.yy(kk,:),'Color',app.Line_Color(kk,:),'LineStyle',app.bondlength_style,'LineWidth',app.bondlength_width)           
                end                   
                hold(app.ImageAxes,'off');                
            end
       
            imagesc(app.FFTAxes,app.fft_img);
            app.FFTAxes.Colormap = jet(256);
            app.output.image = app.img_disp;
            
            
            
            
            hold(app.ImageAxes,'on');
            % Scale Bar
            if ( strcmpi(app.ON_OFF,'on') )
                quiver(app.ImageAxes,app.x,app.y,...
                app.L*10^-9/(app.ser.calibration(1))...
                ,0,'ShowArrowHead','off','LineWidth',app.Line_Width,'color',app.ScaleBar_Color);
            
                if app.Check_Box == 1  
                    text(app.ImageAxes,app.x+app.off_x,app.y+app.off_y,[num2str(app.L) 'nm']...
                    ,'Color',app.ScaleBar_Color,'FontWeight','bold','HorizontalAlignment','center','FontSize',app.font_size);
                    hold(app.ImageAxes,'off');           
                else
                    hold(app.ImageAxes,'off');
                end
                
            else
                hold(app.ImageAxes,'off');
            end  
%             
        end
        
        function RealSpaceLattice(app)
        % This function is adopted from the original Realspacelattice01 script 
        % written by Dr. Colin Ophus [clophus@lbl.gov] 
        % at the National Center for Electron Microscopy Lawrence Berkeley National Laboratory
        
            I = app.img_disp;
            I = I - mean(I(:));
            I = I / sqrt(mean(I(:).^2));
    
            p =   I > circshift(I,[-1 -1]) ...
            & I > circshift(I,[ 0 -1]) ...
            & I > circshift(I,[ 1 -1]) ...
            & I > circshift(I,[-1  0]) ...
            & I > circshift(I,[ 1  0]) ...
            & I > circshift(I,[-1  1]) ...
            & I > circshift(I,[ 0  1]) ...
            & I > circshift(I,[ 1  1]) ...
            & I > app.threshold;
            [xp,yp,Ip] = find(p.*I);
        
            if app.min_dist > 0
                data = sortrows([xp yp Ip],3);
                del = false(size(data,1),1);
                r2 = app.min_dist^2;
                for a0 = 1:(size(data,1)-1)
                    d2 = (data(a0,1)-data((a0+1):end,1)).^2 ...
                        + (data(a0,2)-data((a0+1):end,2)).^2;
                    if min(d2) < r2
                        del(a0) = true;
                    end
                end
                data(del,:) = [];  
                xp = data(:,1);
                yp = data(:,2);
            end
            app.pos = [xp yp zeros(length(xp),4)];
            app.output.pos = app.pos;
            
            
%             imagesc(app.ImageAxes,app.img_disp);
%             hold(app.ImageAxes,'on');
%             scatter(app.ImageAxes,app.pos(:,2),app.pos(:,1),'y.');
%             hold(app.ImageAxes,'off');
        end
        
        function Lattice_finder(app)
        % This function is adopted from the original Realspacelattice01 script 
        % written by Dr. Colin Ophus [clophus@lbl.gov] 
        % at the National Center for Electron Microscopy Lawrence Berkeley National Laboratory        
            f = app.latSiteFrac;
            or = app.lat(1,:);
            u = app.lat(2,:);
            v = app.lat(3,:);
            
            dMax = sqrt(max((app.pos(:,1)-or(1)).^2 + (app.pos(:,2)-or(2)).^2));
            dMin = sqrt(min((app.pos(:,1)-or(1)).^2 ...
                + (app.pos(:,2)-or(2)).^2)) + 5*mean([norm(u) norm(v)]);
            for r = dMin:20:dMax
                sub = (app.pos(:,1) - or(1)).^2 ...
                    + (app.pos(:,2) - or(2)).^2 < r^2;
                
                % Compute a,b values
                a = round(f(1)*((app.pos(sub,2)-or(2))*v(1) ...
                    - (app.pos(sub,1)-or(1))*v(2))/(v(1)*u(2)-v(2)*u(1)))/f(1);
                b = round(f(2)*((app.pos(sub,2)-or(2))*u(1) ...
                    - (app.pos(sub,1)-or(1))*u(2))/(v(2)*u(1)-v(1)*u(2)))/f(2);
        
        
                % Refine lattice
                A = [ones(sum(sub),1) a b];
                xbeta = A \ app.pos(sub,1);
                ybeta = A \ app.pos(sub,2);
                or = [xbeta(1) ybeta(1)];
                u = [xbeta(2) ybeta(2)];
                v = [xbeta(3) ybeta(3)];
            end
            
            % Compute a,b values
        
            a = round(f(1)*((app.pos(:,2)-or(2))*v(1) ...
                - (app.pos(:,1)-or(1))*v(2))/(v(1)*u(2)-v(2)*u(1)))/f(1);
            b = round(f(2)*((app.pos(:,2)-or(2))*u(1) ...
                - (app.pos(:,1)-or(1))*u(2))/(v(2)*u(1)-v(1)*u(2)))/f(2);
            % Refine lattice
            A = [ones(size(app.pos,1),1) a b];
            xbeta = A \ app.pos(:,1);
            ybeta = A \ app.pos(:,2);
            or = [xbeta(1) ybeta(1)];
            u = [xbeta(2) ybeta(2)];
            v = [xbeta(3) ybeta(3)];
            
            app.lat(1,:) = or;
            app.lat(2,:) = u;
            app.lat(3,:) = v;
            % generated fitted positions
            xf = or(1) + a*u(1) + b*v(1);
            yf = or(2) + a*u(2) + b*v(2);
            % Export and plot fitted positions
            app.pos(:,3:6) = [a b xf yf];
%             app.pos = sortrows(sortrows(app.pos,4),3);            
            app.output.pos = app.pos;
            app.output.lat = app.lat;
            app.output.latSiteFrac = app.latSiteFrac;
%             app.UangleKnobLabel.Text = ['U Angle is ' num2str(wrapTo2Pi(acot(app.lat(2,1)/app.lat(2,2)))/(2*pi)*360)];
%             app.ULengthSlider.Value = norm(app.lat(2,:));
%             app.VLengthSlider.Value = norm(app.lat(3,:));
%             app.VangleKnobLabel.Text = ['V Angle is ' num2str(wrapTo2Pi(acot(app.lat(3,1)/app.lat(3,2)))/(2*pi)*360)];
        end

        function Lattice_Refine(app)
            f = app.latSiteFrac;
            or = app.lat(1,:);
            u = app.lat(2,:);
            v = app.lat(3,:);
            
            dMax = sqrt(max((app.posRefineM(:,3)-or(1)).^2 + (app.posRefineM(:,4)-or(2)).^2));
            dMin = sqrt(min((app.posRefineM(:,3)-or(1)).^2 ...
                + (app.posRefineM(:,4)-or(2)).^2)) + 5*mean([norm(u) norm(v)]);
            for r = dMin:20:dMax
                sub = (app.posRefineM(:,3) - or(1)).^2 ...
                    + (app.posRefineM(:,4) - or(2)).^2 < r^2;
                
                % Compute a,b values
                a = round(f(1)*((app.posRefineM(sub,4)-or(2))*v(1) ...
                    - (app.posRefineM(sub,3)-or(1))*v(2))/(v(1)*u(2)-v(2)*u(1)))/f(1);
                b = round(f(2)*((app.posRefineM(sub,4)-or(2))*u(1) ...
                    - (app.posRefineM(sub,3)-or(1))*u(2))/(v(2)*u(1)-v(1)*u(2)))/f(2);
        
        
                % Refine lattice
                A = [ones(sum(sub),1) a b];
                xbeta = A \ app.posRefineM(sub,3);
                ybeta = A \ app.posRefineM(sub,4);
                or = [xbeta(1) ybeta(1)];
                u = [xbeta(2) ybeta(2)];
                v = [xbeta(3) ybeta(3)];
            end
            
            % Compute a,b values
        
            a = round(f(1)*((app.posRefineM(:,4)-or(2))*v(1) ...
                - (app.posRefineM(:,3)-or(1))*v(2))/(v(1)*u(2)-v(2)*u(1)))/f(1);
            b = round(f(2)*((app.posRefineM(:,4)-or(2))*u(1) ...
                - (app.posRefineM(:,3)-or(1))*u(2))/(v(2)*u(1)-v(1)*u(2)))/f(2);
            % Refine lattice
            A = [ones(size(app.posRefineM,1),1) a b];
            xbeta = A \ app.posRefineM(:,3);
            ybeta = A \ app.posRefineM(:,4);
            or = [xbeta(1) ybeta(1)];
            u = [xbeta(2) ybeta(2)];
            v = [xbeta(3) ybeta(3)];
            
            app.lat(1,:) = or;
            app.lat(2,:) = u;
            app.lat(3,:) = v;
            % generated fitted positions
            xf = or(1) + a*u(1) + b*v(1);
            yf = or(2) + a*u(2) + b*v(2);
            % Export and plot fitted positions
            app.posRefineM(:,8:11) = [a b xf yf];
%             app.pos = sortrows(sortrows(app.pos,4),3);            

%             app.UangleKnobLabel.Text = ['U Angle is ' num2str(wrapTo2Pi(acot(app.lat(2,1)/app.lat(2,2)))/(2*pi)*360)];
%             app.ULengthSlider.Value = norm(app.lat(2,:));
%             app.VLengthSlider.Value = norm(app.lat(3,:));
%             app.VangleKnobLabel.Text = ['V Angle is ' num2str(wrapTo2Pi(acot(app.lat(3,1)/app.lat(3,2)))/(2*pi)*360)];
        end
        
        function NearNeighbor_Distance(app)             
            [id,Distance]= knnsearch(app.posRefineM(:,3:4),app.posRefineM(:,3:4),'K',10,'Distance','euclidean');
            id_original = id;
            calibration = app.ser.calibration(1);    
            Distance_original = Distance.*calibration*10^12;
            
            mean_ex = app.mean_disp;
            std_distance = app.measure_range;
            min_ex = mean_ex - std_distance;
            max_ex = mean_ex + std_distance;
%             app.newmap = bluewhitered_v3(256);
            
            
            app.xx = zeros(length(id_original)*6,2);
            app.yy = zeros(length(id_original)*6,2);
            app.Line_Color = zeros(length(id_original)*6,3);
          
            for kk = 1:length(id_original)
                for jj = 2:7
                Start_x = app.posRefineM(id_original(kk,1),4);
                Start_y = app.posRefineM(id_original(kk,1),3);
                    if Distance_original(kk,jj) < max_ex && Distance_original(kk,jj) > min_ex                     
                    Color_Scale = ((Distance_original(kk,jj) - min_ex)/(max_ex - min_ex));
                    Color_Scale = ceil(Color_Scale*256);
                    Color_Scale = 1+uint8(Color_Scale);
                    app.Line_Color(kk*10+jj-11,1:3) = app.newmap(Color_Scale,1:3);                   
                    app.xx(kk*10+jj-11,:) = [Start_x app.posRefineM(id_original(kk,jj),4)];
                    app.yy(kk*10+jj-11,:) = [Start_y app.posRefineM(id_original(kk,jj),3)];
                    end                
                end
            end            
            xxs = sort(app.xx,2);
            yys = sort(app.yy,2);
            xxyy = [xxs yys];
            [~,ia,~] = unique(xxyy,'rows');
            app.xx = app.xx(ia,:);
            size(app.xx)
            app.yy = app.yy(ia,:);
            app.Line_Color = app.Line_Color(ia,:);           
        end
        
        function Lattice_Neighbor_Distance(app)

            aa = mod(app.pos(:,3),1);
            bb = mod(app.pos(:,4),1);
            id_a = (aa == 0 & bb == 0);
            posRefine = app.posRefineM(id_a,:);
        
            [id,Distance]= knnsearch(posRefine(:,3:4),posRefine(:,3:4),'K',7,'Distance','euclidean');
            id_original = id;
            calibration = app.ser.calibration(1);    
            Distance_original = Distance.*calibration*10^12;
            
            mean_ex = app.mean_disp;
            std_distance = app.measure_range;
            min_ex = mean_ex - std_distance;
            max_ex = mean_ex + std_distance;

            
            
            app.xx = zeros(length(id_original)*6,2);
            app.yy = zeros(length(id_original)*6,2);
            app.Line_Color = zeros(length(id_original)*6,3);        
            
            for kk = 1:length(id_original)
                for jj = 2:7
                Start_x = posRefine(id_original(kk,1),4);
                Start_y = posRefine(id_original(kk,1),3);
                    if Distance_original(kk,jj) < max_ex && Distance_original(kk,jj) > min_ex                     
                    Color_Scale = ((Distance_original(kk,jj) - min_ex)/(max_ex - min_ex));
                    Color_Scale = ceil(Color_Scale*256);
                    Color_Scale = 1+uint8(Color_Scale);
                    app.Line_Color(kk*6+jj-7,1:3) = app.newmap(Color_Scale,1:3);                   
                    app.xx(kk*6+jj-7,:) = [Start_x posRefine(id_original(kk,jj),4)];
                    app.yy(kk*6+jj-7,:) = [Start_y posRefine(id_original(kk,jj),3)];
                    end                
                end
            end            
            xxs = sort(app.xx,2);
            yys = sort(app.yy,2);
            xxyy = [xxs yys];
            [~,ia,~] = unique(xxyy,'rows');
            app.xx = app.xx(ia,:);
            app.yy = app.yy(ia,:);
                        size(app.xx)

            app.Line_Color = app.Line_Color(ia,:);     
            ColorMap_ScaleBar(min_ex,max_ex,mean_ex,app.newmap);
            
        end
        
        function    Atom_Filter(app)
        
            
            Image = app.img_disp;           
            pos_int = zeros(length(app.posRefineM),1);
            for kk = 1:length(app.posRefineM)
                pos_int(kk) = Image(round(app.posRefineM(kk,3)),round(app.posRefineM(kk,4)));
            end
            Intensity_Percentile = prctile(pos_int(:),app.Sepa_Threshold);
            id = pos_int > Intensity_Percentile;
            
            app.High_Z_Atom_Pos = app.posRefineM(id,:);
            app.Low_Z_Atom_Pos = app.posRefineM(logical(1-id),:);
            
            app.output.Low_Z_Atom_Pos = app.Low_Z_Atom_Pos;
            app.output.High_Z_Atom_Pos = app.High_Z_Atom_Pos;
            
        end
        
        function Trio_Finder(app)
            aa = mod(app.High_Z_Atom_Pos(:,8),1);
            bb = mod(app.High_Z_Atom_Pos(:,9),1);
            id_a = (aa == 0 & bb == 0);
            High_Z_Pos_pool = app.High_Z_Atom_Pos(id_a,:);
            Trios_u = zeros(length(High_Z_Pos_pool),21);    
            Num_atom = length(High_Z_Pos_pool);
            Trios_u(:,1:7) = High_Z_Pos_pool(:,1:7);
            Trios_v = Trios_u;
            Trios_h = Trios_u;
            for i=1:Num_atom
            % Left atom u   
                u = High_Z_Pos_pool(i,8);
                v = High_Z_Pos_pool(i,9);                
                id1 = High_Z_Pos_pool(:,8) == u-1;
                id2 = High_Z_Pos_pool(:,9) == v;                
                id = logical(id1.*id2);                 
                if isempty(High_Z_Pos_pool(id,3:4)) == 0
                    Trios_u(i,8:14) = High_Z_Pos_pool(id,1:7);                
                end
            % right atom u
                id1 = High_Z_Pos_pool(:,8) == u+1;
                id = logical(id1.*id2);                 
                if isempty(High_Z_Pos_pool(id,3:4)) == 0
                    Trios_u(i,15:21) = High_Z_Pos_pool(id,1:7);                
                end         
                clearvars id id1 id2
            % Left atom     
                id1v = High_Z_Pos_pool(:,8) == u;
                id2v = High_Z_Pos_pool(:,9) == v-1;                
                idv = logical(id1v.*id2v);                 
                if isempty(High_Z_Pos_pool(idv,1:7)) == 0
                    Trios_v(i,8:14) = High_Z_Pos_pool(idv,1:7);                
                end
            % right atom     
                id2v = High_Z_Pos_pool(:,9) == v+1;
                idv = logical(id1v.*id2v);                 
                if isempty(High_Z_Pos_pool(idv,3:4)) == 0
                    Trios_v(i,15:21) = High_Z_Pos_pool(idv,1:7);              
                end        
                
           % high     
                u = High_Z_Pos_pool(i,8);
                v = High_Z_Pos_pool(i,9);                
                id1 = High_Z_Pos_pool(:,8) == u-1;
                id2 = High_Z_Pos_pool(:,9) == v-1;                
                id = logical(id1.*id2);                 
                if isempty(High_Z_Pos_pool(id,3:4)) == 0
                    Trios_h(i,8:14) = High_Z_Pos_pool(id,1:7);                
                end
            % low
                id1 = High_Z_Pos_pool(:,8) == u+1;
                id2 = High_Z_Pos_pool(:,9) == v+1;
                id = logical(id1.*id2);                 
                if isempty(High_Z_Pos_pool(id,3:4)) == 0
                    Trios_h(i,15:21) = High_Z_Pos_pool(id,1:7);                
                end                         
                
            end
        ifnonzero = all(Trios_u(:,1:21),2);        
        Trios_u(~ifnonzero,1) = NaN;
        Trios_u(isnan(Trios_u(:,1)),:)=[];        
%         app.output.Trios_u = Trios_u;
        app.output.Trios_u = [Trios_u(:,1:7);Trios_u(:,8:14);Trios_u(:,15:21)];      
        
        ifnonzero = all(Trios_v(:,1:21),2);        
        Trios_v(~ifnonzero,1) = NaN;
        Trios_v(isnan(Trios_v(:,1)),:)=[];        
        app.output.Trios_v = [Trios_v(:,1:7);Trios_v(:,8:14);Trios_v(:,15:21)];            
%         app.output.Trios_v = Trios_v;

        ifnonzero = all(Trios_h(:,1:21),2);        
        Trios_h(~ifnonzero,1) = NaN;
        Trios_h(isnan(Trios_h(:,1)),:)=[];        
        app.output.Trios_h = [Trios_h(:,1:7);Trios_h(:,8:14);Trios_h(:,15:21)];      
        
        
        figure;
        imagesc(app.img_disp);axis image off;colormap(gray);
        hold on;...
        scatter([Trios_u(:,11);Trios_u(:,4);Trios_u(:,18)] ,...
        [Trios_u(:,10);Trios_u(:,3);Trios_u(:,17)] ,'r.');...
        scatter([Trios_v(:,11);Trios_v(:,4);Trios_v(:,18)] ,...
        [Trios_v(:,10);Trios_v(:,3);Trios_v(:,17)] ,'b.');
        scatter([Trios_h(:,11);Trios_h(:,4);Trios_h(:,18)] ,...
        [Trios_h(:,10);Trios_h(:,3);Trios_h(:,17)] ,'g.');    
        
        figure;
        sz = size(app.img_disp);
        imshow(ones(sz(1),sz(2)));
        hold on;...
        scatter([Trios_u(:,11);Trios_u(:,4);Trios_u(:,18)] ,...
        [Trios_u(:,10);Trios_u(:,3);Trios_u(:,17)] ,'r.');...
        scatter([Trios_v(:,11);Trios_v(:,4);Trios_v(:,18)] ,...
        [Trios_v(:,10);Trios_v(:,3);Trios_v(:,17)] ,'b.');
        scatter([Trios_h(:,11);Trios_h(:,4);Trios_h(:,18)] ,...
        [Trios_h(:,10);Trios_h(:,3);Trios_h(:,17)] ,'g.');    
        end
        
        function Mono_Finder(app)
            aa = mod(app.High_Z_Atom_Pos(:,8),1);
            bb = mod(app.High_Z_Atom_Pos(:,9),1);
            id_a = (aa == 0 & bb == 0);
            High_Z_Pos_pool = app.High_Z_Atom_Pos(id_a,:);
            Num_atom = length(High_Z_Pos_pool);
            number_row = 1;
            for i=1:Num_atom
            % Left atom u   
                u = High_Z_Pos_pool(i,8);
                v = High_Z_Pos_pool(i,9);                
                id11 = High_Z_Pos_pool(:,8) == u-1;
                id12 = High_Z_Pos_pool(:,9) == v;                
                id1 = logical(id11.*id12);

            % right atom u
                id13 = High_Z_Pos_pool(:,8) == u+1;
                id2 = logical(id11.*id13);                 

            % Left atom     
                id1v = High_Z_Pos_pool(:,8) == u;
                id2v = High_Z_Pos_pool(:,9) == v-1;                
                id12v = logical(id1v.*id2v);                 

            % right atom     
                id3v = High_Z_Pos_pool(:,9) == v+1;
                id13v = logical(id1v.*id3v);                 

           % high                 
                id1h = High_Z_Pos_pool(:,8) == u-1;
                id2h = High_Z_Pos_pool(:,9) == v-1;                
                id12h = logical(id1h.*id2h);                 

            % low
                id1l = High_Z_Pos_pool(:,8) == u+1;
                id2l = High_Z_Pos_pool(:,9) == v+1;
                id12l = logical(id1l.*id2l);         
                
            if isempty(High_Z_Pos_pool(id1,3:4)) == 1 & isempty(High_Z_Pos_pool(id2,3:4)) == 1 ...
                    & isempty(High_Z_Pos_pool(id12v,3:4)) == 1 & isempty(High_Z_Pos_pool(id12h,3:4)) == 1 & ...
                    isempty(High_Z_Pos_pool(id12l,3:4)) == 1 & isempty(High_Z_Pos_pool(id13v,3:4)) == 1
                    
            Monos(number_row,1:7) = High_Z_Pos_pool(i,1:7);     
            number_row = number_row + 1;    
            end                 
            
            end
        app.output.Monos = Monos;      
        
        
        figure;
        imagesc(app.img_disp);axis image off;colormap(gray);
        hold on;...
        scatter(Monos(:,4) ,Monos(:,3) ,'r.');
        figure;
        sz = size(app.img_disp);
        imshow(ones(sz(1),sz(2)));
        hold on;...
        scatter(Monos(:,4) ,Monos(:,3) ,'r.');
        hold off;
        end
        
        
        
        function Triangle_Finder(app)
            aa = mod(app.High_Z_Atom_Pos(:,8),1);
            bb = mod(app.High_Z_Atom_Pos(:,9),1);
            id_a = (aa == 0 & bb == 0);
            High_Z_Pos_pool = app.High_Z_Atom_Pos(id_a,:);
            Triangles_u = zeros(length(High_Z_Pos_pool),21);    
            Num_atom = length(High_Z_Pos_pool);
            Triangles_u(:,1:7) = High_Z_Pos_pool(:,1:7);
            Triangles_v = Triangles_u;
            for i=1:Num_atom
            % Left atom u   
                u = High_Z_Pos_pool(i,8);
                v = High_Z_Pos_pool(i,9);                
                id1 = High_Z_Pos_pool(:,8) == u-1;
                id2 = High_Z_Pos_pool(:,9) == v;                
                id = logical(id1.*id2);                 
                if isempty(High_Z_Pos_pool(id,3:4)) == 0
                    Triangles_u(i,8:14) = High_Z_Pos_pool(id,1:7);                
                end
            % right atom u
                id1 = High_Z_Pos_pool(:,8) == u;
                id2 = High_Z_Pos_pool(:,9) == v+1;                  
                id = logical(id1.*id2);                 
                if isempty(High_Z_Pos_pool(id,3:4)) == 0
                    Triangles_u(i,15:21) = High_Z_Pos_pool(id,1:7);                
                end         
                
%             Left atom     
                id1v = High_Z_Pos_pool(:,8) == u+1;
                id2v = High_Z_Pos_pool(:,9) == v;                
                idv = logical(id1v.*id2v);                 
                if isempty(High_Z_Pos_pool(idv,1:7)) == 0
                    Triangles_v(i,8:14) = High_Z_Pos_pool(idv,1:7);                
                end
            % right atom     
                id1v = High_Z_Pos_pool(:,8) == u;
                id2v = High_Z_Pos_pool(:,9) == v-1;   
                idv = logical(id1v.*id2v);                 
                if isempty(High_Z_Pos_pool(idv,3:4)) == 0
                    Triangles_v(i,15:21) = High_Z_Pos_pool(idv,1:7);              
                end
         
            end
        ifnonzero = all(Triangles_u(:,1:21),2);        
        Triangles_u(~ifnonzero,1) = NaN;
        Triangles_u(isnan(Triangles_u(:,1)),:)=[];        
%         app.output.Triangles_u = Triangles_u;
        app.output.Triangles_u = [Triangles_u(:,1:7);Triangles_u(:,8:14);Triangles_u(:,15:21)];
        
        ifnonzero = all(Triangles_v(:,1:21),2);        
        Triangles_v(~ifnonzero,1) = NaN;
        Triangles_v(isnan(Triangles_v(:,1)),:)=[];        
        app.output.Triangles_v = [Triangles_v(:,1:7);Triangles_v(:,8:14);Triangles_v(:,15:21)];
        
        figure;
       
        imagesc(app.img_disp);axis image off;colormap(gray);
        hold on;...
        scatter([Triangles_u(:,11);Triangles_u(:,4);Triangles_u(:,18)] ,...
        [Triangles_u(:,10);Triangles_u(:,3);Triangles_u(:,17)] ,'r.');...
        scatter([Triangles_v(:,11);Triangles_v(:,4);Triangles_v(:,18)] ,...
        [Triangles_v(:,10);Triangles_v(:,3);Triangles_v(:,17)] ,'b.');        
    
        figure;
        sz = size(app.img_disp);
        imshow(ones(sz(1),sz(2)));
        hold on;...
        scatter([Triangles_u(:,11);Triangles_u(:,4);Triangles_u(:,18)] ,...
        [Triangles_u(:,10);Triangles_u(:,3);Triangles_u(:,17)] ,'r.');...
        scatter([Triangles_v(:,11);Triangles_v(:,4);Triangles_v(:,18)] ,...
        [Triangles_v(:,10);Triangles_v(:,3);Triangles_v(:,17)] ,'b.');                
        
        end
        
        
        function NearNeighborMarker(app)
     
            W = app.High_Z_Atom_Pos;
            calibration = app.ser.calibration(1);
            [Idx,~] = rangesearch(W(:,3:4),W(:,3:4),350/(calibration*10^12));
            num_neighbor = zeros(length(Idx),1);
            
            for ii = 1:length(Idx)
                s = size(Idx{ii});
                num_neighbor(ii) = s(2)-1;         
            end
            
            id0 = num_neighbor(:) == 0;
            id1 = num_neighbor(:) == 1;
            id2 = num_neighbor(:) == 2;
            id3 = num_neighbor(:) == 3;
            id4 = num_neighbor(:) == 4;
            id5 = num_neighbor(:) == 5;
            id6 = num_neighbor(:) == 6;
            figure;  
            imagesc(app.img_disp);axis image off;colormap(gray);
            hold on;...
            scatter(W(id0,4),W(id0,3),36,[1 0 0],'o','filled');
            scatter(W(id1,4),W(id1,3),36,[1 0.5 0],'o','filled');           
            scatter(W(id2,4),W(id2,3),36,[1 1 0],'o','filled');
            scatter(W(id3,4),W(id3,3),36,[0 1 0],'o','filled');                  
            scatter(W(id4,4),W(id4,3),36,[0 1 1],'o','filled');
            scatter(W(id5,4),W(id5,3),36,[0 0 1],'o','filled');          
            scatter(W(id6,4),W(id6,3),36,[0.6 0 1],'o','filled');

            figure;  
            sz = size(app.img_disp);
            imshow(zeros(sz(1),sz(2)));
            hold on;...
            scatter(W(id0,4),W(id0,3),36,[1 0 0],'o','filled');
            scatter(W(id1,4),W(id1,3),36,[1 0.5 0],'o','filled');           
            scatter(W(id2,4),W(id2,3),36,[1 1 0],'o','filled');
            scatter(W(id3,4),W(id3,3),36,[0 1 0],'o','filled');                  
            scatter(W(id4,4),W(id4,3),36,[0 1 1],'o','filled');
            scatter(W(id5,4),W(id5,3),36,[0 0 1],'o','filled');          
            scatter(W(id6,4),W(id6,3),36,[0.6 0 1],'o','filled');            
            
            figure;
            aa = zeros(210,30,3);
            aa(1:30,:,1) = 1;
            aa(1:90,:,1) = 1;
            aa(31:60,:,2) = 0.5;
            aa(61:90,:,2) = 1;
            aa(91:120,:,2) = 1;
            aa(121:150,:,2) = 1;
            aa(121:150,:,3) = 1;
            aa(151:180,:,3) = 1;
            aa(181:210,:,3) = 1;
            aa(181:210,:,1) = 0.6;
            imshow(aa);
        end
        
        function NearNeighborMarker_Mo(app)
            Mo = app.Low_Z_Atom_Pos;
            calibration = app.ser.calibration(1);
            [Idx,~] = rangesearch(Mo(:,3:4),Mo(:,3:4),350/(calibration*10^12));
            num_neighbor = zeros(length(Idx),1);
            
            for ii = 1:length(Idx)
                s = size(Idx{ii});
                num_neighbor(ii) = s(2)-1;         
            end
            
            id0 = num_neighbor(:) == 0;
            id1 = num_neighbor(:) == 1;
            id2 = num_neighbor(:) == 2;
            id3 = num_neighbor(:) == 3;
            id4 = num_neighbor(:) == 4;
            id5 = num_neighbor(:) == 5;
            id6 = num_neighbor(:) == 6;
            figure;
           
            imagesc(app.img_disp);axis image off;colormap(gray);
            hold on;...
            scatter(Mo(id0,4),Mo(id0,3),36,[1 0 0],'o','filled');
            scatter(Mo(id1,4),Mo(id1,3),36,[1 0.5 0],'o','filled');           
            scatter(Mo(id2,4),Mo(id2,3),36,[1 1 0],'o','filled');
            scatter(Mo(id3,4),Mo(id3,3),36,[0 1 0],'o','filled');                  
            scatter(Mo(id4,4),Mo(id4,3),36,[0 1 1],'o','filled');
            scatter(Mo(id5,4),Mo(id5,3),36,[0 0 1],'o','filled');          
            scatter(Mo(id6,4),Mo(id6,3),36,[0.6 0 1],'o','filled');

            figure;  
            sz = size(app.img_disp);
            imshow(zeros(sz(1),sz(2)));
            hold on;...            
            scatter(Mo(id0,4),Mo(id0,3),36,[1 0 0],'o','filled');
            scatter(Mo(id1,4),Mo(id1,3),36,[1 0.5 0],'o','filled');           
            scatter(Mo(id2,4),Mo(id2,3),36,[1 1 0],'o','filled');
            scatter(Mo(id3,4),Mo(id3,3),36,[0 1 0],'o','filled');                  
            scatter(Mo(id4,4),Mo(id4,3),36,[0 1 1],'o','filled');
            scatter(Mo(id5,4),Mo(id5,3),36,[0 0 1],'o','filled');          
            scatter(Mo(id6,4),Mo(id6,3),36,[0.6 0 1],'o','filled');            
            
            figure;
            aa = zeros(210,30,3);
            aa(1:30,:,1) = 1;
            aa(1:90,:,1) = 1;
            aa(31:60,:,2) = 0.5;
            aa(61:90,:,2) = 1;
            aa(91:120,:,2) = 1;
            aa(121:150,:,2) = 1;
            aa(121:150,:,3) = 1;
            aa(151:180,:,3) = 1;
            aa(181:210,:,3) = 1;
            aa(181:210,:,1) = 0.6;
            imshow(aa);
        
        end
        
        
end
        
        
    
    

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

        % Code that executes after component creation
        function startupFcn(app)
            % Configure image axes
            app.ImageAxes.Visible = 'off';
            app.ImageAxes.Colormap = gray(256);
            axis(app.ImageAxes, 'image');
                 
            app.x = app.x;
            app.y = app.y;
            app.L = app.L;
            app.img = app.img;
            % Update the image and histograms
            updateimage(app, 'EASYSTEM logo cap.png');

        end

        % Callback function
        function DropDownValueChanged(app, event)
            
            % Update the image and histograms
            updateimage(app, app.ColormapsDropDown.Value);
        end

        % Callback function
        function LoadButtonPushed(app, event)
               
            % Display uigetfile dialog
            filterspec = {'*.jpg;*.tif;*.png;*.gif','All Image Files'};
            [f, p] = uigetfile(filterspec);
            
            % Make sure user didn't cancel uigetfile dialog
%             if (ischar(p))
%                fname = [p f];
%                updateimage(app, fname);
%             end
            
            im = imread([p f]);
            app.img = ImNorm(im);
            app.Raw = ImNorm(im);
            app.fft_img = log(abs(fftshift(fft2(fftshift(app.img)))));
            plot_ser(app);
            
        end

        % Button pushed function: LoadSERFilesButton
        function LoadSERFilesButtonPushed(app, event)
            try
                serfile = serReader_forapp;
                app.ser = serfile;
                app.img = ImNorm(serfile.image);
                app.Raw = ImNorm(serfile.image);
            
                app.output.Raw = app.Raw;
                app.output.ser = serfile;
                app.fft_img = log(abs(fftshift(fft2(fftshift(app.img)))));
                app.FileLocationTextBox.Value = app.ser.fullFileName;
                app.CalibrationEditField.Value = 10^12 * serfile.calibration(1);
                plot_ser(app);
            catch
                fprintf('no Ser file opened');
            end
        end

        % Button pushed function: LoadImageFileButton
        function LoadImageFileButtonPushed(app, event)
            % Display uigetfile dialog
            filterspec = {'*.jpg;*.tif;*.png;*.gif','All Image Files'};
            [f, p] = uigetfile(filterspec);
            fullFileName = fullfile(p, f);
            [~,name,~] = fileparts(fullFileName);
            app.ser.fullFileName = fullFileName;
            app.ser.name = name;
            % Make sure user didn't cancel uigetfile dialog
%             if (ischar(p))
%                fname = [p f];
%                updateimage(app, fname);
%             end            
           try 
            im = double(imread([p f]));
            app.ser.image = im;
            app.img = ImNorm(im);
            app.Raw = ImNorm(im);
            app.output.Raw = app.Raw;
            app.output.ser = app.ser;
                    imsize = size(app.img);
                    app.lat(1,2) = imsize(2)/2;
                    app.lat(1,1) = imsize(1)/2;            
            app.fft_img = log(abs(fftshift(fft2(fftshift(app.img)))));
            plot_ser(app);
           catch 
               display('no image opened');
           end
            
        end

        % Button pushed function: LoadAtomPositionsButton
        function LoadAtomPositionsButtonPushed(app, event)
            [file, path] = uigetfile('*.mat');     
            if isequal(file,0)
               disp('User selected Cancel');
            else
               disp(['User selected ', fullfile(path,file)]);
               fullFileName = fullfile(path, file);
               if exist(fullFileName, 'file')
                loaded_file = load(fullFileName);

                app.img = loaded_file.atom_pos.image;
                app.Raw = loaded_file.atom_pos.Raw;
                app.ser = loaded_file.atom_pos.ser;
                
                app.output.image = app.img;
                app.output.Raw = app.Raw;   
                app.output.ser = app.ser;                 
                
                try
                    app.FileLocationTextBox.Value = app.ser.fullFileName;
                catch
                    app.FileLocationTextBox.Value = 'location not labelled';
                end
                
                if isempty(loaded_file.atom_pos.pos) == 0
                    app.pos = loaded_file.atom_pos.pos;
                    app.lat = loaded_file.atom_pos.lat;
                    app.latSiteFrac = loaded_file.atom_pos.latSiteFrac;
                    app.output.pos = app.pos;
                    app.output.lat = app.lat;   
                    app.output.latSiteFrac = app.latSiteFrac;                                        
                    fprintf('pos loaded');
                    
%                     if isempty(loaded_file.atom_pos.posRefineM) == 0
%                         app.posRefineM = loaded_file.atom_pos.posRefineM;        
%                         app.output.posRefineM = app.posRefineM; 
%                     end
%                     
%                     if isempty(loaded_file.atom_pos.posRefineMPfit) == 0
%                         app.posRefineMPfit = loaded_file.atom_pos.posRefineMPfit;        
%                         app.output.posRefineMPfit = app.posRefineMPfit; 
%                     end         
                    try
                        app.posRefineM = loaded_file.atom_pos.posRefineM;        
                        app.output.posRefineM = app.posRefineM; 
                    catch
                        fprintf('no refined pos found')
                    end
                    
                    try 
                        app.posRefineMPfit = loaded_file.atom_pos.posRefineMPfit;        
                        app.output.posRefineMPfit = app.posRefineMPfit; 
                    catch
                         fprintf('no mpfit refined pos found')
                    end                         




                end
                

                
                plot_ser(app);
               end           
            end            
        end

        % Callback function
        function SwitchValueChanged(app, event)
            
        end

        % Value changed function: GaussianFilterUnitPixelsSlider
        function GaussianFilterUnitPixelsSliderValueChanged(app, event)
            value = app.GaussianFilterUnitPixelsSlider.Value;
            value = round(value*2)/2;% limited to only 0.5 increment
            app.GaussianFilterUnitPixelsSlider.Value = value;
            app.GaussianFilterUnitPixelsSliderLabel.Text = ['Gaussian Filter with ' num2str(value) ' Pixels'];
            app.img = imgaussfilt(app.Raw,value);
            plot_ser(app);
        end

        % Value changed function: FFTFilterSlider
        function FFTFilterSliderValueChanged(app, event)
            value = app.FFTFilterSlider.Value;
            value = round(value);
            [ifft_img,~,Filtered_Pattern,~] = Fourier_Filter_TEM(app.ser,value/2);
            app.img = ifft_img;            
            app.fft_img = log(Filtered_Pattern);
            app.FFTFilterSlider.Value = value;                    
            app.FFTFilterSliderLabel.Text = ['Filter w/ Resolution: ' num2str(value) ' pm'];
            plot_ser(app);
        end

        % Value changed function: RLDeconvIterationsEditField
        function RLDeconvIterationsEditFieldValueChanged(app, event)
            app.RL_deconv_iter = app.RLDeconvIterationsEditField.Value;
            
        end

        % Value changed function: BlindDeconvIterationsEditField
        function BlindDeconvIterationsEditFieldValueChanged(app, event)
            app.blind_deconv_iter = app.BlindDeconvIterationsEditField.Value;
            
        end

        % Button pushed function: DeconvoluteImageButton
        function DeconvoluteImageButtonPushed(app, event)
            fprintf('blind deconvolution started \n')
        PSF = ones(size(app.img));
            original_image = gpuArray(ImNorm(app.img));
            PSF = gpuArray(PSF);
            tic;
            [~,PSF_F] = deconvblind(original_image,PSF,app.blind_deconv_iter);% 125
            Lucy = deconvlucy(original_image,PSF_F,app.RL_deconv_iter); % 5
            app.img = ImNorm(gather(Lucy));
            toc;
            plot_ser(app);            
        end

        % Value changed function: PositionYSlider
        function PositionYSliderValueChanged(app, event)
            app.y = app.PositionYSlider.Value;
            plot_ser(app);
        end

        % Value changed function: PositionXYSlider
        function PositionXYSliderValueChanged(app, event)
            app.x = app.PositionXYSlider.Value;
            plot_ser(app);
        end

        % Callback function
        function LengthnmSliderValueChanged(app, event)
            app.L = app.LengthnmSlider.Value;
            plot_ser(app);
        end

        % Value changed function: GammaSlider
        function GammaSliderValueChanged(app, event)
            app.gamma = app.GammaSlider.Value;
            plot_ser(app);
        end

        % Value changed function: TextPositionXYSlider
        function TextPositionXYSliderValueChanged(app, event)
            app.off_x  = app.TextPositionXYSlider.Value;
            plot_ser(app); 
        end

        % Value changed function: YSlider
        function YSliderValueChanged(app, event)
            app.off_y = app.YSlider.Value;
            plot_ser(app); 
        end

        % Value changed function: ScaleBarSwitch
        function ScaleBarSwitchValueChanged(app, event)
            app.ON_OFF = app.ScaleBarSwitch.Value;
            plot_ser(app);
        end

        % Value changed function: LengthnmEditField
        function LengthnmEditFieldValueChanged(app, event)
            app.L = app.LengthnmEditField.Value;
            plot_ser(app);            
        end

        % Value changed function: ScaleBarTextCheckBox
        function ScaleBarTextCheckBoxValueChanged(app, event)
            app.Check_Box = app.ScaleBarTextCheckBox.Value;
            plot_ser(app);
        end

        % Value changed function: ShowRawImageCheckBox
        function ShowRawImageCheckBoxValueChanged(app, event)
            app.if_raw = app.ShowRawImageCheckBox.Value;
            plot_ser(app);
        end

        % Value changed function: ColormapsDropDown
        function ColormapsDropDownValueChanged(app, event)
            value = app.ColormapsDropDown.Value;
            % 'Gray', 'Parula', 'Hot', 'Cold', 'Jet', 'Blue White Red'
            switch value
                
                case 'Gray'
                    app.ImageAxes.Colormap = gray(256);
                case 'Parula'
                    app.ImageAxes.Colormap = parula(256);                    
                case 'Hot'
                    app.ImageAxes.Colormap = hot(256);                    
                case 'Cold'
                    app.ImageAxes.Colormap = cold(256);                                        
                case 'Jet'
                    app.ImageAxes.Colormap = jet(256);                                     
                case 'Blue White Red'
                    app.ImageAxes.Colormap = bluewhitered_v2(256);
          
            end
            
        end

        % Value changed function: TxtColorDropDown
        function TxtColorDropDownValueChanged(app, event)
            value = app.TxtColorDropDown.Value;
            
            switch value
                %'White', 'Black', 'Yellow', 'Red', 'Blue', 'Green'
                case 'White'
                    app.ScaleBar_Color = [1 1 1];
                case 'Black'
                    app.ScaleBar_Color = [0 0 0];                    
                case 'Yellow'
                    app.ScaleBar_Color = [1 1 0];                    
                case 'Red'
                    app.ScaleBar_Color = [1 0 0];                                        
                case 'Blue'
                    app.ScaleBar_Color = [0 0 1];                                     
                case 'Green'
                    app.ScaleBar_Color = [0 1 0];
            end         
            plot_ser(app);
        end

        % Callback function
        function FFT_Filter_NumberValueChanged(app, event)
            
        end

        % Value changed function: HighOutSlider
        function HighOutSliderValueChanged(app, event)
            app.out_high = app.HighOutSlider.Value;
            plot_ser(app);
        end

        % Value changed function: LineWidthSlider
        function LineWidthSliderValueChanged(app, event)
            value = app.LineWidthSlider.Value;
            value = round(value*2)/2;
            app.Line_Width = value;
            app.LineWidthSlider.Value = value;
            app.LineWidthSliderLabel.Text = ['Line Width: ' num2str(value)];
            plot_ser(app);
        end

        % Value changed function: FontSizeEditField
        function FontSizeEditFieldValueChanged(app, event)
            app.font_size = app.FontSizeEditField.Value;
            plot_ser(app); 
        end

        % Value changed function: MinDistanceEditField
        function MinDistanceEditFieldValueChanged(app, event)
            app.min_dist = app.MinDistanceEditField.Value;
        end

        % Value changed function: FlatFieldUnevenBrightnessCheckBox
        function FlatFieldUnevenBrightnessCheckBoxValueChanged(app, event)
            app.if_flat = app.FlatFieldUnevenBrightnessCheckBox.Value;            
            plot_ser(app);
        end

        % Value changed function: FlatFieldCorrectionSigmaSlider
        function FlatFieldCorrectionSigmaSliderValueChanged(app, event)
            value = app.FlatFieldCorrectionSigmaSlider.Value;
            value = round(value);
            app.flat_strength = value;
            app.FlatFieldCorrectionSigmaSlider.Value = value;
            app.FlatFieldCorrectionSigmaSliderLabel.Text = ['Flat Field Correction Sigma: ' num2str(value)];            
            plot_ser(app);            
        end

        % Button pushed function: FindInitialPositionsButton
        function FindInitialPositionsButtonPushed(app, event)
            RealSpaceLattice(app);
            plot_ser(app);
        end

        % Value changed function: LowInSlider
        function LowInSliderValueChanged(app, event)
            app.in_low = app.LowInSlider.Value;
            plot_ser(app);
        end

        % Value changed function: HighInSlider
        function HighInSliderValueChanged(app, event)
            app.in_high = app.HighInSlider.Value;
            plot_ser(app);
        end

        % Button pushed function: SaveAtomPositionsButton
        function SaveAtomPositionsButtonPushed(app, event)
            sername = app.ser.name;
            assignin('base','atom_pos',app.output);
            atom_pos = app.output;
            uisave('atom_pos',[sername ' Processed Data']);
        end

        % Value changed function: LowOutSlider
        function LowOutSliderValueChanged(app, event)
            app.out_low = app.LowOutSlider.Value;
            plot_ser(app);
        end

        % Value changed function: ThresholdsigmaEditField
        function ThresholdsigmaEditFieldValueChanged(app, event)
            app.threshold = app.ThresholdsigmaEditField.Value;
        end

        % Button pushed function: RefinePositionsButton
        function RefinePositionsButtonPushed(app, event)
            s = STEMlat01_LM(app.output);
            app.posRefineM = s.posRefineM;
            app.pos = s.pos;
            app.output.posRefineM = app.posRefineM;
            app.output.pos = app.pos;
            plot_ser(app); 
%             hold(app.ImageAxes,'on');
%             scatter(app.ImageAxes,app.posRefineM(:,4),app.posRefineM(:,3),'r.');
%             hold(app.ImageAxes,'off');
        end

        % Value changed function: ShowInitialpositionsCheckBox
        function ShowInitialpositionsCheckBoxValueChanged(app, event)
            app.if_show_initial = app.ShowInitialpositionsCheckBox.Value;
            plot_ser(app);
        end

        % Value changed function: ShowrefinedpositionsCheckBox
        function ShowrefinedpositionsCheckBoxValueChanged(app, event)
            app.if_show_refined = app.ShowrefinedpositionsCheckBox.Value;
            plot_ser(app);
        end

        % Value changed function: InitialSpotsColorDropDown
        function InitialSpotsColorDropDownValueChanged(app, event)
            value = app.InitialSpotsColorDropDown.Value;
            switch value
                %'White', 'Black', 'Yellow', 'Red', 'Blue', 'Green'
                case 'White'
                    app.initial_spot_color = [1 1 1];
                case 'Black'
                    app.initial_spot_color = [0 0 0];                    
                case 'Yellow'
                    app.initial_spot_color = [1 1 0];                    
                case 'Red'
                    app.initial_spot_color = [1 0 0];                                        
                case 'Blue'
                    app.initial_spot_color = [0 0 1];                                     
                case 'Green'
                    app.initial_spot_color = [0 1 0];
            end         
            plot_ser(app);            
        end

        % Value changed function: RefinedSpotsColorDropDown
        function RefinedSpotsColorDropDownValueChanged(app, event)
            value = app.RefinedSpotsColorDropDown.Value;
            switch value
                %'White', 'Black', 'Yellow', 'Red', 'Blue', 'Green'
                case 'White'
                    app.refined_spot_color = [1 1 1];
                case 'Black'
                    app.refined_spot_color = [0 0 0];                    
                case 'Yellow'
                    app.refined_spot_color = [1 1 0];                    
                case 'Red'
                    app.refined_spot_color = [1 0 0];                                        
                case 'Blue'
                    app.refined_spot_color = [0 0 1];                                     
                case 'Green'
                    app.refined_spot_color = [0 1 0];
            end         
            plot_ser(app);              
        end

        % Value changed function: InverseColorImageCheckBox
        function InverseColorImageCheckBoxValueChanged(app, event)
            app.if_inverse = app.InverseColorImageCheckBox.Value;
            plot_ser(app);            
        end

        % Callback function
        function UangleKnobValueChanging(app, event)
            changingValue = event.Value;
            app.lat(2,:) = [app.U_length*cos(changingValue/360*2*pi) app.U_length*sin(changingValue/360*2*pi)];
%             imagesc(app.ImageAxes,app.img_disp);  
            hold(app.ImageAxes,'on');
            qq = quiver(app.ImageAxes,app.lat(1,2),app.lat(1,1),app.lat(2,2)*app.LatNumPlot,app.lat(2,1)*app.LatNumPlot,...
                'LineWidth',4,'Color',[1 0.2 0],'MaxHeadSize',0.3,"AutoScale","off");
            pause(1/15);
            set(qq,'Visible','off');            
            hold(app.ImageAxes,'off');
        end

        % Callback function
        function UangleKnobValueChanged(app, event)
            app.U_angle = app.UangleKnob.Value;
            plot_ser(app);
        end

        % Callback function
        function ULengthSliderValueChanging(app, event)
            changingValue = event.Value;
            app.lat(2,:) = [changingValue*cos(app.U_angle/360*2*pi) changingValue*sin(app.U_angle/360*2*pi)];
            hold(app.ImageAxes,'on');
            qq = quiver(app.ImageAxes,app.lat(1,2),app.lat(1,1),app.lat(2,2)*app.LatNumPlot,app.lat(2,1)*app.LatNumPlot...
                ,'LineWidth',4,'Color',[1 0.2 0],'MaxHeadSize',0.3,'AutoScale',"off");
            pause(1/15);
            set(qq,'Visible','off');
            hold(app.ImageAxes,'off');            
        end

        % Callback function
        function ULengthSliderValueChanged(app, event)
            app.U_length = app.ULengthSlider.Value;
            plot_ser(app);
        end

        % Callback function
        function VangleKnobValueChanging(app, event)
            changingValue = event.Value;
            app.lat(3,:) = [app.V_length*cos(changingValue/360*2*pi) app.V_length*sin(changingValue/360*2*pi)];
%             imagesc(app.ImageAxes,app.img_disp);  
            hold(app.ImageAxes,'on');
            qq = quiver(app.ImageAxes,app.lat(1,2),app.lat(1,1),app.lat(3,2)*app.LatNumPlot,app.lat(3,1)*app.LatNumPlot...
                ,'LineWidth',4,'Color',[0 0.2 1],'MaxHeadSize',0.3,'AutoScale',"off");
            pause(1/15);
            set(qq,'Visible','off');            
            hold(app.ImageAxes,'off');
        end

        % Callback function
        function VangleKnobValueChanged(app, event)
            app.V_angle = app.VangleKnob.Value;
            plot_ser(app);            
        end

        % Callback function
        function VLengthSliderValueChanging(app, event)
            changingValue = event.Value;
            app.lat(3,:) = [changingValue*cos(app.V_angle/360*2*pi) changingValue*sin(app.V_angle/360*2*pi)];
            hold(app.ImageAxes,'on');
            qq = quiver(app.ImageAxes,app.lat(1,2),app.lat(1,1),app.lat(3,2)*app.LatNumPlot,app.lat(3,1)*app.LatNumPlot...
                ,'LineWidth',4,'Color',[0 0.2 1],'MaxHeadSize',0.3,'AutoScale',"off");
            pause(1/15);
            set(qq,'Visible','off');
            hold(app.ImageAxes,'off');                 
        end

        % Value changed function: OriginXEditField
        function OriginXEditFieldValueChanged(app, event)
            app.origin_x = app.OriginXEditField.Value;
            app.lat(1,2) = app.origin_x;
            plot_ser(app);
        end

        % Callback function
        function VLengthSliderValueChanged(app, event)
            app.V_length = app.VLengthSlider.Value;
            plot_ser(app);
        end

        % Value changed function: OriginYEditField
        function OriginYEditFieldValueChanged(app, event)
            app.origin_y = app.OriginYEditField.Value;
            app.lat(1,1) = app.origin_y;
            plot_ser(app);
        end

        % Button pushed function: FindUButton
        function FindUButtonPushed(app, event)
            imshow(app.img_disp);
            hold on;
            scatter(app.pos(:,2),app.pos(:,1),'.','MarkerEdgeColor',app.initial_spot_color);                        
            assignin('base','lat',app.lat);
            assignin('base','LatNumPlot',app.LatNumPlot);
            assignin('base','atom_pos',app.output);
            app.U_end_x = app.lat(1,2) + app.lat(2,2)*app.LatNumPlot;
            app.U_end_y = app.lat(1,1) + app.lat(2,1)*app.LatNumPlot;
            q1 = quiver(app.lat(1,2),app.lat(1,1),app.lat(2,2)*app.LatNumPlot,app.lat(2,1)*app.LatNumPlot,'LineWidth',4,'Color',[1 0.2 0],'MaxHeadSize',0.3,'AutoScale',"off");
            q2 = quiver(app.lat(1,2),app.lat(1,1),app.lat(3,2)*app.LatNumPlot,app.lat(3,1)*app.LatNumPlot,'LineWidth',4,'Color',[0 0.2 1],'MaxHeadSize',0.3,'AutoScale',"off");                    
            roi_u = drawpoint('Position',[app.U_end_x app.U_end_y]);    
            roi_u.Label = 'Drag Me!';
            roi_u.Color = [0 1 0];
            roi_u.LabelVisible = 'hover';	
            roi_u.LineWidth = 5;            
            addlistener(roi_u,'ROIMoved',@Point_moving_u);              
            
            
                remove_extra_pts = 1;
                while remove_extra_pts > 0  
                    pause(0.5)
                      try
                        app.lat = evalin('base','lat');                          
                        PosPOC=round(get(roi_u,'Position'));    %Extract Coordinates of the point ROI
                        app.UendXEditField.Value = app.lat(1,2) + app.lat(2,2)*app.LatNumPlot;
                        app.UendYEditField.Value = app.lat(1,1) + app.lat(2,1)*app.LatNumPlot;
%                         fprintf(num2str(app.lat(2,1)));
%                         fprintf('\n');
%                         fprintf(num2str(app.lat(2,2)));
%                         fprintf('\n');      
                      catch
                        fprintf('find u completed \n');
                        remove_extra_pts = 0;
                      end
    
                end
            plot_ser(app);
        end

        % Value changed function: LatNumPlotEditField
        function LatNumPlotEditFieldValueChanged(app, event)
            app.LatNumPlot = app.LatNumPlotEditField.Value;
        end

        % Value changed function: LatFracUEditField
        function LatFracUEditFieldValueChanged(app, event)
            app.latSiteFrac(1) = app.LatFracUEditField.Value;            
        end

        % Value changed function: LatFracVEditField
        function LatFracVEditFieldValueChanged(app, event)
            app.latSiteFrac(2) = app.LatFracVEditField.Value;            
        end

        % Button pushed function: CalculateLatticeButton
        function CalculateLatticeButtonPushed(app, event)
            Lattice_finder(app)
            plot_ser(app);
        end

        % Value changed function: ShowLatticepositionsCheckBox
        function ShowLatticepositionsCheckBoxValueChanged(app, event)
            app.if_show_lat = app.ShowLatticepositionsCheckBox.Value;
            plot_ser(app);
        end

        % Button pushed function: MpfitOverlapsButton
        function MpfitOverlapsButtonPushed(app, event)
            s = MPFit(app.output);
            app.posRefineMPfit = s.posRefine;
            app.pos = s.pos;
            app.output.posRefineMPfit = app.posRefineMPfit;
            app.output.pos = app.pos;
            app.if_mpfit_exist = 1;
            plot_ser(app);           
        end

        % Value changed function: MPfitpositionsCheckBox
        function MPfitpositionsCheckBoxValueChanged(app, event)
            app.if_show_ref_lat = app.ShowLatticepositionsCheckBox.Value;
            plot_ser(app);
        end

        % Value changed function: CrossColorDropDown
        function CrossColorDropDownValueChanged(app, event)
            value = app.CrossColorDropDown.Value;
            switch value
                %'White', 'Black', 'Yellow', 'Red', 'Blue', 'Green'
                case 'White'
                    app.lat_cross_color = [1 1 1];
                case 'Black'
                    app.lat_cross_color = [0 0 0];                    
                case 'Yellow'
                    app.lat_cross_color = [1 1 0];                    
                case 'Red'
                    app.lat_cross_color = [1 0 0];                                        
                case 'Blue'
                    app.lat_cross_color = [0 0 1];                                     
                case 'Green'
                    app.lat_cross_color = [0 1 0];
            end        
            plot_ser(app);
        end

        % Value changed function: RefinedCrossColorDropDown
        function RefinedCrossColorDropDownValueChanged(app, event)
            value = app.RefinedCrossColorDropDown.Value;
            switch value
                %'White', 'Black', 'Yellow', 'Red', 'Blue', 'Green'
                case 'White'
                    app.ref_lat_cross_color = [1 1 1];
                case 'Black'
                    app.ref_lat_cross_color = [0 0 0];                    
                case 'Yellow'
                    app.ref_lat_cross_color = [1 1 0];                    
                case 'Red'
                    app.ref_lat_cross_color = [1 0 0];                                        
                case 'Blue'
                    app.ref_lat_cross_color = [0 0 1];                                     
                case 'Green'
                    app.ref_lat_cross_color = [0 1 0];
            end        
            plot_ser(app);            
        end

        % Button pushed function: 
        % CalculateBondLengthBasedonNearNeighborButton
        function CalculateBondLengthBasedonNearNeighborButtonPushed(app, event)
            NearNeighbor_Distance(app);
            app.if_bond_exist = 1;            
            plot_ser(app);
        end

        % Value changed function: IfShowBondLengthMapCheckBox
        function IfShowBondLengthMapCheckBoxValueChanged(app, event)
            app.if_show_bond = app.IfShowBondLengthMapCheckBox.Value;
            plot_ser(app);
        end

        % Button pushed function: 
        % CalculateBondLengthBasedonLatticeButton
        function CalculateBondLengthBasedonLatticeButtonPushed(app, event)
            Lattice_Neighbor_Distance(app);
            app.if_bond_exist = 1;
            app.ShowInitialpositionsCheckBox.Value = 0;
            app.ShowLatticepositionsCheckBox.Value = 0;
            app.ShowrefinedpositionsCheckBox.Value = 0;
            plot_ser(app);            
        end

        % Callback function
        function AddMissingPointsCheckBoxValueChanged(app, event)

            app.if_add_missing_pts = app.AddMissingPointsCheckBox.Value;       
            if app.if_add_missing_pts == 1
                figure('CloseRequestFcn',@my_closereq);
                imagesc(app.img_disp);axis image off;colormap(gray(256));...
                while app.if_add_missing_pts > 0  
%                     imagesc(app.img_disp);axis image off;colormap(gray(256));...
                    hold on;...
                    scatter(app.pos(:,2),app.pos(:,1),'.','MarkerEdgeColor',app.initial_spot_color);...
                    hold off;
                    roiPOC = drawpoint;    %Use Mouse To Select a point ROI
                      try
                        PosPOC=round(get(roiPOC,'Position'));    %Extract Coordinates of the point ROI
                        delete(roiPOC);
                      catch
                        fprintf('missing point function completed \n');
                        app.if_add_missing_pts = 0;
                        app.AddMissingPointsCheckBox.Value = 0;
                      end
%                     if isempty(roiPOC) == 0
%                     PosPOC=round(get(roiPOC,'Position'));    %Extract Coordinates of the point ROI
%                     delete(roiPOC);
%                     end
                    add_pos = [PosPOC(2) PosPOC(1) 0 0 0 0];
                    app.pos = [app.pos;add_pos];
                    app.output.pos = app.pos;     
                end
            else
                plot_ser(app);
            end    
            plot_ser(app);
        end

        % Value changed function: LineStyleDropDown
        function LineStyleDropDownValueChanged(app, event)

                value = app.LineStyleDropDown.Value;
                % 'Gray', 'Parula', 'Hot', 'Cold', 'Jet', 'Blue White Red'
                switch value
                    
                    case 'Straight Line'
                        app.bondlength_style = '-';
                    case 'Dashed Line'
                        app.bondlength_style = '--';                
                    case 'Dotted Line'
                        app.bondlength_style = ':';                 
                    case 'Dot Dash Dot Dash'
                        app.bondlength_style = '-.';                                        
              
                end 
                plot_ser(app);
        end

        % Button pushed function: AddMissingPointsButton
        function AddMissingPointsButtonPushed(app, event)
                figure('CloseRequestFcn',@my_closereq);
                imagesc(app.img_disp);axis image off;colormap(gray(256));...
                add_missing_pts = 1;
                while add_missing_pts > 0  
                    hold on;...
                    scatter(app.pos(:,2),app.pos(:,1),'.','MarkerEdgeColor',app.initial_spot_color);...
                    hold off;
                    roiPOC = drawpoint;    %Use Mouse To Select a point ROI
                      try
                        PosPOC=round(get(roiPOC,'Position'));    %Extract Coordinates of the point ROI
                        delete(roiPOC);
                      catch
                        fprintf('missing point function completed \n');
                        add_missing_pts = 0;
                      end
                    add_pos = [PosPOC(2) PosPOC(1) 0 0 0 0];
                    app.pos = [app.pos;add_pos];
                    app.output.pos = app.pos;     
                end
                plot_ser(app);
        end

        % Button pushed function: DefineAreaofInterestButton
        function DefineAreaofInterestButtonPushed(app, event)
                imagesc(app.img_disp);axis image off;colormap(gray(256));...
                hold on;...
                scatter(app.pos(:,2),app.pos(:,1),'.','MarkerEdgeColor',app.initial_spot_color);...
                hold off;
                RoiRectangular = drawpolygon;    %Use Mouse To Select a polygon ROI
                try
                corners = get(RoiRectangular,'Position');
                xv = corners(:,1);yv = corners(:,2);
                xq = app.pos(:,2);yq = app.pos(:,1);
                [in,on] = inpolygon(xq,yq,xv,yv);
%                 delete(gcf)
                app.pos = [app.pos(in,:);app.pos(on,:)];
                catch
                    fprintf('no ROI seleted \n');
                end
                
                imagesc(app.img_disp);axis image off;colormap(gray(256));...
                hold on;...
                scatter(app.pos(:,2),app.pos(:,1),'.','MarkerEdgeColor',app.initial_spot_color);...
                hold off;           
                plot_ser(app);
        end

        % Value changed function: UendXEditField
        function UendXEditFieldValueChanged(app, event)
            app.U_end_x = app.UendXEditField.Value;
            app.lat(2,2) = (app.U_end_x - app.origin_x)/app.LatNumPlot;
            plot_ser(app);
        end

        % Value changed function: UendYEditField
        function UendYEditFieldValueChanged(app, event)
            app.U_end_y = app.UendYEditField.Value;
            app.lat(2,1) = (app.U_end_y - app.origin_y)/app.LatNumPlot;
            plot_ser(app);            
        end

        % Value changed function: VendXEditField
        function VendXEditFieldValueChanged(app, event)
            app.V_end_x = app.VendXEditField.Value;
            app.lat(3,2) = (app.V_end_x - app.origin_x)/app.LatNumPlot;
            plot_ser(app);
        end

        % Value changed function: VendYEditField
        function VendYEditFieldValueChanged(app, event)
            app.V_end_y = app.VendYEditField.Value;
            app.lat(3,1) = (app.V_end_y - app.origin_y)/app.LatNumPlot;
            plot_ser(app);
        end

        % Value changed function: BondLengthColormapsDropDown
        function BondLengthColormapsDropDownValueChanged(app, event)
            value = app.BondLengthColormapsDropDown.Value;
            app.InvertBondColorCheckBox.Value = 0;
            % 'Gray', 'Parula', 'Hot', 'Cold', 'Jet', 'Blue White Red'
            switch value
                
                case 'Gray'
                    app.newmap = gray(256);
                case 'Parula'
                    app.newmap = parula(256);                    
                case 'Hot'
                    app.newmap = hot(256);                    
                case 'Cold'
                    app.newmap = cold(256);                                        
                case 'Jet'
                    app.newmap = jet(256);                                     
                case 'Blue White Red'
                    app.newmap = bluewhitered_v3(256);
                case 'All White'
                    app.newmap = ones(256,3);
                    
            end
            Lattice_Neighbor_Distance(app);
            app.if_bond_exist = 1;            
            plot_ser(app);          
            
        end

        % Value changed function: InvertBondColorCheckBox
        function InvertBondColorCheckBoxValueChanged(app, event)
         value = app.InvertBondColorCheckBox.Value;
            if value == 1
                app.newmap = flipud(app.newmap);                         
            else
                BL_Color = app.BondLengthColormapsDropDown.Value;
                % 'Gray', 'Parula', 'Hot', 'Cold', 'Jet', 'Blue White Red'
                switch BL_Color
                    
                    case 'Gray'
                        app.newmap = gray(256);
                    case 'Parula'
                        app.newmap = parula(256);                    
                    case 'Hot'
                        app.newmap = hot(256);                    
                    case 'Cold'
                        app.newmap = cold(256);                                        
                    case 'Jet'
                        app.newmap = jet(256);                                     
                    case 'Blue White Red'
                        app.newmap = bluewhitered_v3(256);
              
                end                        
            end
            Lattice_Neighbor_Distance(app);
            plot_ser(app); 
        end

        % Value changed function: MeanDistanceEditField
        function MeanDistanceEditFieldValueChanged(app, event)
            app.mean_disp = app.MeanDistanceEditField.Value;
%             Lattice_Neighbor_Distance(app);
            plot_ser(app);
        end

        % Value changed function: MeasurementRangeEditField
        function MeasurementRangeEditFieldValueChanged(app, event)
            app.measure_range = app.MeasurementRangeEditField.Value;
%             Lattice_Neighbor_Distance(app);
            plot_ser(app);            
        end

        % Button pushed function: resetButton
        function resetButtonPushed(app, event)
            app.img = app.Raw;
            plot_ser(app);
        end

        % Button pushed function: GenerateBondLengthHistogramButton
        function GenerateBondLengthHistogramButtonPushed(app, event)
            dx = (app.xx(:,1) - app.xx(:,2));
            dy = (app.yy(:,1) - app.yy(:,2));
            d = sqrt(dx.^2 + dy.^2)*app.ser.calibration(1)*(10^12);
            histogram(d,150);
        end

        % Button pushed function: RemoveExtraPointsButton
        function RemoveExtraPointsButtonPushed(app, event)

                imagesc(app.img_disp);axis image off;colormap(gray(256));...
                remove_extra_pts = 1;
                while remove_extra_pts > 0  
                    hold on;...
                    scatter(app.pos(:,2),app.pos(:,1),'.','MarkerEdgeColor',app.initial_spot_color);...
                    hold off;
                    roiPOC = drawpoint;    %Use Mouse To Select a point ROI
                      try
                        PosPOC=round(get(roiPOC,'Position'));    %Extract Coordinates of the point ROI
                        cursor_point = [PosPOC(2) PosPOC(1)];  %Extract Coordinates of the point ROI
                        delete(roiPOC);                        
                        Idx = knnsearch(app.pos(:,1:2),cursor_point);
                        app.pos(Idx,:)=[];
                        app.output.pos = app.pos; 
                        imagesc(app.img_disp);axis image off;colormap(gray(256));
                        hold on;...
                        scatter(app.pos(:,2),app.pos(:,1),'.','MarkerEdgeColor',app.initial_spot_color);...
                        hold off;                        
                      catch
                        fprintf('removing point function completed \n');
                        remove_extra_pts = 0;
                      end
    
                end
                plot_ser(app);
        end

        % Button pushed function: FindOriginButton
        function FindOriginButtonPushed(app, event)
                    imshow(app.img_disp);
                    hold on;
                    scatter(app.pos(:,2),app.pos(:,1),'.','MarkerEdgeColor',app.initial_spot_color);                        
                    assignin('base','lat',app.lat);
                    assignin('base','LatNumPlot',app.LatNumPlot);              
                    assignin('base','atom_pos',app.output);
                    
                    roi_origin = drawpoint('Position',[app.lat(1,2) app.lat(1,1)]);  
                    roi_origin.Label = 'Drag Me!';
                    roi_origin.Color = [0 1 0];
                    roi_origin.LabelVisible = 'hover';	
                    roi_origin.LineWidth = 5;
                    addlistener(roi_origin,'ROIMoved',@Point_moving_origin); 

                remove_extra_pts = 1;
                while remove_extra_pts > 0  
%                     fprintf('while looping')
                    pause(0.5)
                      try
                        app.lat = evalin('base','lat');                          
                        PosPOC=round(get(roi_origin,'Position'));    %Extract Coordinates of the point ROI
                        app.OriginXEditField.Value = app.lat(1,2);
                        app.OriginYEditField.Value = app.lat(1,1); 
%                         fprintf(num2str(app.lat(1,1)));
%                         fprintf('\n');
%                         fprintf(num2str(app.lat(1,2)));
%                         fprintf('\n');                            
                      catch
                        fprintf('find origin completed');
                        remove_extra_pts = 0;
                      end
    
                end
                plot_ser(app);                    

        end

        % Value changed function: LineWidthSlider_2
        function LineWidthSlider_2ValueChanged(app, event)
            app.bondlength_width = app.LineWidthSlider_2.Value;
            plot_ser(app);
        end

        % Value changed function: SeparateAtomsCheckBox
        function SeparateAtomsCheckBoxValueChanged(app, event)
            app.if_show_separate = app.SeparateAtomsCheckBox.Value;
            plot_ser(app);
        end

        % Button pushed function: SeparateAtomSpeciesButton
        function SeparateAtomSpeciesButtonPushed(app, event)
            Atom_Filter(app);
            plot_ser(app);
        end

        % Value changed function: ThresholdSlider
        function ThresholdSliderValueChanged(app, event)
            app.Sepa_Threshold = app.ThresholdSlider.Value;
            Atom_Filter(app);
            plot_ser(app);            
        end

        % Button pushed function: PairDistributionFunctionButton
        function PairDistributionFunctionButtonPushed(app, event)
            hist_calibration = app.ser.calibration(1)*(10^9);        
            [~,Distance_LH]= knnsearch(app.High_Z_Atom_Pos(:,3:4),app.Low_Z_Atom_Pos(:,3:4),'K',app.Num_neighbor_PDF,'Distance','euclidean');
            [~,Distance_LL]= knnsearch(app.Low_Z_Atom_Pos(:,3:4),app.Low_Z_Atom_Pos(:,3:4),'K',app.Num_neighbor_PDF,'Distance','euclidean');
            [~,Distance_HH]= knnsearch(app.High_Z_Atom_Pos(:,3:4),app.High_Z_Atom_Pos(:,3:4),'K',app.Num_neighbor_PDF,'Distance','euclidean');
            
            Distance_HH = Distance_HH*hist_calibration;% in nm            
            Distance_LL = Distance_LL*hist_calibration;% in nm            
            Distance_LH = Distance_LH*hist_calibration;% in nm        
      
            xbins = 0:0.01:10;
            B = reshape(Distance_LH(:,2:end),[1 (length(Distance_LH)*length(2:app.Num_neighbor_PDF))]);            
            [counts1,centers] = hist(B,xbins);
            counts1 = counts1./max(counts1(:));
            figure;
            bar(centers,counts1);xlabel('Distance (nm)','Interpreter','latex');ylabel('Probability');title('Pair Distribution: Mo to W Distance');
            xlim([0 app.PDF_xaxis_lim]);xticks([0:(app.PDF_xaxis_lim/10):app.PDF_xaxis_lim]);
            ylim([0 1]);
            
            xbins = 0:0.01:10;
            B = reshape(Distance_LL(:,2:end),[1 (length(Distance_LL)*length(2:app.Num_neighbor_PDF))]);            
            [counts2,centers] = hist(B,xbins);
            counts2 = counts2./max(counts2(:));
            figure;
            bar(centers,counts2);xlabel('Distance (nm)','Interpreter','latex');ylabel('Probability');title('Pair Distribution: Mo to Mo Distance');
            xlim([0 app.PDF_xaxis_lim]);xticks([0:(app.PDF_xaxis_lim/10):app.PDF_xaxis_lim]);
            ylim([0 1]);
            
            xbins = 0:0.01:10;
            B = reshape(Distance_HH(:,2:end),[1 (length(Distance_HH)*length(2:app.Num_neighbor_PDF))]);            
            [counts3,centers] = hist(B,xbins);
            counts3 = counts3./max(counts3(:));
            figure;
            bar(centers,counts3);xlabel('Distance (nm)','Interpreter','latex');ylabel('Probability');title('Pair Distribution: W to W Distance');
            xlim([0 app.PDF_xaxis_lim]);xticks([0:(app.PDF_xaxis_lim/10):app.PDF_xaxis_lim]);
            ylim([0 1]);      
        end

        % Button pushed function: PlotNNDistributionButton
        function PlotNNDistributionButtonPushed(app, event)
            hist_calibration = app.ser.calibration(1)*(10^9);
            [~,Distance_LH]= knnsearch(app.High_Z_Atom_Pos(:,3:4),app.Low_Z_Atom_Pos(:,3:4),'K',app.Num_neighbor_NN,'Distance','euclidean');
            [~,Distance_LL]= knnsearch(app.Low_Z_Atom_Pos(:,3:4),app.Low_Z_Atom_Pos(:,3:4),'K',app.Num_neighbor_NN,'Distance','euclidean');
            [~,Distance_HH]= knnsearch(app.High_Z_Atom_Pos(:,3:4),app.High_Z_Atom_Pos(:,3:4),'K',app.Num_neighbor_NN,'Distance','euclidean');
            
            Distance_HH = Distance_HH*hist_calibration;% in nm            
            Distance_LL = Distance_LL*hist_calibration;% in nm            
            Distance_LH = Distance_LH*hist_calibration;% in nm        
            
            xbins = 0:0.2:4;
            [counts,centers] = hist(Distance_LH(:,2:app.Num_neighbor_NN),xbins);
            figure;
            bar(centers,counts);xlabel('Distance (nm)');ylabel('Counts');legend('1st Nearest','2nd Nearest','3rd Nearest');title('Mo to W Distance')
            xticks(centers);xlim([0 app.NN_xaxis_lim]);
            
            xbins = 0:0.2:4;
            [counts,centers] = hist(Distance_LL(:,2:app.Num_neighbor_NN),xbins);
            figure;
            bar(centers,counts);xlabel('Distance (nm)');ylabel('Counts');legend('1st Nearest','2nd Nearest','3rd Nearest');title('Mo to Mo Distance')
            xticks(centers);      xlim([0 app.NN_xaxis_lim]);                 

            xbins = 0:0.2:4;
            [counts,centers] = hist(Distance_HH(:,2:app.Num_neighbor_NN),xbins);
            figure;
            bar(centers,counts);xlabel('Distance (nm)');ylabel('Counts');legend('1st Nearest','2nd Nearest','3rd Nearest');title('W to W Distance')
            xticks(centers);  xlim([0 app.NN_xaxis_lim]);     
        end

        % Value changed function: XAxisLimitEditField_NN
        function XAxisLimitEditField_NNValueChanged(app, event)
            app.NN_xaxis_lim = app.XAxisLimitEditField_NN.Value;            
        end

        % Value changed function: XAxisLimitEditField_PDF
        function XAxisLimitEditField_PDFValueChanged(app, event)
            app.PDF_xaxis_lim = app.XAxisLimitEditField_PDF.Value;        
        end

        % Value changed function: NeighborsEditField_NN
        function NeighborsEditField_NNValueChanged(app, event)
            app.Num_neighbor_NN = app.NeighborsEditField_NN.Value;
            
        end

        % Value changed function: NeighborsEditField_PDF
        function NeighborsEditField_PDFValueChanged(app, event)
            app.Num_neighbor_PDF = app.NeighborsEditField_PDF.Value;
            
        end

        % Button pushed function: Find_Trios
        function Find_TriosButtonPushed(app, event)
            Trio_Finder(app);
            
        end

        % Button pushed function: Find_Triangles
        function Find_TrianglesButtonPushed(app, event)
            Triangle_Finder(app);
        end

        % Button pushed function: FindVButton
        function FindVButtonPushed(app, event)
            imshow(app.img_disp);
            hold on;
            scatter(app.pos(:,2),app.pos(:,1),'.','MarkerEdgeColor',app.initial_spot_color);                        
            assignin('base','lat',app.lat);
            assignin('base','LatNumPlot',app.LatNumPlot);
            assignin('base','atom_pos',app.output);
            app.V_end_x = app.lat(1,2) + app.lat(3,2)*app.LatNumPlot;
            app.V_end_y = app.lat(1,1) + app.lat(3,1)*app.LatNumPlot;
            q1 = quiver(app.lat(1,2),app.lat(1,1),app.lat(2,2)*app.LatNumPlot,app.lat(2,1)*app.LatNumPlot,'LineWidth',4,'Color',[1 0.2 0],'MaxHeadSize',0.3,'AutoScale',"off");
            q2 = quiver(app.lat(1,2),app.lat(1,1),app.lat(3,2)*app.LatNumPlot,app.lat(3,1)*app.LatNumPlot,'LineWidth',4,'Color',[0 0.2 1],'MaxHeadSize',0.3,'AutoScale',"off");                    
            roi_v = drawpoint('Position',[app.V_end_x app.V_end_y]);    
            roi_v.Label = 'Drag Me!';
            roi_v.Color = [0 1 0];
            roi_v.LabelVisible = 'hover';	
            roi_v.LineWidth = 5;            
            addlistener(roi_v,'ROIMoved',@Point_moving_v);              
            
            
                remove_extra_pts = 1;
                while remove_extra_pts > 0  
                    pause(0.5)
                      try
                        app.lat = evalin('base','lat');                          
                        PosPOC=round(get(roi_v,'Position'));    %Extract Coordinates of the point ROI
                        app.VendXEditField.Value = app.lat(1,2) + app.lat(3,2)*app.LatNumPlot;
                        app.VendYEditField.Value = app.lat(1,1) + app.lat(3,1)*app.LatNumPlot;
%                         fprintf(num2str(app.lat(2,1)));
%                         fprintf('\n');
%                         fprintf(num2str(app.lat(2,2)));
%                         fprintf('\n');      
                      catch
                        fprintf('find u completed');
                        remove_extra_pts = 0;
                      end
    
                end
            plot_ser(app);            
        end

        % Button pushed function: FindNumNeighbors_W
        function FindNumNeighbors_WButtonPushed(app, event)
            NearNeighborMarker(app);
        end

        % Button pushed function: FindNumNeighbors_Mo
        function FindNumNeighbors_MoButtonPushed(app, event)
            NearNeighborMarker_Mo(app);
        end

        % Value changed function: CalibrationEditField
        function CalibrationEditFieldValueChanged(app, event)
            value = app.CalibrationEditField.Value;
            app.ser.calibration = value*10^-12;
            app.output.ser.calibration = app.ser.calibration;
        end

        % Button pushed function: Find_Monos
        function Find_MonosButtonPushed(app, event)
            Mono_Finder(app);
        end

        % Button pushed function: RotateBy90Button
        function RotateBy90ButtonPushed(app, event)
            app.img_disp = rot90(app.img_disp);
            app.img = rot90(app.img);
            plot_ser(app);
        end

        % Button pushed function: 
        % CalculateStrainbasedonatomicpositionsButton
        function CalculateStrainbasedonatomicpositionsButtonPushed(app, event)
            app.output = RealSpaceStrain(app.output,app.Strain_lim);
        end

        % Value changed function: StrainUpperLowerLimitEditField
        function StrainUpperLowerLimitEditFieldValueChanged(app, event)
            app.Strain_lim = app.StrainUpperLowerLimitEditField.Value;                     
        end
    end

    % Component initialization
    methods (Access = private)

        % Create UIFigure and components
        function createComponents(app)

            % Create UIFigure and hide until all components are created
            app.UIFigure = uifigure('Visible', 'off');
            app.UIFigure.AutoResizeChildren = 'off';
            app.UIFigure.Position = [100 100 1198 646];
            app.UIFigure.Name = 'EASY-STEM Main Window';
            app.UIFigure.Resize = 'off';

            % Create ImageAxes
            app.ImageAxes = uiaxes(app.UIFigure);
            app.ImageAxes.XTick = [];
            app.ImageAxes.XTickLabel = {'[ ]'};
            app.ImageAxes.YTick = [];
            app.ImageAxes.Position = [187 0 648 647];

            % Create LoadSERFilesButton
            app.LoadSERFilesButton = uibutton(app.UIFigure, 'push');
            app.LoadSERFilesButton.ButtonPushedFcn = createCallbackFcn(app, @LoadSERFilesButtonPushed, true);
            app.LoadSERFilesButton.BackgroundColor = [0 0 1];
            app.LoadSERFilesButton.FontName = 'Georgia';
            app.LoadSERFilesButton.FontWeight = 'bold';
            app.LoadSERFilesButton.FontAngle = 'italic';
            app.LoadSERFilesButton.FontColor = [1 1 1];
            app.LoadSERFilesButton.Position = [8 603 177 36];
            app.LoadSERFilesButton.Text = 'Load SER Files';

            % Create ShowRawImageCheckBox
            app.ShowRawImageCheckBox = uicheckbox(app.UIFigure);
            app.ShowRawImageCheckBox.ValueChangedFcn = createCallbackFcn(app, @ShowRawImageCheckBoxValueChanged, true);
            app.ShowRawImageCheckBox.Text = 'Show Raw Image';
            app.ShowRawImageCheckBox.Position = [12 462 116 22];

            % Create ColormapsDropDownLabel
            app.ColormapsDropDownLabel = uilabel(app.UIFigure);
            app.ColormapsDropDownLabel.HorizontalAlignment = 'center';
            app.ColormapsDropDownLabel.Position = [10 395 75 22];
            app.ColormapsDropDownLabel.Text = 'Colormaps';

            % Create ColormapsDropDown
            app.ColormapsDropDown = uidropdown(app.UIFigure);
            app.ColormapsDropDown.Items = {'Gray', 'Parula', 'Hot', 'Cold', 'Jet', 'Blue White Red'};
            app.ColormapsDropDown.ValueChangedFcn = createCallbackFcn(app, @ColormapsDropDownValueChanged, true);
            app.ColormapsDropDown.Position = [92 395 92 22];
            app.ColormapsDropDown.Value = 'Gray';

            % Create Filters
            app.Filters = uitabgroup(app.UIFigure);
            app.Filters.AutoResizeChildren = 'off';
            app.Filters.Position = [1 1 191 227];

            % Create GaussianTab
            app.GaussianTab = uitab(app.Filters);
            app.GaussianTab.AutoResizeChildren = 'off';
            app.GaussianTab.Title = 'Gaussian';

            % Create GaussianFilterUnitPixelsSliderLabel
            app.GaussianFilterUnitPixelsSliderLabel = uilabel(app.GaussianTab);
            app.GaussianFilterUnitPixelsSliderLabel.HorizontalAlignment = 'center';
            app.GaussianFilterUnitPixelsSliderLabel.Position = [9 121 168 22];
            app.GaussianFilterUnitPixelsSliderLabel.Text = 'Gaussian Filter (Unit: Pixels)';

            % Create GaussianFilterUnitPixelsSlider
            app.GaussianFilterUnitPixelsSlider = uislider(app.GaussianTab);
            app.GaussianFilterUnitPixelsSlider.Limits = [0.5 6];
            app.GaussianFilterUnitPixelsSlider.MajorTicks = [0.5 1.5 2.5 3.5 4.5 5.5];
            app.GaussianFilterUnitPixelsSlider.ValueChangedFcn = createCallbackFcn(app, @GaussianFilterUnitPixelsSliderValueChanged, true);
            app.GaussianFilterUnitPixelsSlider.Position = [11 175 166 3];
            app.GaussianFilterUnitPixelsSlider.Value = 1;

            % Create FFTTab
            app.FFTTab = uitab(app.Filters);
            app.FFTTab.AutoResizeChildren = 'off';
            app.FFTTab.Title = 'FFT';

            % Create FFTAxes
            app.FFTAxes = uiaxes(app.FFTTab);
            title(app.FFTAxes, '')
            xlabel(app.FFTAxes, '')
            ylabel(app.FFTAxes, '')
            app.FFTAxes.PlotBoxAspectRatio = [1 1 1];
            app.FFTAxes.XLim = [512 1536];
            app.FFTAxes.YLim = [512 1536];
            app.FFTAxes.BoxStyle = 'full';
            app.FFTAxes.XTick = [];
            app.FFTAxes.YTick = [];
            app.FFTAxes.Position = [15 -18 152 147];

            % Create FFTFilterSliderLabel
            app.FFTFilterSliderLabel = uilabel(app.FFTTab);
            app.FFTFilterSliderLabel.HorizontalAlignment = 'center';
            app.FFTFilterSliderLabel.Position = [10 130 166 22];
            app.FFTFilterSliderLabel.Text = 'FFT Filter';

            % Create FFTFilterSlider
            app.FFTFilterSlider = uislider(app.FFTTab);
            app.FFTFilterSlider.Limits = [10 135];
            app.FFTFilterSlider.MajorTicks = [10 35 60 85 110 135];
            app.FFTFilterSlider.ValueChangedFcn = createCallbackFcn(app, @FFTFilterSliderValueChanged, true);
            app.FFTFilterSlider.Position = [10 182 166 3];
            app.FFTFilterSlider.Value = 60;

            % Create DeconvolutionTab
            app.DeconvolutionTab = uitab(app.Filters);
            app.DeconvolutionTab.Title = 'Deconvolution';

            % Create BlindDeconvIterationsEditFieldLabel
            app.BlindDeconvIterationsEditFieldLabel = uilabel(app.DeconvolutionTab);
            app.BlindDeconvIterationsEditFieldLabel.HorizontalAlignment = 'right';
            app.BlindDeconvIterationsEditFieldLabel.Position = [3 155 129 22];
            app.BlindDeconvIterationsEditFieldLabel.Text = 'Blind Deconv Iterations';

            % Create BlindDeconvIterationsEditField
            app.BlindDeconvIterationsEditField = uieditfield(app.DeconvolutionTab, 'numeric');
            app.BlindDeconvIterationsEditField.ValueChangedFcn = createCallbackFcn(app, @BlindDeconvIterationsEditFieldValueChanged, true);
            app.BlindDeconvIterationsEditField.Position = [137 155 43 22];
            app.BlindDeconvIterationsEditField.Value = 125;

            % Create RLDeconvIterationsEditFieldLabel
            app.RLDeconvIterationsEditFieldLabel = uilabel(app.DeconvolutionTab);
            app.RLDeconvIterationsEditFieldLabel.HorizontalAlignment = 'right';
            app.RLDeconvIterationsEditFieldLabel.Position = [6 122 126 22];
            app.RLDeconvIterationsEditFieldLabel.Text = 'R&L Deconv Iterations';

            % Create RLDeconvIterationsEditField
            app.RLDeconvIterationsEditField = uieditfield(app.DeconvolutionTab, 'numeric');
            app.RLDeconvIterationsEditField.ValueChangedFcn = createCallbackFcn(app, @RLDeconvIterationsEditFieldValueChanged, true);
            app.RLDeconvIterationsEditField.Position = [137 122 43 22];
            app.RLDeconvIterationsEditField.Value = 4;

            % Create DeconvoluteImageButton
            app.DeconvoluteImageButton = uibutton(app.DeconvolutionTab, 'push');
            app.DeconvoluteImageButton.ButtonPushedFcn = createCallbackFcn(app, @DeconvoluteImageButtonPushed, true);
            app.DeconvoluteImageButton.Position = [15 79 165 22];
            app.DeconvoluteImageButton.Text = 'Deconvolute Image';

            % Create ContrastBrightness
            app.ContrastBrightness = uitabgroup(app.UIFigure);
            app.ContrastBrightness.AutoResizeChildren = 'off';
            app.ContrastBrightness.Position = [1 229 191 159];

            % Create FlatFieldTab
            app.FlatFieldTab = uitab(app.ContrastBrightness);
            app.FlatFieldTab.Title = 'FlatField';

            % Create FlatFieldUnevenBrightnessCheckBox
            app.FlatFieldUnevenBrightnessCheckBox = uicheckbox(app.FlatFieldTab);
            app.FlatFieldUnevenBrightnessCheckBox.ValueChangedFcn = createCallbackFcn(app, @FlatFieldUnevenBrightnessCheckBoxValueChanged, true);
            app.FlatFieldUnevenBrightnessCheckBox.Text = 'Flat Field (Uneven Brightness)';
            app.FlatFieldUnevenBrightnessCheckBox.Position = [4 95 184 22];

            % Create FlatFieldCorrectionSigmaSliderLabel
            app.FlatFieldCorrectionSigmaSliderLabel = uilabel(app.FlatFieldTab);
            app.FlatFieldCorrectionSigmaSliderLabel.HorizontalAlignment = 'center';
            app.FlatFieldCorrectionSigmaSliderLabel.Position = [7 74 166 22];
            app.FlatFieldCorrectionSigmaSliderLabel.Text = 'Flat Field Correction Sigma';

            % Create FlatFieldCorrectionSigmaSlider
            app.FlatFieldCorrectionSigmaSlider = uislider(app.FlatFieldTab);
            app.FlatFieldCorrectionSigmaSlider.Limits = [5 100];
            app.FlatFieldCorrectionSigmaSlider.MajorTicks = [0 20 40 60 80 100];
            app.FlatFieldCorrectionSigmaSlider.MajorTickLabels = {'0', '20', '40', '60', '80', '100'};
            app.FlatFieldCorrectionSigmaSlider.ValueChangedFcn = createCallbackFcn(app, @FlatFieldCorrectionSigmaSliderValueChanged, true);
            app.FlatFieldCorrectionSigmaSlider.MinorTicks = [10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100];
            app.FlatFieldCorrectionSigmaSlider.Position = [7 63 166 3];
            app.FlatFieldCorrectionSigmaSlider.Value = 30;

            % Create IntensityInTab
            app.IntensityInTab = uitab(app.ContrastBrightness);
            app.IntensityInTab.AutoResizeChildren = 'off';
            app.IntensityInTab.Title = 'Intensity In';

            % Create LowInSliderLabel
            app.LowInSliderLabel = uilabel(app.IntensityInTab);
            app.LowInSliderLabel.HorizontalAlignment = 'right';
            app.LowInSliderLabel.Position = [15 100 41 22];
            app.LowInSliderLabel.Text = 'Low In';

            % Create LowInSlider
            app.LowInSlider = uislider(app.IntensityInTab);
            app.LowInSlider.Limits = [0 1];
            app.LowInSlider.ValueChangedFcn = createCallbackFcn(app, @LowInSliderValueChanged, true);
            app.LowInSlider.Position = [70 119 107 3];

            % Create HighInSliderLabel
            app.HighInSliderLabel = uilabel(app.IntensityInTab);
            app.HighInSliderLabel.HorizontalAlignment = 'right';
            app.HighInSliderLabel.Position = [15 28 44 22];
            app.HighInSliderLabel.Text = 'High In';

            % Create HighInSlider
            app.HighInSlider = uislider(app.IntensityInTab);
            app.HighInSlider.Limits = [0 1];
            app.HighInSlider.ValueChangedFcn = createCallbackFcn(app, @HighInSliderValueChanged, true);
            app.HighInSlider.Position = [70 47 107 3];
            app.HighInSlider.Value = 1;

            % Create IntensityOutTab
            app.IntensityOutTab = uitab(app.ContrastBrightness);
            app.IntensityOutTab.AutoResizeChildren = 'off';
            app.IntensityOutTab.Title = 'Intensity Out';

            % Create LowOutSliderLabel
            app.LowOutSliderLabel = uilabel(app.IntensityOutTab);
            app.LowOutSliderLabel.HorizontalAlignment = 'right';
            app.LowOutSliderLabel.Position = [8 102 50 22];
            app.LowOutSliderLabel.Text = 'Low Out';

            % Create LowOutSlider
            app.LowOutSlider = uislider(app.IntensityOutTab);
            app.LowOutSlider.Limits = [0 1];
            app.LowOutSlider.ValueChangedFcn = createCallbackFcn(app, @LowOutSliderValueChanged, true);
            app.LowOutSlider.Position = [70 119 107 3];

            % Create HighOutSliderLabel
            app.HighOutSliderLabel = uilabel(app.IntensityOutTab);
            app.HighOutSliderLabel.HorizontalAlignment = 'right';
            app.HighOutSliderLabel.Position = [9 29 53 22];
            app.HighOutSliderLabel.Text = 'High Out';

            % Create HighOutSlider
            app.HighOutSlider = uislider(app.IntensityOutTab);
            app.HighOutSlider.Limits = [0 1];
            app.HighOutSlider.ValueChangedFcn = createCallbackFcn(app, @HighOutSliderValueChanged, true);
            app.HighOutSlider.Position = [70 47 107 3];
            app.HighOutSlider.Value = 1;

            % Create GammaTab
            app.GammaTab = uitab(app.ContrastBrightness);
            app.GammaTab.Title = 'Gamma';

            % Create GammaLabel
            app.GammaLabel = uilabel(app.GammaTab);
            app.GammaLabel.HorizontalAlignment = 'right';
            app.GammaLabel.Position = [0 74 48 22];
            app.GammaLabel.Text = 'Gamma';

            % Create GammaSlider
            app.GammaSlider = uislider(app.GammaTab);
            app.GammaSlider.Limits = [0 2.5];
            app.GammaSlider.ValueChangedFcn = createCallbackFcn(app, @GammaSliderValueChanged, true);
            app.GammaSlider.Position = [61 83 116 3];
            app.GammaSlider.Value = 1;

            % Create Quantify_ScaleBar
            app.Quantify_ScaleBar = uitabgroup(app.UIFigure);
            app.Quantify_ScaleBar.AutoResizeChildren = 'off';
            app.Quantify_ScaleBar.Position = [834 0 365 647];

            % Create AtomPositionTab
            app.AtomPositionTab = uitab(app.Quantify_ScaleBar);
            app.AtomPositionTab.AutoResizeChildren = 'off';
            app.AtomPositionTab.Title = 'Atom Position';

            % Create ThresholdsigmaEditFieldLabel
            app.ThresholdsigmaEditFieldLabel = uilabel(app.AtomPositionTab);
            app.ThresholdsigmaEditFieldLabel.HorizontalAlignment = 'center';
            app.ThresholdsigmaEditFieldLabel.Position = [0 594 102 22];
            app.ThresholdsigmaEditFieldLabel.Text = 'Threshold (sigma)';

            % Create ThresholdsigmaEditField
            app.ThresholdsigmaEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.ThresholdsigmaEditField.ValueChangedFcn = createCallbackFcn(app, @ThresholdsigmaEditFieldValueChanged, true);
            app.ThresholdsigmaEditField.HorizontalAlignment = 'center';
            app.ThresholdsigmaEditField.Position = [105 594 53 22];

            % Create MinDistanceEditFieldLabel
            app.MinDistanceEditFieldLabel = uilabel(app.AtomPositionTab);
            app.MinDistanceEditFieldLabel.HorizontalAlignment = 'center';
            app.MinDistanceEditFieldLabel.Position = [13 561 75 22];
            app.MinDistanceEditFieldLabel.Text = 'Min Distance';

            % Create MinDistanceEditField
            app.MinDistanceEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.MinDistanceEditField.ValueChangedFcn = createCallbackFcn(app, @MinDistanceEditFieldValueChanged, true);
            app.MinDistanceEditField.HorizontalAlignment = 'center';
            app.MinDistanceEditField.Position = [105 561 53 22];
            app.MinDistanceEditField.Value = 10;

            % Create CalculateLatticeButton
            app.CalculateLatticeButton = uibutton(app.AtomPositionTab, 'push');
            app.CalculateLatticeButton.ButtonPushedFcn = createCallbackFcn(app, @CalculateLatticeButtonPushed, true);
            app.CalculateLatticeButton.Position = [16 131 138 22];
            app.CalculateLatticeButton.Text = 'Calculate Lattice';

            % Create OriginXEditFieldLabel
            app.OriginXEditFieldLabel = uilabel(app.AtomPositionTab);
            app.OriginXEditFieldLabel.HorizontalAlignment = 'right';
            app.OriginXEditFieldLabel.Position = [179 341 55 22];
            app.OriginXEditFieldLabel.Text = 'Origin X';

            % Create OriginXEditField
            app.OriginXEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.OriginXEditField.Limits = [0 2048];
            app.OriginXEditField.ValueChangedFcn = createCallbackFcn(app, @OriginXEditFieldValueChanged, true);
            app.OriginXEditField.HorizontalAlignment = 'center';
            app.OriginXEditField.Position = [244 341 41 22];
            app.OriginXEditField.Value = 1024;

            % Create YEditFieldLabel
            app.YEditFieldLabel = uilabel(app.AtomPositionTab);
            app.YEditFieldLabel.HorizontalAlignment = 'right';
            app.YEditFieldLabel.Position = [297 341 14 22];
            app.YEditFieldLabel.Text = 'Y';

            % Create OriginYEditField
            app.OriginYEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.OriginYEditField.Limits = [0 2048];
            app.OriginYEditField.ValueChangedFcn = createCallbackFcn(app, @OriginYEditFieldValueChanged, true);
            app.OriginYEditField.HorizontalAlignment = 'center';
            app.OriginYEditField.Position = [318 341 41 22];
            app.OriginYEditField.Value = 1024;

            % Create LatNumPlotEditFieldLabel
            app.LatNumPlotEditFieldLabel = uilabel(app.AtomPositionTab);
            app.LatNumPlotEditFieldLabel.HorizontalAlignment = 'center';
            app.LatNumPlotEditFieldLabel.Position = [9 175 68 22];
            app.LatNumPlotEditFieldLabel.Text = 'LatNumPlot';

            % Create LatNumPlotEditField
            app.LatNumPlotEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.LatNumPlotEditField.ValueChangedFcn = createCallbackFcn(app, @LatNumPlotEditFieldValueChanged, true);
            app.LatNumPlotEditField.HorizontalAlignment = 'center';
            app.LatNumPlotEditField.Position = [81 175 90 22];
            app.LatNumPlotEditField.Value = 3;

            % Create LatFracUEditFieldLabel
            app.LatFracUEditFieldLabel = uilabel(app.AtomPositionTab);
            app.LatFracUEditFieldLabel.HorizontalAlignment = 'center';
            app.LatFracUEditFieldLabel.Position = [9 209 62 22];
            app.LatFracUEditFieldLabel.Text = 'Lat Frac U';

            % Create LatFracUEditField
            app.LatFracUEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.LatFracUEditField.ValueChangedFcn = createCallbackFcn(app, @LatFracUEditFieldValueChanged, true);
            app.LatFracUEditField.HorizontalAlignment = 'center';
            app.LatFracUEditField.Position = [81 209 90 22];
            app.LatFracUEditField.Value = 3;

            % Create LatFracVEditFieldLabel
            app.LatFracVEditFieldLabel = uilabel(app.AtomPositionTab);
            app.LatFracVEditFieldLabel.HorizontalAlignment = 'center';
            app.LatFracVEditFieldLabel.Position = [201 209 61 22];
            app.LatFracVEditFieldLabel.Text = 'Lat Frac V';

            % Create LatFracVEditField
            app.LatFracVEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.LatFracVEditField.ValueChangedFcn = createCallbackFcn(app, @LatFracVEditFieldValueChanged, true);
            app.LatFracVEditField.HorizontalAlignment = 'center';
            app.LatFracVEditField.Position = [273 209 90 22];
            app.LatFracVEditField.Value = 3;

            % Create FindInitialPositionsButton
            app.FindInitialPositionsButton = uibutton(app.AtomPositionTab, 'push');
            app.FindInitialPositionsButton.ButtonPushedFcn = createCallbackFcn(app, @FindInitialPositionsButtonPushed, true);
            app.FindInitialPositionsButton.Position = [9 483 138 22];
            app.FindInitialPositionsButton.Text = 'Find Initial Positions';

            % Create ShowInitialpositionsCheckBox
            app.ShowInitialpositionsCheckBox = uicheckbox(app.AtomPositionTab);
            app.ShowInitialpositionsCheckBox.ValueChangedFcn = createCallbackFcn(app, @ShowInitialpositionsCheckBoxValueChanged, true);
            app.ShowInitialpositionsCheckBox.Text = 'Show Initial positions';
            app.ShowInitialpositionsCheckBox.Position = [189 442 138 22];
            app.ShowInitialpositionsCheckBox.Value = true;

            % Create SpotsColorDropDownLabel
            app.SpotsColorDropDownLabel = uilabel(app.AtomPositionTab);
            app.SpotsColorDropDownLabel.HorizontalAlignment = 'center';
            app.SpotsColorDropDownLabel.Position = [186 483 68 22];
            app.SpotsColorDropDownLabel.Text = 'Spots Color';

            % Create InitialSpotsColorDropDown
            app.InitialSpotsColorDropDown = uidropdown(app.AtomPositionTab);
            app.InitialSpotsColorDropDown.Items = {'Yellow', 'Blue', 'Red', 'Green', 'White', 'Black'};
            app.InitialSpotsColorDropDown.ValueChangedFcn = createCallbackFcn(app, @InitialSpotsColorDropDownValueChanged, true);
            app.InitialSpotsColorDropDown.Position = [259 483 90 22];
            app.InitialSpotsColorDropDown.Value = 'Yellow';

            % Create ShowLatticepositionsCheckBox
            app.ShowLatticepositionsCheckBox = uicheckbox(app.AtomPositionTab);
            app.ShowLatticepositionsCheckBox.ValueChangedFcn = createCallbackFcn(app, @ShowLatticepositionsCheckBoxValueChanged, true);
            app.ShowLatticepositionsCheckBox.Text = 'Show Lattice positions';
            app.ShowLatticepositionsCheckBox.Position = [196 107 141 22];
            app.ShowLatticepositionsCheckBox.Value = true;

            % Create RefinePositionsButton
            app.RefinePositionsButton = uibutton(app.AtomPositionTab, 'push');
            app.RefinePositionsButton.ButtonPushedFcn = createCallbackFcn(app, @RefinePositionsButtonPushed, true);
            app.RefinePositionsButton.Position = [16 76 138 22];
            app.RefinePositionsButton.Text = 'Refine Positions';

            % Create ShowrefinedpositionsCheckBox
            app.ShowrefinedpositionsCheckBox = uicheckbox(app.AtomPositionTab);
            app.ShowrefinedpositionsCheckBox.ValueChangedFcn = createCallbackFcn(app, @ShowrefinedpositionsCheckBoxValueChanged, true);
            app.ShowrefinedpositionsCheckBox.Text = 'Show refined positions';
            app.ShowrefinedpositionsCheckBox.Position = [196 55 138 22];
            app.ShowrefinedpositionsCheckBox.Value = true;

            % Create SpotsColorDropDown_2Label
            app.SpotsColorDropDown_2Label = uilabel(app.AtomPositionTab);
            app.SpotsColorDropDown_2Label.HorizontalAlignment = 'center';
            app.SpotsColorDropDown_2Label.Position = [196 78 68 22];
            app.SpotsColorDropDown_2Label.Text = 'Spots Color';

            % Create RefinedSpotsColorDropDown
            app.RefinedSpotsColorDropDown = uidropdown(app.AtomPositionTab);
            app.RefinedSpotsColorDropDown.Items = {'Yellow', 'Blue', 'Red', 'Green', 'White', 'Black'};
            app.RefinedSpotsColorDropDown.ValueChangedFcn = createCallbackFcn(app, @RefinedSpotsColorDropDownValueChanged, true);
            app.RefinedSpotsColorDropDown.Position = [266 77 90 22];
            app.RefinedSpotsColorDropDown.Value = 'Red';

            % Create MpfitOverlapsButton
            app.MpfitOverlapsButton = uibutton(app.AtomPositionTab, 'push');
            app.MpfitOverlapsButton.ButtonPushedFcn = createCallbackFcn(app, @MpfitOverlapsButtonPushed, true);
            app.MpfitOverlapsButton.Position = [16 26 138 22];
            app.MpfitOverlapsButton.Text = 'Mpfit Overlaps';

            % Create MPfitpositionsCheckBox
            app.MPfitpositionsCheckBox = uicheckbox(app.AtomPositionTab);
            app.MPfitpositionsCheckBox.ValueChangedFcn = createCallbackFcn(app, @MPfitpositionsCheckBoxValueChanged, true);
            app.MPfitpositionsCheckBox.Text = 'MPfit positions';
            app.MPfitpositionsCheckBox.Position = [196 4 100 22];
            app.MPfitpositionsCheckBox.Value = true;

            % Create CrossColorLabel
            app.CrossColorLabel = uilabel(app.AtomPositionTab);
            app.CrossColorLabel.HorizontalAlignment = 'center';
            app.CrossColorLabel.Position = [193 131 69 22];
            app.CrossColorLabel.Text = 'Cross Color';

            % Create CrossColorDropDown
            app.CrossColorDropDown = uidropdown(app.AtomPositionTab);
            app.CrossColorDropDown.Items = {'Yellow', 'Blue', 'Red', 'Green', 'White', 'Black'};
            app.CrossColorDropDown.ValueChangedFcn = createCallbackFcn(app, @CrossColorDropDownValueChanged, true);
            app.CrossColorDropDown.Position = [266 131 90 22];
            app.CrossColorDropDown.Value = 'Green';

            % Create CrossColorDropDown_2Label
            app.CrossColorDropDown_2Label = uilabel(app.AtomPositionTab);
            app.CrossColorDropDown_2Label.HorizontalAlignment = 'center';
            app.CrossColorDropDown_2Label.Position = [193 25 69 22];
            app.CrossColorDropDown_2Label.Text = 'Cross Color';

            % Create RefinedCrossColorDropDown
            app.RefinedCrossColorDropDown = uidropdown(app.AtomPositionTab);
            app.RefinedCrossColorDropDown.Items = {'Yellow', 'Blue', 'Red', 'Green', 'White', 'Black'};
            app.RefinedCrossColorDropDown.ValueChangedFcn = createCallbackFcn(app, @RefinedCrossColorDropDownValueChanged, true);
            app.RefinedCrossColorDropDown.Position = [266 25 90 22];
            app.RefinedCrossColorDropDown.Value = 'Green';

            % Create AddMissingPointsButton
            app.AddMissingPointsButton = uibutton(app.AtomPositionTab, 'push');
            app.AddMissingPointsButton.ButtonPushedFcn = createCallbackFcn(app, @AddMissingPointsButtonPushed, true);
            app.AddMissingPointsButton.Position = [9 395 138 22];
            app.AddMissingPointsButton.Text = 'Add Missing Points';

            % Create DefineAreaofInterestButton
            app.DefineAreaofInterestButton = uibutton(app.AtomPositionTab, 'push');
            app.DefineAreaofInterestButton.ButtonPushedFcn = createCallbackFcn(app, @DefineAreaofInterestButtonPushed, true);
            app.DefineAreaofInterestButton.Position = [9 441 138 22];
            app.DefineAreaofInterestButton.Text = 'Define Area of Interest';

            % Create UendXEditFieldLabel
            app.UendXEditFieldLabel = uilabel(app.AtomPositionTab);
            app.UendXEditFieldLabel.HorizontalAlignment = 'right';
            app.UendXEditFieldLabel.Position = [185 299 49 22];
            app.UendXEditFieldLabel.Text = 'U end X';

            % Create UendXEditField
            app.UendXEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.UendXEditField.ValueChangedFcn = createCallbackFcn(app, @UendXEditFieldValueChanged, true);
            app.UendXEditField.HorizontalAlignment = 'center';
            app.UendXEditField.Position = [244 299 41 22];
            app.UendXEditField.Value = 1124;

            % Create YEditFieldLabel_2
            app.YEditFieldLabel_2 = uilabel(app.AtomPositionTab);
            app.YEditFieldLabel_2.HorizontalAlignment = 'right';
            app.YEditFieldLabel_2.Position = [297 299 14 22];
            app.YEditFieldLabel_2.Text = 'Y';

            % Create UendYEditField
            app.UendYEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.UendYEditField.ValueChangedFcn = createCallbackFcn(app, @UendYEditFieldValueChanged, true);
            app.UendYEditField.HorizontalAlignment = 'center';
            app.UendYEditField.Position = [318 299 41 22];
            app.UendYEditField.Value = 1024;

            % Create VendXEditFieldLabel
            app.VendXEditFieldLabel = uilabel(app.AtomPositionTab);
            app.VendXEditFieldLabel.HorizontalAlignment = 'right';
            app.VendXEditFieldLabel.Position = [186 257 48 22];
            app.VendXEditFieldLabel.Text = 'V end X';

            % Create VendXEditField
            app.VendXEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.VendXEditField.ValueChangedFcn = createCallbackFcn(app, @VendXEditFieldValueChanged, true);
            app.VendXEditField.HorizontalAlignment = 'center';
            app.VendXEditField.Position = [244 257 41 22];
            app.VendXEditField.Value = 1024;

            % Create YEditFieldLabel_3
            app.YEditFieldLabel_3 = uilabel(app.AtomPositionTab);
            app.YEditFieldLabel_3.HorizontalAlignment = 'right';
            app.YEditFieldLabel_3.Position = [299 257 10 22];
            app.YEditFieldLabel_3.Text = 'Y';

            % Create VendYEditField
            app.VendYEditField = uieditfield(app.AtomPositionTab, 'numeric');
            app.VendYEditField.ValueChangedFcn = createCallbackFcn(app, @VendYEditFieldValueChanged, true);
            app.VendYEditField.HorizontalAlignment = 'center';
            app.VendYEditField.Position = [318 257 41 22];
            app.VendYEditField.Value = 1124;

            % Create RemoveExtraPointsButton
            app.RemoveExtraPointsButton = uibutton(app.AtomPositionTab, 'push');
            app.RemoveExtraPointsButton.ButtonPushedFcn = createCallbackFcn(app, @RemoveExtraPointsButtonPushed, true);
            app.RemoveExtraPointsButton.Position = [199 395 138 22];
            app.RemoveExtraPointsButton.Text = 'Remove Extra Points';

            % Create SaveAtomPositionsButton
            app.SaveAtomPositionsButton = uibutton(app.AtomPositionTab, 'push');
            app.SaveAtomPositionsButton.ButtonPushedFcn = createCallbackFcn(app, @SaveAtomPositionsButtonPushed, true);
            app.SaveAtomPositionsButton.BackgroundColor = [1 0 0];
            app.SaveAtomPositionsButton.FontName = 'Georgia';
            app.SaveAtomPositionsButton.FontWeight = 'bold';
            app.SaveAtomPositionsButton.FontAngle = 'italic';
            app.SaveAtomPositionsButton.FontColor = [1 1 1];
            app.SaveAtomPositionsButton.Position = [173 568 177 36];
            app.SaveAtomPositionsButton.Text = 'Save Atom Positions';

            % Create FileLocationTextBox
            app.FileLocationTextBox = uitextarea(app.AtomPositionTab);
            app.FileLocationTextBox.BackgroundColor = [0.9412 0.9412 0.9412];
            app.FileLocationTextBox.Position = [0 519 364 36];
            app.FileLocationTextBox.Value = {'File Location'};

            % Create FindOriginButton
            app.FindOriginButton = uibutton(app.AtomPositionTab, 'push');
            app.FindOriginButton.ButtonPushedFcn = createCallbackFcn(app, @FindOriginButtonPushed, true);
            app.FindOriginButton.Position = [9 341 138 22];
            app.FindOriginButton.Text = {'Find Origin'; ''};

            % Create FindUButton
            app.FindUButton = uibutton(app.AtomPositionTab, 'push');
            app.FindUButton.ButtonPushedFcn = createCallbackFcn(app, @FindUButtonPushed, true);
            app.FindUButton.Position = [9 299 138 22];
            app.FindUButton.Text = 'Find U';

            % Create FindVButton
            app.FindVButton = uibutton(app.AtomPositionTab, 'push');
            app.FindVButton.ButtonPushedFcn = createCallbackFcn(app, @FindVButtonPushed, true);
            app.FindVButton.Position = [9 257 138 22];
            app.FindVButton.Text = 'Find V';

            % Create QuantifyTab
            app.QuantifyTab = uitab(app.Quantify_ScaleBar);
            app.QuantifyTab.Title = 'Quantify';

            % Create CalculateBondLengthBasedonNearNeighborButton
            app.CalculateBondLengthBasedonNearNeighborButton = uibutton(app.QuantifyTab, 'push');
            app.CalculateBondLengthBasedonNearNeighborButton.ButtonPushedFcn = createCallbackFcn(app, @CalculateBondLengthBasedonNearNeighborButtonPushed, true);
            app.CalculateBondLengthBasedonNearNeighborButton.Position = [11 429 343 55];
            app.CalculateBondLengthBasedonNearNeighborButton.Text = 'Calculate Bond Length Based on Near Neighbor';

            % Create IfShowBondLengthMapCheckBox
            app.IfShowBondLengthMapCheckBox = uicheckbox(app.QuantifyTab);
            app.IfShowBondLengthMapCheckBox.ValueChangedFcn = createCallbackFcn(app, @IfShowBondLengthMapCheckBoxValueChanged, true);
            app.IfShowBondLengthMapCheckBox.Text = 'If Show Bond Length Map';
            app.IfShowBondLengthMapCheckBox.Position = [108 404 160 22];
            app.IfShowBondLengthMapCheckBox.Value = true;

            % Create CalculateBondLengthBasedonLatticeButton
            app.CalculateBondLengthBasedonLatticeButton = uibutton(app.QuantifyTab, 'push');
            app.CalculateBondLengthBasedonLatticeButton.ButtonPushedFcn = createCallbackFcn(app, @CalculateBondLengthBasedonLatticeButtonPushed, true);
            app.CalculateBondLengthBasedonLatticeButton.Position = [11 258 343 55];
            app.CalculateBondLengthBasedonLatticeButton.Text = 'Calculate Bond Length Based on Lattice';

            % Create ColormapsDropDown_2Label
            app.ColormapsDropDown_2Label = uilabel(app.QuantifyTab);
            app.ColormapsDropDown_2Label.HorizontalAlignment = 'center';
            app.ColormapsDropDown_2Label.Position = [11 220 75 22];
            app.ColormapsDropDown_2Label.Text = 'Colormaps';

            % Create BondLengthColormapsDropDown
            app.BondLengthColormapsDropDown = uidropdown(app.QuantifyTab);
            app.BondLengthColormapsDropDown.Items = {'Gray', 'Parula', 'Hot', 'Cold', 'Jet', 'Blue White Red', 'All White'};
            app.BondLengthColormapsDropDown.ValueChangedFcn = createCallbackFcn(app, @BondLengthColormapsDropDownValueChanged, true);
            app.BondLengthColormapsDropDown.Position = [93 220 117 22];
            app.BondLengthColormapsDropDown.Value = 'Blue White Red';

            % Create InvertBondColorCheckBox
            app.InvertBondColorCheckBox = uicheckbox(app.QuantifyTab);
            app.InvertBondColorCheckBox.ValueChangedFcn = createCallbackFcn(app, @InvertBondColorCheckBoxValueChanged, true);
            app.InvertBondColorCheckBox.Text = 'Invert Bond Color';
            app.InvertBondColorCheckBox.Position = [236 220 118 22];

            % Create MeanDistanceEditFieldLabel
            app.MeanDistanceEditFieldLabel = uilabel(app.QuantifyTab);
            app.MeanDistanceEditFieldLabel.HorizontalAlignment = 'right';
            app.MeanDistanceEditFieldLabel.Position = [82 362 86 22];
            app.MeanDistanceEditFieldLabel.Text = 'Mean Distance';

            % Create MeanDistanceEditField
            app.MeanDistanceEditField = uieditfield(app.QuantifyTab, 'numeric');
            app.MeanDistanceEditField.ValueChangedFcn = createCallbackFcn(app, @MeanDistanceEditFieldValueChanged, true);
            app.MeanDistanceEditField.Position = [183 362 100 22];
            app.MeanDistanceEditField.Value = 329;

            % Create MeasurementRangeEditFieldLabel
            app.MeasurementRangeEditFieldLabel = uilabel(app.QuantifyTab);
            app.MeasurementRangeEditFieldLabel.HorizontalAlignment = 'right';
            app.MeasurementRangeEditFieldLabel.Position = [50 333 118 22];
            app.MeasurementRangeEditFieldLabel.Text = 'Measurement Range';

            % Create MeasurementRangeEditField
            app.MeasurementRangeEditField = uieditfield(app.QuantifyTab, 'numeric');
            app.MeasurementRangeEditField.ValueChangedFcn = createCallbackFcn(app, @MeasurementRangeEditFieldValueChanged, true);
            app.MeasurementRangeEditField.Position = [183 333 100 22];
            app.MeasurementRangeEditField.Value = 60;

            % Create LineStyleDropDownLabel
            app.LineStyleDropDownLabel = uilabel(app.QuantifyTab);
            app.LineStyleDropDownLabel.HorizontalAlignment = 'right';
            app.LineStyleDropDownLabel.Position = [15 180 58 22];
            app.LineStyleDropDownLabel.Text = 'Line Style';

            % Create LineStyleDropDown
            app.LineStyleDropDown = uidropdown(app.QuantifyTab);
            app.LineStyleDropDown.Items = {'Straight Line', 'Dashed Line', 'Dotted Line', 'Dot Dash Dot Dash'};
            app.LineStyleDropDown.ValueChangedFcn = createCallbackFcn(app, @LineStyleDropDownValueChanged, true);
            app.LineStyleDropDown.Position = [93 180 117 22];
            app.LineStyleDropDown.Value = 'Straight Line';

            % Create LineWidthSlider_2Label
            app.LineWidthSlider_2Label = uilabel(app.QuantifyTab);
            app.LineWidthSlider_2Label.HorizontalAlignment = 'right';
            app.LineWidthSlider_2Label.Position = [15 139 62 22];
            app.LineWidthSlider_2Label.Text = 'Line Width';

            % Create LineWidthSlider_2
            app.LineWidthSlider_2 = uislider(app.QuantifyTab);
            app.LineWidthSlider_2.Limits = [1 6];
            app.LineWidthSlider_2.ValueChangedFcn = createCallbackFcn(app, @LineWidthSlider_2ValueChanged, true);
            app.LineWidthSlider_2.Position = [93 148 261 3];
            app.LineWidthSlider_2.Value = 1;

            % Create GenerateBondLengthHistogramButton
            app.GenerateBondLengthHistogramButton = uibutton(app.QuantifyTab, 'push');
            app.GenerateBondLengthHistogramButton.ButtonPushedFcn = createCallbackFcn(app, @GenerateBondLengthHistogramButtonPushed, true);
            app.GenerateBondLengthHistogramButton.Position = [11 50 343 54];
            app.GenerateBondLengthHistogramButton.Text = 'Generate Bond Length Histogram';

            % Create CalculateStrainbasedonatomicpositionsButton
            app.CalculateStrainbasedonatomicpositionsButton = uibutton(app.QuantifyTab, 'push');
            app.CalculateStrainbasedonatomicpositionsButton.ButtonPushedFcn = createCallbackFcn(app, @CalculateStrainbasedonatomicpositionsButtonPushed, true);
            app.CalculateStrainbasedonatomicpositionsButton.Position = [11 541 343 56];
            app.CalculateStrainbasedonatomicpositionsButton.Text = 'Calculate Strain based on atomic positions';

            % Create StrainUpperLowerLimitEditFieldLabel
            app.StrainUpperLowerLimitEditFieldLabel = uilabel(app.QuantifyTab);
            app.StrainUpperLowerLimitEditFieldLabel.HorizontalAlignment = 'right';
            app.StrainUpperLowerLimitEditFieldLabel.Position = [30 511 138 22];
            app.StrainUpperLowerLimitEditFieldLabel.Text = 'Strain Upper/Lower Limit';

            % Create StrainUpperLowerLimitEditField
            app.StrainUpperLowerLimitEditField = uieditfield(app.QuantifyTab, 'numeric');
            app.StrainUpperLowerLimitEditField.ValueChangedFcn = createCallbackFcn(app, @StrainUpperLowerLimitEditFieldValueChanged, true);
            app.StrainUpperLowerLimitEditField.Position = [183 511 100 22];
            app.StrainUpperLowerLimitEditField.Value = 0.05;

            % Create Atom_SeparateTab
            app.Atom_SeparateTab = uitab(app.Quantify_ScaleBar);
            app.Atom_SeparateTab.Title = 'Atom_Separate';

            % Create SeparateAtomsCheckBox
            app.SeparateAtomsCheckBox = uicheckbox(app.Atom_SeparateTab);
            app.SeparateAtomsCheckBox.ValueChangedFcn = createCallbackFcn(app, @SeparateAtomsCheckBoxValueChanged, true);
            app.SeparateAtomsCheckBox.Text = 'Separate Atoms';
            app.SeparateAtomsCheckBox.Position = [249 575 105 22];
            app.SeparateAtomsCheckBox.Value = true;

            % Create SeparateAtomSpeciesButton
            app.SeparateAtomSpeciesButton = uibutton(app.Atom_SeparateTab, 'push');
            app.SeparateAtomSpeciesButton.ButtonPushedFcn = createCallbackFcn(app, @SeparateAtomSpeciesButtonPushed, true);
            app.SeparateAtomSpeciesButton.Position = [11 551 226 56];
            app.SeparateAtomSpeciesButton.Text = 'Separate Atom Species';

            % Create ThresholdSliderLabel
            app.ThresholdSliderLabel = uilabel(app.Atom_SeparateTab);
            app.ThresholdSliderLabel.HorizontalAlignment = 'right';
            app.ThresholdSliderLabel.Position = [5 503 59 22];
            app.ThresholdSliderLabel.Text = 'Threshold';

            % Create ThresholdSlider
            app.ThresholdSlider = uislider(app.Atom_SeparateTab);
            app.ThresholdSlider.ValueChangedFcn = createCallbackFcn(app, @ThresholdSliderValueChanged, true);
            app.ThresholdSlider.Position = [81 523 267 3];
            app.ThresholdSlider.Value = 70;

            % Create PlotNNDistributionButton
            app.PlotNNDistributionButton = uibutton(app.Atom_SeparateTab, 'push');
            app.PlotNNDistributionButton.ButtonPushedFcn = createCallbackFcn(app, @PlotNNDistributionButtonPushed, true);
            app.PlotNNDistributionButton.Position = [11 418 158 56];
            app.PlotNNDistributionButton.Text = 'Plot NN Distribution';

            % Create PairDistributionFunctionButton
            app.PairDistributionFunctionButton = uibutton(app.Atom_SeparateTab, 'push');
            app.PairDistributionFunctionButton.ButtonPushedFcn = createCallbackFcn(app, @PairDistributionFunctionButtonPushed, true);
            app.PairDistributionFunctionButton.Position = [196 418 158 56];
            app.PairDistributionFunctionButton.Text = 'Pair Distribution Function';

            % Create XAxisLimitEditFieldLabel
            app.XAxisLimitEditFieldLabel = uilabel(app.Atom_SeparateTab);
            app.XAxisLimitEditFieldLabel.HorizontalAlignment = 'right';
            app.XAxisLimitEditFieldLabel.Position = [196 387 69 22];
            app.XAxisLimitEditFieldLabel.Text = 'X-Axis Limit';

            % Create XAxisLimitEditField_PDF
            app.XAxisLimitEditField_PDF = uieditfield(app.Atom_SeparateTab, 'numeric');
            app.XAxisLimitEditField_PDF.ValueChangedFcn = createCallbackFcn(app, @XAxisLimitEditField_PDFValueChanged, true);
            app.XAxisLimitEditField_PDF.HorizontalAlignment = 'center';
            app.XAxisLimitEditField_PDF.Position = [275 387 79 22];
            app.XAxisLimitEditField_PDF.Value = 4;

            % Create XAxisLimitEditField_2Label
            app.XAxisLimitEditField_2Label = uilabel(app.Atom_SeparateTab);
            app.XAxisLimitEditField_2Label.HorizontalAlignment = 'right';
            app.XAxisLimitEditField_2Label.Position = [11 387 69 22];
            app.XAxisLimitEditField_2Label.Text = 'X-Axis Limit';

            % Create XAxisLimitEditField_NN
            app.XAxisLimitEditField_NN = uieditfield(app.Atom_SeparateTab, 'numeric');
            app.XAxisLimitEditField_NN.ValueChangedFcn = createCallbackFcn(app, @XAxisLimitEditField_NNValueChanged, true);
            app.XAxisLimitEditField_NN.HorizontalAlignment = 'center';
            app.XAxisLimitEditField_NN.Position = [90 387 79 22];
            app.XAxisLimitEditField_NN.Value = 4;

            % Create NeighborsEditFieldLabel
            app.NeighborsEditFieldLabel = uilabel(app.Atom_SeparateTab);
            app.NeighborsEditFieldLabel.HorizontalAlignment = 'right';
            app.NeighborsEditFieldLabel.Position = [11 345 70 22];
            app.NeighborsEditFieldLabel.Text = '# Neighbors';

            % Create NeighborsEditField_NN
            app.NeighborsEditField_NN = uieditfield(app.Atom_SeparateTab, 'numeric');
            app.NeighborsEditField_NN.ValueChangedFcn = createCallbackFcn(app, @NeighborsEditField_NNValueChanged, true);
            app.NeighborsEditField_NN.HorizontalAlignment = 'center';
            app.NeighborsEditField_NN.Position = [90 345 79 22];
            app.NeighborsEditField_NN.Value = 4;

            % Create NeighborsEditFieldLabel_2
            app.NeighborsEditFieldLabel_2 = uilabel(app.Atom_SeparateTab);
            app.NeighborsEditFieldLabel_2.HorizontalAlignment = 'right';
            app.NeighborsEditFieldLabel_2.Position = [196 345 70 22];
            app.NeighborsEditFieldLabel_2.Text = '# Neighbors';

            % Create NeighborsEditField_PDF
            app.NeighborsEditField_PDF = uieditfield(app.Atom_SeparateTab, 'numeric');
            app.NeighborsEditField_PDF.ValueChangedFcn = createCallbackFcn(app, @NeighborsEditField_PDFValueChanged, true);
            app.NeighborsEditField_PDF.HorizontalAlignment = 'center';
            app.NeighborsEditField_PDF.Position = [275 345 79 22];
            app.NeighborsEditField_PDF.Value = 100;

            % Create Find_Trios
            app.Find_Trios = uibutton(app.Atom_SeparateTab, 'push');
            app.Find_Trios.ButtonPushedFcn = createCallbackFcn(app, @Find_TriosButtonPushed, true);
            app.Find_Trios.Position = [11 269 158 56];
            app.Find_Trios.Text = 'Find Trios';

            % Create Find_Triangles
            app.Find_Triangles = uibutton(app.Atom_SeparateTab, 'push');
            app.Find_Triangles.ButtonPushedFcn = createCallbackFcn(app, @Find_TrianglesButtonPushed, true);
            app.Find_Triangles.Position = [196 269 158 56];
            app.Find_Triangles.Text = 'Find Triangles';

            % Create Find_Monos
            app.Find_Monos = uibutton(app.Atom_SeparateTab, 'push');
            app.Find_Monos.ButtonPushedFcn = createCallbackFcn(app, @Find_MonosButtonPushed, true);
            app.Find_Monos.Position = [196 202 158 56];
            app.Find_Monos.Text = 'Find Monos';

            % Create FindNumNeighbors_W
            app.FindNumNeighbors_W = uibutton(app.Atom_SeparateTab, 'push');
            app.FindNumNeighbors_W.ButtonPushedFcn = createCallbackFcn(app, @FindNumNeighbors_WButtonPushed, true);
            app.FindNumNeighbors_W.Position = [11 129 158 56];
            app.FindNumNeighbors_W.Text = 'Scatter W#NN distribution';

            % Create FindNumNeighbors_Mo
            app.FindNumNeighbors_Mo = uibutton(app.Atom_SeparateTab, 'push');
            app.FindNumNeighbors_Mo.ButtonPushedFcn = createCallbackFcn(app, @FindNumNeighbors_MoButtonPushed, true);
            app.FindNumNeighbors_Mo.Position = [196 129 159 56];
            app.FindNumNeighbors_Mo.Text = 'Scatter Mo#NN distribution';

            % Create NoteTextAreaLabel
            app.NoteTextAreaLabel = uilabel(app.Atom_SeparateTab);
            app.NoteTextAreaLabel.HorizontalAlignment = 'right';
            app.NoteTextAreaLabel.Position = [22 57 34 22];
            app.NoteTextAreaLabel.Text = 'Note:';

            % Create NoteTextArea
            app.NoteTextArea = uitextarea(app.Atom_SeparateTab);
            app.NoteTextArea.BackgroundColor = [0.9412 0.9412 0.9412];
            app.NoteTextArea.Position = [71 13 272 83];
            app.NoteTextArea.Value = {'This tab is designed for sorting different alloying elements in the monolayer (W,Mo)S2'; ''; 'It is still under construction. Not sure if it works for other systems for now. '};

            % Create ScaleBarTab
            app.ScaleBarTab = uitab(app.Quantify_ScaleBar);
            app.ScaleBarTab.AutoResizeChildren = 'off';
            app.ScaleBarTab.Title = 'Scale Bar';

            % Create PositionYSlider
            app.PositionYSlider = uislider(app.ScaleBarTab);
            app.PositionYSlider.Limits = [500 2050];
            app.PositionYSlider.MajorTicks = [500 750 1000 1250 1500 1750 2000];
            app.PositionYSlider.ValueChangedFcn = createCallbackFcn(app, @PositionYSliderValueChanged, true);
            app.PositionYSlider.Position = [20 253 320 3];
            app.PositionYSlider.Value = 1900;

            % Create YSlider
            app.YSlider = uislider(app.ScaleBarTab);
            app.YSlider.Limits = [-300 300];
            app.YSlider.ValueChangedFcn = createCallbackFcn(app, @YSliderValueChanged, true);
            app.YSlider.Position = [209 426 102 3];
            app.YSlider.Value = -100;

            % Create ScaleBarSwitch
            app.ScaleBarSwitch = uiswitch(app.ScaleBarTab, 'slider');
            app.ScaleBarSwitch.ValueChangedFcn = createCallbackFcn(app, @ScaleBarSwitchValueChanged, true);
            app.ScaleBarSwitch.Position = [56 578 45 20];

            % Create ScaleBarTextCheckBox
            app.ScaleBarTextCheckBox = uicheckbox(app.ScaleBarTab);
            app.ScaleBarTextCheckBox.ValueChangedFcn = createCallbackFcn(app, @ScaleBarTextCheckBoxValueChanged, true);
            app.ScaleBarTextCheckBox.Text = 'Scale Bar Text';
            app.ScaleBarTextCheckBox.Position = [211 580 99 22];
            app.ScaleBarTextCheckBox.Value = true;

            % Create TxtColorDropDown
            app.TxtColorDropDown = uidropdown(app.ScaleBarTab);
            app.TxtColorDropDown.Items = {'White', 'Black', 'Yellow', 'Red', 'Blue', 'Green'};
            app.TxtColorDropDown.ValueChangedFcn = createCallbackFcn(app, @TxtColorDropDownValueChanged, true);
            app.TxtColorDropDown.Position = [209 515 100 22];
            app.TxtColorDropDown.Value = 'White';

            % Create PositionXYSliderLabel
            app.PositionXYSliderLabel = uilabel(app.ScaleBarTab);
            app.PositionXYSliderLabel.HorizontalAlignment = 'center';
            app.PositionXYSliderLabel.Position = [139 316 71 22];
            app.PositionXYSliderLabel.Text = 'Position X,Y';

            % Create PositionXYSlider
            app.PositionXYSlider = uislider(app.ScaleBarTab);
            app.PositionXYSlider.Limits = [500 2050];
            app.PositionXYSlider.MajorTicks = [500 750 1000 1250 1500 1750 2000];
            app.PositionXYSlider.MajorTickLabels = {'500', '750', '1000', '1250', '1500', '1750', '2000'};
            app.PositionXYSlider.ValueChangedFcn = createCallbackFcn(app, @PositionXYSliderValueChanged, true);
            app.PositionXYSlider.MinorTicks = [500 525 550 575 600 625 650 675 700 725 750 775 800 825 850 875 900 925 950 975 1000 1025 1050 1075 1100 1125 1150 1175 1200 1225 1250 1275 1300 1325 1350 1375 1400 1425 1450 1475 1500 1525 1550 1575 1600 1625 1650 1675 1700 1725 1750 1775 1800 1825 1850 1875 1900 1925 1950 1975 2000 2025 2050];
            app.PositionXYSlider.Position = [20 308 320 3];
            app.PositionXYSlider.Value = 1800;

            % Create LengthnmEditFieldLabel
            app.LengthnmEditFieldLabel = uilabel(app.ScaleBarTab);
            app.LengthnmEditFieldLabel.HorizontalAlignment = 'right';
            app.LengthnmEditFieldLabel.FontSize = 13;
            app.LengthnmEditFieldLabel.Position = [46 552 71 22];
            app.LengthnmEditFieldLabel.Text = 'Length (nm)';

            % Create LengthnmEditField
            app.LengthnmEditField = uieditfield(app.ScaleBarTab, 'numeric');
            app.LengthnmEditField.Limits = [0.1 100];
            app.LengthnmEditField.ValueChangedFcn = createCallbackFcn(app, @LengthnmEditFieldValueChanged, true);
            app.LengthnmEditField.HorizontalAlignment = 'center';
            app.LengthnmEditField.Position = [61 524 46 22];
            app.LengthnmEditField.Value = 1;

            % Create FontSizeEditFieldLabel
            app.FontSizeEditFieldLabel = uilabel(app.ScaleBarTab);
            app.FontSizeEditFieldLabel.HorizontalAlignment = 'right';
            app.FontSizeEditFieldLabel.Position = [211 546 56 22];
            app.FontSizeEditFieldLabel.Text = 'Font Size';

            % Create FontSizeEditField
            app.FontSizeEditField = uieditfield(app.ScaleBarTab, 'numeric');
            app.FontSizeEditField.Limits = [5 50];
            app.FontSizeEditField.ValueChangedFcn = createCallbackFcn(app, @FontSizeEditFieldValueChanged, true);
            app.FontSizeEditField.HorizontalAlignment = 'center';
            app.FontSizeEditField.Position = [271 545 42 24];
            app.FontSizeEditField.Value = 15;

            % Create TextPositionXYSliderLabel
            app.TextPositionXYSliderLabel = uilabel(app.ScaleBarTab);
            app.TextPositionXYSliderLabel.HorizontalAlignment = 'right';
            app.TextPositionXYSliderLabel.Position = [213 479 96 22];
            app.TextPositionXYSliderLabel.Text = 'Text Position X,Y';

            % Create TextPositionXYSlider
            app.TextPositionXYSlider = uislider(app.ScaleBarTab);
            app.TextPositionXYSlider.Limits = [-300 300];
            app.TextPositionXYSlider.ValueChangedFcn = createCallbackFcn(app, @TextPositionXYSliderValueChanged, true);
            app.TextPositionXYSlider.Position = [209 468 102 3];
            app.TextPositionXYSlider.Value = 100;

            % Create LineWidthSliderLabel
            app.LineWidthSliderLabel = uilabel(app.ScaleBarTab);
            app.LineWidthSliderLabel.HorizontalAlignment = 'center';
            app.LineWidthSliderLabel.Position = [27 391 102 22];
            app.LineWidthSliderLabel.Text = 'Line Width';

            % Create LineWidthSlider
            app.LineWidthSlider = uislider(app.ScaleBarTab);
            app.LineWidthSlider.Limits = [1 10];
            app.LineWidthSlider.MajorTicks = [1 2 3 4 5 6 7 8 9 10];
            app.LineWidthSlider.ValueChangedFcn = createCallbackFcn(app, @LineWidthSliderValueChanged, true);
            app.LineWidthSlider.Position = [27 382 102 3];
            app.LineWidthSlider.Value = 5;

            % Create RotateBy90Button
            app.RotateBy90Button = uibutton(app.ScaleBarTab, 'push');
            app.RotateBy90Button.ButtonPushedFcn = createCallbackFcn(app, @RotateBy90ButtonPushed, true);
            app.RotateBy90Button.Position = [29 455 100 22];
            app.RotateBy90Button.Text = 'Rotate By 90';

            % Create NoteTextArea_2Label
            app.NoteTextArea_2Label = uilabel(app.ScaleBarTab);
            app.NoteTextArea_2Label.HorizontalAlignment = 'right';
            app.NoteTextArea_2Label.Position = [29 80 34 24];
            app.NoteTextArea_2Label.Text = 'Note:';

            % Create NoteTextArea_2
            app.NoteTextArea_2 = uitextarea(app.ScaleBarTab);
            app.NoteTextArea_2.BackgroundColor = [0.9412 0.9412 0.9412];
            app.NoteTextArea_2.Position = [71 60 272 63];
            app.NoteTextArea_2.Value = {'This tab is designed for adding scale bar for your image. Just drag the slider and change the values based on your need. '; ''};

            % Create InverseColorImageCheckBox
            app.InverseColorImageCheckBox = uicheckbox(app.UIFigure);
            app.InverseColorImageCheckBox.ValueChangedFcn = createCallbackFcn(app, @InverseColorImageCheckBoxValueChanged, true);
            app.InverseColorImageCheckBox.Text = 'Inverse Color Image';
            app.InverseColorImageCheckBox.Position = [12 434 130 22];

            % Create resetButton
            app.resetButton = uibutton(app.UIFigure, 'push');
            app.resetButton.ButtonPushedFcn = createCallbackFcn(app, @resetButtonPushed, true);
            app.resetButton.Position = [141 462 43 22];
            app.resetButton.Text = 'reset';

            % Create LoadImageFileButton
            app.LoadImageFileButton = uibutton(app.UIFigure, 'push');
            app.LoadImageFileButton.ButtonPushedFcn = createCallbackFcn(app, @LoadImageFileButtonPushed, true);
            app.LoadImageFileButton.BackgroundColor = [0.0745 0.6235 1];
            app.LoadImageFileButton.FontName = 'Georgia';
            app.LoadImageFileButton.FontWeight = 'bold';
            app.LoadImageFileButton.FontAngle = 'italic';
            app.LoadImageFileButton.FontColor = [1 1 1];
            app.LoadImageFileButton.Position = [9 519 177 36];
            app.LoadImageFileButton.Text = 'Load Image File';

            % Create LoadAtomPositionsButton
            app.LoadAtomPositionsButton = uibutton(app.UIFigure, 'push');
            app.LoadAtomPositionsButton.ButtonPushedFcn = createCallbackFcn(app, @LoadAtomPositionsButtonPushed, true);
            app.LoadAtomPositionsButton.BackgroundColor = [0 0.4471 0.7412];
            app.LoadAtomPositionsButton.FontName = 'Georgia';
            app.LoadAtomPositionsButton.FontWeight = 'bold';
            app.LoadAtomPositionsButton.FontAngle = 'italic';
            app.LoadAtomPositionsButton.FontColor = [1 1 1];
            app.LoadAtomPositionsButton.Position = [9 561 177 36];
            app.LoadAtomPositionsButton.Text = 'Load Atom Positions';

            % Create CalibrationLabel
            app.CalibrationLabel = uilabel(app.UIFigure);
            app.CalibrationLabel.HorizontalAlignment = 'right';
            app.CalibrationLabel.Position = [10 490 70 22];
            app.CalibrationLabel.Text = 'Calibration: ';

            % Create CalibrationEditField
            app.CalibrationEditField = uieditfield(app.UIFigure, 'numeric');
            app.CalibrationEditField.ValueChangedFcn = createCallbackFcn(app, @CalibrationEditFieldValueChanged, true);
            app.CalibrationEditField.HorizontalAlignment = 'center';
            app.CalibrationEditField.Position = [85 490 43 22];

            % Create ImageCalibrationEditFieldLabel_2
            app.ImageCalibrationEditFieldLabel_2 = uilabel(app.UIFigure);
            app.ImageCalibrationEditFieldLabel_2.HorizontalAlignment = 'right';
            app.ImageCalibrationEditFieldLabel_2.Position = [127 490 59 22];
            app.ImageCalibrationEditFieldLabel_2.Text = 'pm/pixel';

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

    % App creation and deletion
    methods (Access = public)

        % Construct app
        function app = EASYSTEM_V1065_2ndPublishedVersion

            % Create UIFigure and components
            createComponents(app)

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

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

            if nargout == 0
                clear app
            end
        end

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

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