classdef NRICH< matlab.apps.AppBase
    % NRICH  Neutron Radiograph Inference of Concentration of Hydrogen
    %
    %   Estimates the hydrogen concentration in Zr-alloy cladding tubes from
    %   normalized neutron transmission images (.tif).
    %
    %   Calibration model
    %       T = a * exp(-b * C_H)    ->    C_H = -ln(T / a) / b
    %       T   : transmission (normalized gray value)
    %       a   : transmission of H-free material
    %       b   : sensitivity of neutrons to hydrogen (1/wppm)
    %       C_H : hydrogen concentration (wppm)
    %
    %   Workflow
    %       Input tab    Load image; enter geometry, calibration and pixel size.
    %       Analysis 1   "Average H" (or "Average gray value" for calibration)
    %                    -> Setting1: fit wall boundaries (auto or manual)
    %                    -> Radial profile: azimuthally averaged profile,
    %                       optional manual range, export to Excel.
    %       Analysis 2   "Contour"
    %                    -> Setting 2: select rectangular ROI
    %                    -> Contour map: raw and smoothed H maps, optional
    %                       boundary refinement and local radial profile.
    %
    %   Requirements
    %       MATLAB R2021b or later, Image Processing Toolbox,
    %       Optimization Toolbox (lsqnonlin), Statistics and Machine
    %       Learning Toolbox (quantile).
    %
    %   Usage
    %       app = NRICH;

    % Properties that correspond to app components
    properties (Access = public)
        UIFigure                        matlab.ui.Figure
        NeutronRadiographInferenceofConcentrationofHydrogenLabel  matlab.ui.control.Label
        RestartButton                   matlab.ui.control.Button
        NRICHLabel                      matlab.ui.control.Label
        TabGroup                        matlab.ui.container.TabGroup
        InputTab                        matlab.ui.container.Tab
        pixelumEditField                matlab.ui.control.NumericEditField
        ThicknessmmEditField_2Label_2   matlab.ui.control.Label
        bEditField                      matlab.ui.control.NumericEditField
        bEditField_2Label               matlab.ui.control.Label
        aEditField                      matlab.ui.control.NumericEditField
        aEditField_2Label               matlab.ui.control.Label
        ThicknessmmEditField            matlab.ui.control.NumericEditField
        ThicknessmmEditField_2Label     matlab.ui.control.Label
        ODmmEditField                   matlab.ui.control.NumericEditField
        ODmmEditField_2Label            matlab.ui.control.Label
        LoadfileButton                  matlab.ui.control.Button
        LoadyourtiffileLabel            matlab.ui.control.Label
        atransmissionofHfreematerialLabel  matlab.ui.control.Label
        CladdinggeometryinformationLabel  matlab.ui.control.Label
        CalibrationparametersLabel      matlab.ui.control.Label
        bsensitivityofneutronstohydrogenLabel  matlab.ui.control.Label
        xHconcentrationLabel            matlab.ui.control.Label
        yaexpbxLabel                    matlab.ui.control.Label
        yTransmissionLabel              matlab.ui.control.Label
        RunanalysisLabel                matlab.ui.control.Label
        ODmmEditField_2Label_4          matlab.ui.control.Label
        AveragegrayvalueButton          matlab.ui.control.Button
        ODmmEditField_2Label_2          matlab.ui.control.Label
        AverageHButton                  matlab.ui.control.Button
        ODmmEditField_2Label_3          matlab.ui.control.Label
        OptionalPanel                   matlab.ui.container.Panel
        ContourButton                   matlab.ui.control.Button
        UIAxes                          matlab.ui.control.UIAxes
        Setting1Tab                     matlab.ui.container.Tab
        AutoDetectBoundariesButton      matlab.ui.control.Button
        GenerateProfileButton           matlab.ui.control.Button
        OptionalPanel_2                 matlab.ui.container.Panel
        FitBoundariesButton             matlab.ui.control.Button
        Label_3                         matlab.ui.control.Label
        Label_2                         matlab.ui.control.Label
        Label                           matlab.ui.control.Label
        ManualFitLabel                  matlab.ui.control.Label
        SelectAreaButton                matlab.ui.control.Button
        DefineAnalysisAreaLabel         matlab.ui.control.Label
        RedrawButton                    matlab.ui.control.Button
        ResetouterButton                matlab.ui.control.Button
        MarkOuter3PointsButton          matlab.ui.control.Button
        ResetinnerButton                matlab.ui.control.Button
        MarkInner3PointsButton          matlab.ui.control.Button
        UIAxes_2                        matlab.ui.control.UIAxes
        RadialprofileandEntireviewTab   matlab.ui.container.Tab
        EntertoUpdateLabel_2            matlab.ui.control.Label
        LineWidthpixelEditField         matlab.ui.control.NumericEditField
        LineWidthpixelEditFieldLabel    matlab.ui.control.Label
        ExporttoexcelButton             matlab.ui.control.Button
        ManuallyselectthecladdingregionButton  matlab.ui.control.Button
        UIAxes3                         matlab.ui.control.UIAxes
        UIAxes4                         matlab.ui.control.UIAxes
        Setting2Tab                     matlab.ui.container.Tab
        ClickanddragtoselecttherectangularROIontheimageLabel  matlab.ui.control.Label
        GetcontourmapButton             matlab.ui.control.Button
        SelecttheROIButton              matlab.ui.control.Button
        UIAxes_4                        matlab.ui.control.UIAxes
        UIAxes_3                        matlab.ui.control.UIAxes
        ManualFitPanel_2                matlab.ui.container.Panel
        MarkInner3PointsButton_2        matlab.ui.control.Button
        MarkOuter3PointsButton_2        matlab.ui.control.Button
        FitBoundariesButton_2           matlab.ui.control.Button
        ManualFitHintLabel_2            matlab.ui.control.Label
        ContourmapTab                   matlab.ui.container.Tab
        EntertoUpdateLabel              matlab.ui.control.Label
        GetradialprofileButton          matlab.ui.control.Button
        ScalebarlengthEditField         matlab.ui.control.NumericEditField
        ScalebarlengthLabel             matlab.ui.control.Label
        SelectanewROIfromthestartLabel  matlab.ui.control.Label
        AdjustwallboundarieswithinthecurrentROILabel  matlab.ui.control.Label
        RefineBoundariesButton          matlab.ui.control.Button
        ReselectROIButton               matlab.ui.control.Button
        UIAxes_6                        matlab.ui.control.UIAxes
        UIAxes_5                        matlab.ui.control.UIAxes
    end

    % Analysis constants
    properties (Constant, Access = private)
        COLOR_ACTIVE = [0.67, 0.92, 1.00]   % highlights the recommended next step
        COLOR_IDLE   = [0.96, 0.96, 0.96]

        EDGE_THRESHOLD = 0.95               % transmission threshold: air (>=) vs. cladding (<)

        % Wall boundary detection on the radial profile
        PEAK_WINDOW_INNER_UM = [-100 300]   % search window around fitted inner radius (um)
        PEAK_WINDOW_OUTER_UM = [-300 100]   % search window around fitted outer radius (um)
        BASELINE_WINDOW_FRAC = 0.1          % half-width of mid-wall baseline window (fraction of peak spacing)
        PLATEAU_TOL_FRAC     = 0.05         % back on baseline when within 5% of peak height
        SYMMETRIC_PEAK_RATIO = 0.3          % symmetric clipping if smaller/larger peak >= ratio
        EDGE_MARGIN_UM       = 5            % extra clipping beyond the detected surface region (um)
    end

    % App state
    properties (Access = private)
        LoadedImage, filename
        calibration                 % [a b]
        pixeltolength               % um per pixel
        Grayaverage = false         % true: Analysis 1 reports transmission instead of H

        % Analysis 1 (Setting1)
        Fit_result = []             % [cx cy Ri Ro] in px
        Fit_done = 0
        Calc_done = false
        ViewRange = []              % zoom area from "Select Area" [row1 row2 col1 col2]
        SelectedPoints_in, SelectedPoints_out
        BlueDotHandles, RedDotHandles, FitCircleHandles
        Radial_data                 % [distance_um, value] of the azimuthal profile

        % Analysis 2 (Setting 2 / Contour map)
        SaveRange = []              % contour ROI [row1 row2 col1 col2]
        ContourCropHandles
        ContourFit = []             % [cx cy Ri Ro] in px (fit used for the contour map)
        ContourManualFit = false    % true when ContourFit comes from the 3-point manual fit on Setting 2
        ContourPoints_in, ContourPoints_out
        ContourBlueDotHandles, ContourRedDotHandles, ContourFitCircleHandles
        isManualRange = false       % true after "Refine Boundaries"
        current_ri_px, current_ro_px
        last_line_pos

        isLocalProfile = false      % true when UIAxes3 shows the local (line) profile
    end

    % Helper methods
    methods (Access = private)

        function updateSettings(app)
            % Synchronize UI field values with properties
            app.calibration = [app.aEditField.Value, app.bEditField.Value];
            app.pixeltolength = app.pixelumEditField.Value;
        end

        function setButtonState(app, buttons, isActive)
            % Highlight (or un-highlight) the button(s) for the next step
            for k = 1:numel(buttons)
                if isActive
                    buttons(k).BackgroundColor = app.COLOR_ACTIVE;
                    buttons(k).FontWeight = 'bold';
                else
                    buttons(k).BackgroundColor = app.COLOR_IDLE;
                    buttons(k).FontWeight = 'normal';
                end
            end
        end

        function doCrop(app)
            % Reset axis view to full image size
            [imgH, imgW, ~] = size(app.LoadedImage);
            app.UIAxes_2.XLim = [0.5, imgW + 0.5];
            app.UIAxes_2.YLim = [0.5, imgH + 0.5];

            imshow(app.LoadedImage, 'Parent', app.UIAxes_2);
            app.UIAxes_2.XTick = []; app.UIAxes_2.YTick = [];

            h = drawrectangle(app.UIAxes_2);
            rect = h.Position;

            % ROI selection
            if isempty(rect) || rect(3) <= 0 || rect(4) <= 0
                uialert(app.UIFigure, 'Please select a valid ROI area.', 'Error');
                delete(h);
                return;
            end

            % Update view to selected ROI
            app.UIAxes_2.XLim = [rect(1), rect(1) + rect(3)];
            app.UIAxes_2.YLim = [rect(2), rect(2) + rect(4)];

            % Save view range
            app.ViewRange = [round(rect(2)), round(rect(2)+rect(4)), ...
                round(rect(1)), round(rect(1)+rect(3))];

            delete(h);
        end

        function [pts, h] = selectPoints(~, ax, type)
            % Let the user click 3 points on the inner ('in', blue) or outer
            % ('out', red) surface. Returns [] if the selection is cancelled.
            dotColor = 'b'; if strcmp(type,'out'), dotColor = 'r'; end

            pts = zeros(3,2);
            h = gobjects(3,1);

            for i = 1:3
                roi = drawpoint(ax, 'Color', dotColor, 'MarkerSize', 8);
                if ~isvalid(roi) || isempty(roi.Position)   % selection cancelled
                    delete(h(isgraphics(h)));
                    pts = []; h = [];
                    return;
                end
                pts(i,:) = roi.Position;
                h(i) = roi;
            end
        end

        function deleteHandles(~, h)
            % Delete graphics/ROI handles that are still valid
            if ~isempty(h) && ~isnumeric(h)
                delete(h(isvalid(h)));
            end
        end

        function updateScaleBar(app)
            delete(findobj(app.UIAxes_5, 'Tag', 'ScaleBarItem'));
            delete(findobj(app.UIAxes_6, 'Tag', 'ScaleBarItem'));

            pixel_um = app.pixeltolength;
            scalebar_um = app.ScalebarlengthEditField.Value;

            if isempty(app.UIAxes_5.Children) || isempty(pixel_um), return; end

            xl = app.UIAxes_5.XLim;
            yl = app.UIAxes_5.YLim;
            bar_px = scalebar_um / pixel_um;

            margin_x = (xl(2) - xl(1)) * 0.04;
            margin_y = (yl(2) - yl(1)) * 0.04;
            x_start = xl(1) + margin_x;
            x_end = x_start + bar_px;
            y_pos = yl(2) - margin_y;

            pad_x = (xl(2) - xl(1)) * 0.01;
            pad_y = (yl(2) - yl(1)) * 0.01;

            px = [x_start-pad_x, x_end+pad_x, x_end+pad_x, x_start-pad_x];
            py = [y_pos+pad_y*1.6, y_pos+pad_y*1.6, y_pos-pad_y*4.8, y_pos-pad_y*4.8];

            target_axes = {app.UIAxes_5, app.UIAxes_6};
            for i = 1:length(target_axes)
                ax = target_axes{i};
                hold(ax, 'on');
                z_level = 1000;

                patch(ax, 'XData', px, 'YData', py, 'ZData', repmat(z_level-10, 1, 4), ...
                    'FaceColor', 'w', 'FaceAlpha', 0.85, 'EdgeColor', 'none', 'Tag', 'ScaleBarItem');

                plot3(ax, [x_start, x_end], [y_pos, y_pos], [z_level, z_level], ...
                    'k-', 'LineWidth', 3.7, 'Tag', 'ScaleBarItem');

                scale_text = [num2str(scalebar_um), ' \mum'];
                text(ax, (x_start + x_end)/2, y_pos - pad_y*0.43, z_level, scale_text, ...
                    'Color', 'k', 'FontSize', 15, 'FontWeight', 'bold', 'FontName', 'Times New Roman', ...
                    'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom', 'Tag', 'ScaleBarItem');

                hold(ax, 'off');
            end
        end

        function UpdateLineWidth(app)
            % Sector-averaged local H profile along the last drawn radial line.
            % Used by "Get radial profile" and by the Line Width field.
            if isempty(app.last_line_pos) || isempty(app.ContourFit), return; end

            img = app.LoadedImage;
            a = app.calibration(1); b = app.calibration(2);
            H_full = -log(max(double(img), eps)/a)/b;
            cx = app.ContourFit(1); cy = app.ContourFit(2);
            Ri_px = app.current_ri_px;
            Ro_px = app.current_ro_px;
            pixel_um = app.pixeltolength;

            % Center angle of the drawn line
            pos = app.last_line_pos;
            midX = mean(pos(:, 1)); midY = mean(pos(:, 2));
            targetAngle = atan2(midY - cy, midX - cx);

            % Sampling setup based on EditField value
            num_samples = round(app.LineWidthpixelEditField.Value);
            if num_samples < 1, num_samples = 1; end
            angleRange = num_samples / Ro_px;
            theta_steps = linspace(targetAngle - angleRange/2, targetAngle + angleRange/2, num_samples);

            % Extract radial profile data
            margin = (Ro_px - Ri_px) * 0.2;
            r_px = linspace(max(1, Ri_px - margin), Ro_px + margin, 300);
            x_v = r_px * pixel_um;

            [R_calc, T_calc] = meshgrid(r_px, theta_steps);
            X_calc = cx + R_calc .* cos(T_calc);
            Y_calc = cy + R_calc .* sin(T_calc);

            H_interp = interp2(H_full, X_calc, Y_calc, 'linear', NaN);
            y_v_local = mean(H_interp, 1, 'omitnan');

            % Update UIAxes3: profile plot
            cla(app.UIAxes3);
            hold(app.UIAxes3, 'on');
            plot(app.UIAxes3, x_v, y_v_local, 'b-', 'LineWidth', 1.5);
            xline(app.UIAxes3, Ri_px * pixel_um, '--r', 'LineWidth', 1.5);
            xline(app.UIAxes3, Ro_px * pixel_um, '--r', 'LineWidth', 1.5);

            valid_y = y_v_local(r_px >= Ri_px & r_px <= Ro_px);
            avg_val = mean(valid_y, 'omitnan');
            grid(app.UIAxes3, 'on');
            xlabel(app.UIAxes3, 'Radial distance (\mum)');
            ylabel(app.UIAxes3, 'H concentration (wppm)');
            title(app.UIAxes3, sprintf('Local Profile (Avg: %.1f wppm, Width: %d px)', avg_val, num_samples));
            hold(app.UIAxes3, 'off');

            % Update UIAxes4: averaging region
            cla(app.UIAxes4);
            imshow(img, 'Parent', app.UIAxes4);
            hold(app.UIAxes4, 'on');
            r = app.SaveRange;
            if ~isempty(r)
                app.UIAxes4.XLim = [r(3), r(4)];
                app.UIAxes4.YLim = [r(1), r(2)];
            end

            theta_min = theta_steps(1);
            theta_max = theta_steps(end);
            X_rect = cx + [Ri_px*cos(theta_min), Ro_px*cos(theta_min), ...
                Ro_px*cos(theta_max), Ri_px*cos(theta_max), Ri_px*cos(theta_min)];
            Y_rect = cy + [Ri_px*sin(theta_min), Ro_px*sin(theta_min), ...
                Ro_px*sin(theta_max), Ri_px*sin(theta_max), Ri_px*sin(theta_min)];

            plot(app.UIAxes4, X_rect, Y_rect, 'r-', 'LineWidth', 1.5);
            title(app.UIAxes4, ['Averaging Region (Width: ', num2str(num_samples), ' px)']);
            hold(app.UIAxes4, 'off');

            app.isLocalProfile = true;
        end

        function visualizeFit(app, img, targetAxes)
            imshow(img, 'Parent', targetAxes);
            hold(targetAxes, 'on');

            % Remove axis lines and labels
            axis(targetAxes, 'off');
            targetAxes.XLabel.String = '';
            targetAxes.YLabel.String = '';
            targetAxes.Title.String = '';

            xSize = size(img, 2);
            ySize = size(img, 1);

            % Fix axis limits
            targetAxes.XLim = [0.5, xSize + 0.5];
            targetAxes.YLim = [0.5, ySize + 0.5];

            % Draw fitted circles and center point
            theta = linspace(0, 2*pi, 360);
            c = app.Fit_result(1:2);
            Ri = app.Fit_result(3);
            Ro = app.Fit_result(4);

            app.FitCircleHandles(1) = plot(targetAxes, c(1)+Ri*cos(theta), c(2)+Ri*sin(theta), 'b', 'LineWidth', 1.5);
            app.FitCircleHandles(2) = plot(targetAxes, c(1)+Ro*cos(theta), c(2)+Ro*sin(theta), 'r', 'LineWidth', 1.5);
            app.FitCircleHandles(3) = plot(targetAxes, c(1), c(2), 'yo', 'MarkerSize', 8, 'MarkerFaceColor', 'y');

            axis(targetAxes, 'off');
            hold(targetAxes, 'off');
        end

        function fit = autoFitCircles(app, inputImage)
            % Fit concentric inner/outer circles to the two largest edge rings.
            % Returns [cx cy Ri Ro] (px), or [] if fewer than two rings are found.
            fit = [];
            binaryMask = (inputImage >= app.EDGE_THRESHOLD);
            edgeImage = edge(binaryMask, 'canny');
            CC = bwconncomp(edgeImage);
            if CC.NumObjects < 2, return; end

            numPixels = cellfun(@numel, CC.PixelIdxList);
            [~, sortedIdx] = sort(numPixels, 'descend');
            [r1, c1] = ind2sub(size(edgeImage), CC.PixelIdxList{sortedIdx(1)});
            [r2, c2] = ind2sub(size(edgeImage), CC.PixelIdxList{sortedIdx(2)});
            [center, R1, R2] = fit_two_circles_same_center([c1, r1], [c2, r2]);
            R_sorted = sort([R1, R2]);
            fit = [center, R_sorted(1), R_sorted(2)];
        end

        function [Ri_final, Ro_final, xLimits] = detectWallBoundaries(app, x_v, y_v, Ri_fit_um, Ro_fit_um)
            % Locate the cladding wall on a radial H profile.
            %   1) Find the surface peaks near the fitted inner/outer radii.
            %   2) From each peak, walk toward mid-wall until the profile is back
            %      within PLATEAU_TOL_FRAC of the mid-wall baseline.
            %   3) Clip both surfaces by that distance (+ EDGE_MARGIN_UM). If the two
            %      peaks are comparable, the larger distance is used on both sides.
            % Returns empty outputs if the peaks cannot be located.
            x_v = x_v(:); y_v = y_v(:);
            Ri_final = []; Ro_final = []; xLimits = [];

            search_i = find(x_v >= Ri_fit_um + app.PEAK_WINDOW_INNER_UM(1) & x_v <= Ri_fit_um + app.PEAK_WINDOW_INNER_UM(2));
            search_o = find(x_v >= Ro_fit_um + app.PEAK_WINDOW_OUTER_UM(1) & x_v <= Ro_fit_um + app.PEAK_WINDOW_OUTER_UM(2));
            if isempty(search_i) || isempty(search_o), return; end

            [val_i, mi] = max(y_v(search_i)); idx_peak_i = search_i(mi);
            [val_o, mo] = max(y_v(search_o)); idx_peak_o = search_o(mo);
            if idx_peak_o <= idx_peak_i, return; end

            % Baseline (mid-wall) and thresholds
            mid_idx = round((idx_peak_i + idx_peak_o) / 2);
            search_range = round((idx_peak_o - idx_peak_i) * app.BASELINE_WINDOW_FRAC);
            baseline = median(y_v(max(1, mid_idx - search_range) : min(numel(y_v), mid_idx + search_range)));
            threshold_i = abs(val_i - baseline) * app.PLATEAU_TOL_FRAC;
            threshold_o = abs(val_o - baseline) * app.PLATEAU_TOL_FRAC;

            % Search from inner peak toward mid-wall
            idx_stable_i = idx_peak_i;
            for k = idx_peak_i : idx_peak_o
                if abs(y_v(k) - baseline) < threshold_i, idx_stable_i = k; break; end
            end
            dist_i = abs(x_v(idx_stable_i) - x_v(idx_peak_i)) + app.EDGE_MARGIN_UM;

            % Search from outer peak toward mid-wall
            idx_stable_o = idx_peak_o;
            for k = idx_peak_o : -1 : idx_peak_i
                if abs(y_v(k) - baseline) < threshold_o, idx_stable_o = k; break; end
            end
            dist_o = abs(x_v(idx_peak_o) - x_v(idx_stable_o)) + app.EDGE_MARGIN_UM;

            % Symmetric clipping if both peaks are comparable, otherwise independent
            if min(val_i, val_o) / max(val_i, val_o) >= app.SYMMETRIC_PEAK_RATIO
                final_offset = max(dist_i, dist_o);
                Ri_final = x_v(idx_peak_i) + final_offset;
                Ro_final = x_v(idx_peak_o) - final_offset;
            else
                Ri_final = x_v(idx_peak_i) + dist_i;
                Ro_final = x_v(idx_peak_o) - dist_o;
            end
            xLimits = [min(x_v(search_i)) - 100, max(x_v(search_o)) + 100];
        end

        function clearAnalysis(app)
            % Reset analysis flags and data
            app.Calc_done = false;
            app.Fit_done = 0;
            app.Fit_result = [];
            app.Radial_data = [];
            app.isLocalProfile = false;

            % Clear main axes graphics
            app.deleteHandles(app.FitCircleHandles);
            app.FitCircleHandles = [];
            allLines = findobj(app.UIAxes_2, 'Type', 'line');
            if ~isempty(allLines), delete(allLines); end

            % Full reset of result axes
            cla(app.UIAxes3, 'reset');
            cla(app.UIAxes4, 'reset');

            app.UIAxes3.XTick = []; app.UIAxes3.YTick = [];
            app.UIAxes4.XTick = []; app.UIAxes4.YTick = [];
            title(app.UIAxes3, 'No Data');
            title(app.UIAxes4, 'No Data');
            app.LineWidthpixelEditField.Enable = 'off';

            % Update button states and colors
            app.GenerateProfileButton.Enable = 'off';
            app.GenerateProfileButton.BackgroundColor = app.COLOR_IDLE;
            app.AutoDetectBoundariesButton.BackgroundColor = app.COLOR_ACTIVE;
        end

        function ok = confirmDefaults(~, isDefault)
            % Ask the user to confirm when the input values are still the defaults
            ok = true;
            if isDefault
                ok = strcmp(questdlg('Use default values?', 'Confirm', 'Yes', 'No', 'No'), 'Yes');
            end
        end

        function startProfileAnalysis(app, grayMode)
            % Analysis 1 ("Average H" / "Average gray value"): go to Setting1
            if isempty(app.LoadedImage), return; end
            if ~app.confirmDefaults(app.ODmmEditField.Value == 9.5 && app.aEditField.Value == 0.9107)
                return;
            end

            app.setButtonState([app.AveragegrayvalueButton, app.AverageHButton, app.ContourButton], false);
            updateSettings(app);
            app.Grayaverage = grayMode;

            app.clearAnalysis();
            app.deleteHandles(app.BlueDotHandles); app.BlueDotHandles = [];
            app.deleteHandles(app.RedDotHandles);  app.RedDotHandles = [];
            app.SelectedPoints_in = []; app.SelectedPoints_out = [];
            app.ViewRange = [];

            app.TabGroup.SelectedTab = app.Setting1Tab;

            % Setup axes for analysis
            imshow(app.LoadedImage, 'Parent', app.UIAxes_2);
            axis(app.UIAxes_2, 'normal');
            axis(app.UIAxes_2, 'tight');

            app.UIAxes_2.XTick = [];
            app.UIAxes_2.YTick = [];
            app.UIAxes_2.XLabel.String = '';
            app.UIAxes_2.YLabel.String = '';

            app.UIAxes_2.Title.String = app.filename;
            app.UIAxes_2.Title.Interpreter = 'none';
            app.UIAxes_2.Title.Visible = 'on';
            box(app.UIAxes_2, 'on');

            % Highlight next step
            app.setButtonState(app.AutoDetectBoundariesButton, true);
        end

        function markPoints(app, type)
            % Manual fit: mark 3 points on the inner ('in') or outer ('out') surface
            if isempty(app.LoadedImage), return; end
            if app.Calc_done
                app.clearAnalysis();
            end

            % Save current zoom state
            currentXLim = app.UIAxes_2.XLim;
            currentYLim = app.UIAxes_2.YLim;

            % Remove existing dots of this type
            if strcmp(type, 'in')
                app.deleteHandles(app.BlueDotHandles); app.BlueDotHandles = [];
                app.SelectedPoints_in = [];
            else
                app.deleteHandles(app.RedDotHandles); app.RedDotHandles = [];
                app.SelectedPoints_out = [];
            end

            % Remove existing fitting results (the old fit is no longer valid)
            app.deleteHandles(app.FitCircleHandles);
            app.FitCircleHandles = [];
            allLines = findobj(app.UIAxes_2, 'Type', 'line');
            if ~isempty(allLines), delete(allLines); end
            app.Fit_done = 0;
            app.Fit_result = [];
            app.GenerateProfileButton.Enable = 'off';
            app.GenerateProfileButton.BackgroundColor = app.COLOR_IDLE;

            % Restore zoom state
            app.UIAxes_2.XLim = currentXLim;
            app.UIAxes_2.YLim = currentYLim;

            app.setButtonState(app.AutoDetectBoundariesButton, false);
            [pts, h] = app.selectPoints(app.UIAxes_2, type);
            if isempty(pts), return; end
            if strcmp(type, 'in')
                app.SelectedPoints_in = pts;  app.BlueDotHandles = h;
            else
                app.SelectedPoints_out = pts; app.RedDotHandles = h;
            end
        end

        function markContourPoints(app, type)
            % Manual fit on Setting 2: mark 3 points on the inner/outer surface (UIAxes_3)
            if isempty(app.LoadedImage), return; end
            if isempty(findobj(app.UIAxes_3, 'Type', 'image'))
                uialert(app.UIFigure, 'Please press "Contour" on the Input tab first.', 'Error');
                return;
            end

            % Remove existing dots of this type and the previous fit
            if strcmp(type, 'in')
                app.deleteHandles(app.ContourBlueDotHandles); app.ContourBlueDotHandles = [];
                app.ContourPoints_in = [];
            else
                app.deleteHandles(app.ContourRedDotHandles); app.ContourRedDotHandles = [];
                app.ContourPoints_out = [];
            end
            app.clearContourFit();

            [pts, h] = app.selectPoints(app.UIAxes_3, type);
            if isempty(pts), return; end
            if strcmp(type, 'in')
                app.ContourPoints_in = pts;  app.ContourBlueDotHandles = h;
            else
                app.ContourPoints_out = pts; app.ContourRedDotHandles = h;
            end
            if ~isempty(app.ContourPoints_in) && ~isempty(app.ContourPoints_out)
                app.setButtonState(app.FitBoundariesButton_2, true);
            end
        end

        function clearContourFit(app)
            % Drop the manual fit on Setting 2 (back to automatic fitting)
            app.deleteHandles(app.ContourFitCircleHandles);
            app.ContourFitCircleHandles = [];
            app.ContourManualFit = false;
            app.isManualRange = false;
            app.setButtonState(app.FitBoundariesButton_2, false);
        end

        function clearContourPoints(app)
            app.deleteHandles(app.ContourBlueDotHandles); app.ContourBlueDotHandles = [];
            app.deleteHandles(app.ContourRedDotHandles);  app.ContourRedDotHandles = [];
            app.ContourPoints_in = []; app.ContourPoints_out = [];
            app.clearContourFit();
        end

        function drawContourFit(app)
            % Draw the fit circles on UIAxes_3, keeping the view on the image
            app.deleteHandles(app.ContourFitCircleHandles);
            c = app.ContourFit(1:2); Ri = app.ContourFit(3); Ro = app.ContourFit(4);
            theta = linspace(0, 2*pi, 720);
            hold(app.UIAxes_3, 'on');
            app.ContourFitCircleHandles = [ ...
                plot(app.UIAxes_3, c(1)+Ri*cos(theta), c(2)+Ri*sin(theta), 'b-', 'LineWidth', 1.5), ...
                plot(app.UIAxes_3, c(1)+Ro*cos(theta), c(2)+Ro*sin(theta), 'r-', 'LineWidth', 1.5), ...
                plot(app.UIAxes_3, c(1), c(2), 'kx', 'MarkerSize', 10)];
            hold(app.UIAxes_3, 'off');

            % Lock the view to the image area (circles may extend beyond it)
            [imgH, imgW, ~] = size(app.LoadedImage);
            app.UIAxes_3.XLim = [0.5, imgW + 0.5];
            app.UIAxes_3.YLim = [0.5, imgH + 0.5];
            app.UIAxes_3.XLimMode = 'manual';
            app.UIAxes_3.YLimMode = 'manual';
        end

        function ok = selectContourROI(app)
            % Rectangular ROI on Setting 2 with preview (used by "Select the ROI"
            % and "Reselect ROI")
            ok = false;
            if ~isempty(app.ContourCropHandles)
                delete(app.ContourCropHandles(isvalid(app.ContourCropHandles)));
            end
            app.isManualRange = false;      % a new ROI starts with automatic boundaries

            im = app.LoadedImage;
            h = drawrectangle(app.UIAxes_3);
            app.ContourCropHandles = h;

            % ROI position [xmin, ymin, width, height]
            pos = h.Position;
            if isempty(pos) || pos(3) <= 0 || pos(4) <= 0
                uialert(app.UIFigure, 'Please select a valid ROI area.', 'Error');
                return;
            end
            minC = round(pos(1)); maxC = round(pos(1) + pos(3));
            minR = round(pos(2)); maxR = round(pos(2) + pos(4));

            % Check data boundaries to prevent out-of-bounds errors
            [imgH, imgW, ~] = size(im);
            minR = max(1, minR); maxR = min(imgH, maxR);
            minC = max(1, minC); maxC = min(imgW, maxC);
            app.SaveRange = [minR, maxR, minC, maxC];

            % Circle fit shown with the ROI: the manual fit if present,
            % otherwise the automatic fit (the same one "Get contour map" uses)
            if ~app.ContourManualFit
                app.ContourFit = app.autoFitCircles(im);
            end
            if ~isempty(app.ContourFit)
                app.drawContourFit();
            end

            % Display cropped preview on the right axes (in image coordinates,
            % so the fitted circles can be overlaid)
            cropped_preview = im(minR:maxR, minC:maxC, :);
            cla(app.UIAxes_4);
            imagesc(app.UIAxes_4, [minC maxC], [minR maxR], cropped_preview);
            if size(im, 3) == 1
                colormap(app.UIAxes_4, 'gray');
            end
            axis(app.UIAxes_4, 'image');
            set(app.UIAxes_4, 'YDir', 'reverse');
            app.UIAxes_4.XLim = [minC, maxC]; app.UIAxes_4.YLim = [minR, maxR];
            app.UIAxes_4.XTick = []; app.UIAxes_4.YTick = [];
            if ~isempty(app.ContourFit)
                c = app.ContourFit(1:2); theta = linspace(0, 2*pi, 720);
                hold(app.UIAxes_4, 'on');
                plot(app.UIAxes_4, c(1)+app.ContourFit(3)*cos(theta), c(2)+app.ContourFit(3)*sin(theta), 'b-', 'LineWidth', 1.5);
                plot(app.UIAxes_4, c(1)+app.ContourFit(4)*cos(theta), c(2)+app.ContourFit(4)*sin(theta), 'r-', 'LineWidth', 1.5);
                hold(app.UIAxes_4, 'off');
                if app.ContourManualFit, fitStr = 'manual fit'; else, fitStr = 'auto fit'; end
                title(app.UIAxes_4, ['Selected ROI Preview (', fitStr, ')']);
            else
                title(app.UIAxes_4, 'Selected ROI Preview (no fit found)');
            end
            ok = true;
        end
    end


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

        % Code that executes after component creation
        function startupFcn(app)
            % Initialize UI axes styling
            app.UIAxes.XTick = [];
            app.UIAxes.YTick = [];
            app.UIAxes.XLabel.String = '';
            app.UIAxes.YLabel.String = '';
            app.UIAxes.Title.String = '';

            % Configure white theme for axes
            app.UIAxes.Box = 'on';
            app.UIAxes.XColor = [1 1 1];
            app.UIAxes.YColor = [1 1 1];
            app.UIAxes.BackgroundColor = [1 1 1];

            app.ScalebarlengthEditField.Value = 100;
            app.LineWidthpixelEditField.Enable = 'off';

            % Analysis buttons are enabled once an image is loaded
            app.AverageHButton.Enable = 'off';
            app.ContourButton.Enable = 'off';
            app.AveragegrayvalueButton.Enable = 'off';
            app.GenerateProfileButton.Enable = 'off';
            app.GetcontourmapButton.Enable = 'off';

            app.setButtonState(app.LoadfileButton, true);
        end

        % Button pushed function: LoadfileButton
        function LoadfileButtonPushed(app, event)
            [file, path] = uigetfile('*.tif');
            if isequal(file,0), return; end
            app.filename = file;
            im = imread(fullfile(path, file));
            app.LoadedImage = cleanInf(im);

            % A new image invalidates all previous results
            app.clearAnalysis();
            app.ViewRange = []; app.SaveRange = []; app.ContourFit = [];
            app.isManualRange = false; app.last_line_pos = [];
            app.current_ri_px = []; app.current_ro_px = [];
            app.clearContourPoints();

            imshow(app.LoadedImage, 'Parent', app.UIAxes);
            axis(app.UIAxes, 'normal');
            axis(app.UIAxes, 'tight');

            app.UIAxes.XTick = [];
            app.UIAxes.YTick = [];
            app.UIAxes.XLabel.String = '';
            app.UIAxes.YLabel.String = '';
            box(app.UIAxes, 'on');
            title(app.UIAxes, file, 'Interpreter', 'none');

            if ~isempty(app.LoadedImage)
                app.setButtonState(app.LoadfileButton, false);

                app.AverageHButton.Enable = 'on';
                app.ContourButton.Enable = 'on';
                app.AveragegrayvalueButton.Enable = 'on';
                app.setButtonState([app.AverageHButton, app.ContourButton], true);
            end
        end

        % Button pushed function: AveragegrayvalueButton
        function AveragegrayvalueButtonPushed(app, event)
            app.startProfileAnalysis(true);
        end

        % Button pushed function: AverageHButton
        function AverageHButtonPushed(app, event)
            app.startProfileAnalysis(false);
        end

        % Button pushed function: ContourButton
        function ContourButtonPushed(app, event)
            if isempty(app.LoadedImage)
                uialert(app.UIFigure, 'No image loaded.', 'Error');
                return;
            end

            OD = app.ODmmEditField.Value;
            Thickness = app.ThicknessmmEditField.Value;
            a = app.aEditField.Value;
            b = app.bEditField.Value;
            pixel = app.pixelumEditField.Value;
            if ~app.confirmDefaults(OD == 9.5 && Thickness == 0.57 && a == 0.9107 && b == 0.0001 && pixel == 2.7)
                return;
            end

            app.setButtonState([app.AverageHButton, app.ContourButton], false);
            updateSettings(app);

            app.TabGroup.SelectedTab = app.Setting2Tab;

            im = app.LoadedImage;
            app.SelecttheROIButton.Enable = 'on';
            app.setButtonState(app.SelecttheROIButton, true);

            app.GetcontourmapButton.Enable = 'off';
            app.GetcontourmapButton.BackgroundColor = app.COLOR_IDLE;

            app.clearContourPoints();
            imshow(im, 'Parent', app.UIAxes_3);
            title(app.UIAxes_3, app.filename, 'Interpreter', 'none', 'FontWeight', 'bold');
            axis(app.UIAxes_3, 'image');
            set(app.UIAxes_3, 'XTick', [], 'YTick', [], 'Box', 'off', 'XColor', 'none', 'YColor', 'none');

            set(app.UIAxes_4, 'XTick', [], 'YTick', [], 'Box', 'off', 'XColor', 'none', 'YColor', 'none');
            xlabel(app.UIAxes_4, ''); ylabel(app.UIAxes_4, '');

            set(app.UIAxes_2, 'XTick', [], 'YTick', [], 'XColor', 'none', 'YColor', 'none');
        end

        % Button pushed function: RedrawButton
        function RedrawButtonPushed(app, event)
            % Clear existing analysis and restart ROI cropping
            if isempty(app.LoadedImage), return; end
            if app.Calc_done
                app.clearAnalysis();
            end
            imshow(app.LoadedImage, 'Parent', app.UIAxes_2);
            app.ViewRange = [];
            app.doCrop();
        end

        % Button pushed function: SelectAreaButton
        function SelectAreaButtonPushed(app, event)
            if isempty(app.LoadedImage), return; end
            app.clearAnalysis();
            app.ViewRange = [];
            app.doCrop();
        end

        % Button pushed function: MarkInner3PointsButton
        function MarkInner3PointsButtonPushed(app, event)
            app.markPoints('in');
        end

        % Button pushed function: MarkOuter3PointsButton
        function MarkOuter3PointsButtonPushed(app, event)
            app.markPoints('out');
        end

        % Button pushed function: ResetinnerButton
        function ResetinnerButtonPushed(app, event)
            app.markPoints('in');
        end

        % Button pushed function: ResetouterButton
        function ResetouterButtonPushed(app, event)
            app.markPoints('out');
        end

        % Button pushed function: FitBoundariesButton
        function FitBoundariesButtonPushed(app, event)
            if app.Calc_done
                app.clearAnalysis();
            end

            % 1. Verify point selection
            if isempty(app.SelectedPoints_in) || isempty(app.SelectedPoints_out)
                uialert(app.UIFigure, 'Select points first', 'Error'); return;
            end
            updateSettings(app);

            % 2. Store current zoom state (ROI area)
            targetXLim = app.UIAxes_2.XLim;
            targetYLim = app.UIAxes_2.YLim;

            % 3. Remove existing fitting lines
            app.deleteHandles(app.FitCircleHandles);
            app.FitCircleHandles = [];

            % 4. Calculate fitting
            [center, R1, R2] = fit_two_circles_same_center(app.SelectedPoints_in, app.SelectedPoints_out);
            R_sorted = sort([R1, R2]);
            Ri = R_sorted(1); Ro = R_sorted(2);

            % 5. Draw fitted circles
            hold(app.UIAxes_2, 'on');
            theta = linspace(0, 2*pi, 360);
            app.FitCircleHandles(1) = plot(app.UIAxes_2, center(1)+Ri*cos(theta), center(2)+Ri*sin(theta), 'b-', 'LineWidth', 1.5);
            app.FitCircleHandles(2) = plot(app.UIAxes_2, center(1)+Ro*cos(theta), center(2)+Ro*sin(theta), 'r-', 'LineWidth', 1.5);
            app.FitCircleHandles(3) = plot(app.UIAxes_2, center(1), center(2), 'kx', 'MarkerSize', 10);

            % 6. Finalize axis scaling and zoom
            axis(app.UIAxes_2, 'image');
            app.UIAxes_2.XLim = targetXLim;
            app.UIAxes_2.YLim = targetYLim;
            app.UIAxes_2.XLimMode = 'manual';
            app.UIAxes_2.YLimMode = 'manual';

            hold(app.UIAxes_2, 'off');

            % 7. Save result and enable calculation button
            app.Fit_result = [center, Ri, Ro];
            app.Fit_done = 1;
            app.GenerateProfileButton.Enable = 'on';
            app.setButtonState(app.GenerateProfileButton, true);
        end

        % Button pushed function: AutoDetectBoundariesButton
        function AutoDetectBoundariesButtonPushed(app, event)
            % Clear previous analysis results if calculation is already done
            if app.Calc_done
                app.clearAnalysis();
            end

            % 1. Check if an image is loaded
            if isempty(app.LoadedImage)
                uialert(app.UIFigure, 'Please load a TIFF file first.', 'Warning'); return;
            end
            updateSettings(app);

            % 2. Clean up manual input handles and data
            app.deleteHandles(app.BlueDotHandles); app.BlueDotHandles = [];
            app.deleteHandles(app.RedDotHandles);  app.RedDotHandles = [];
            app.deleteHandles(app.FitCircleHandles); app.FitCircleHandles = [];
            app.SelectedPoints_in = []; app.SelectedPoints_out = [];

            % 3. Automatic fitting on the full loaded image
            inputImage = app.LoadedImage;
            fit = app.autoFitCircles(inputImage);

            if ~isempty(fit)
                app.Fit_result = fit;
                app.Fit_done = 1;

                % 4. Visualize the fitting result
                app.visualizeFit(inputImage, app.UIAxes_2);

                % 5. Maintain the zoom area if previously set
                if ~isempty(app.ViewRange)
                    app.UIAxes_2.XLim = [app.ViewRange(3), app.ViewRange(4)];
                    app.UIAxes_2.YLim = [app.ViewRange(1), app.ViewRange(2)];
                end

                % 6. Update button states
                app.AutoDetectBoundariesButton.BackgroundColor = app.COLOR_IDLE;
                app.GenerateProfileButton.Enable = 'on';
                app.setButtonState(app.GenerateProfileButton, true);
            else
                app.Fit_done = 0;
                uialert(app.UIFigure, 'Could not detect boundaries. Try Manual Fit.', 'Warning');
                app.GenerateProfileButton.Enable = 'off';
            end
        end

        % Button pushed function: GenerateProfileButton
        function GenerateProfileButtonPushed(app, event)
            % Safety check: ensure fitting is complete
            if app.Fit_done ~= 1 || isempty(app.Fit_result)
                uialert(app.UIFigure, 'Please complete the fitting process first.', 'Error');
                app.GenerateProfileButton.Enable = 'off';
                app.GenerateProfileButton.BackgroundColor = app.COLOR_IDLE;
                return;
            end
            updateSettings(app);

            % 1. Prepare image and data for calculation
            img = app.LoadedImage;
            [Tics, Average_profile] = radial_profile(img, 1, app.Fit_result(1), app.Fit_result(2));
            if isempty(Tics), return; end

            Tics = Tics(:); Average_profile = Average_profile(:);
            pixel_um = app.pixeltolength;
            x_v = Tics * pixel_um;
            H_v = -log(max(Average_profile, eps) / app.calibration(1)) / app.calibration(2);

            if app.Grayaverage
                y_v = Average_profile; unit_str = '(-)'; y_lab = 'Transmission (-)';
            else
                y_v = H_v; unit_str = 'wppm'; y_lab = 'H concentration (wppm)';
            end

            % 2. Wall boundaries. Always detected on the H profile (H peaks at the
            %    wall surfaces), also in gray-value mode.
            [Ri_final, Ro_final, xLimits] = app.detectWallBoundaries(x_v, H_v, ...
                app.Fit_result(3) * pixel_um, app.Fit_result(4) * pixel_um);
            if isempty(Ri_final) || Ro_final <= Ri_final
                uialert(app.UIFigure, 'Could not locate the wall on the radial profile.', 'Error');
                return;
            end

            app.TabGroup.SelectedTab = app.RadialprofileandEntireviewTab;
            app.Radial_data = [x_v, y_v];
            app.isLocalProfile = false;

            % 3. Final calculations
            mask = (x_v >= Ri_final) & (x_v <= Ro_final);
            Total_average = mean(y_v(mask));
            cladding_thickness_um = abs(Ro_final - Ri_final);

            avg_text = sprintf('Avg: %.2f %s', Total_average, unit_str);
            thickness_text = sprintf('Width: %.1f um', cladding_thickness_um);

            % --- Update profile plot (UIAxes3) ---
            % Remove existing plot objects only (preserve axis settings)
            delete(app.UIAxes3.Children);
            hold(app.UIAxes3, 'on');

            plot(app.UIAxes3, x_v, y_v, 'k-', 'LineWidth', 1.5);
            xline(app.UIAxes3, Ri_final, '--r', 'LineWidth', 1.5);
            xline(app.UIAxes3, Ro_final, '--r', 'LineWidth', 1.5);

            % Set grid/box directly (the 'grid on' command does not always persist here)
            app.UIAxes3.XGrid = 'on';
            app.UIAxes3.YGrid = 'on';
            app.UIAxes3.Box = 'on';

            % Axis limits must be reassigned for every new image
            app.UIAxes3.XLim = xLimits;

            y_min = min(y_v); y_max = max(y_v);
            y_range = y_max - y_min;
            if y_range == 0, y_range = 1; end
            app.UIAxes3.YLim = [y_min - y_range*0.05, y_max + y_range*0.2];

            % Tick mode 'auto' forces tick labels to refresh with new data
            app.UIAxes3.XTickMode = 'auto';
            app.UIAxes3.YTickMode = 'auto';

            % Text annotations and labels
            mid_y = app.UIAxes3.YLim(1) + (app.UIAxes3.YLim(2) - app.UIAxes3.YLim(1)) * 0.92;
            text(app.UIAxes3, (Ri_final+Ro_final)/2, mid_y, thickness_text, ...
                'HorizontalAlignment', 'center', 'Color', 'r', 'FontWeight', 'bold', 'FontSize', 11);

            xlabel(app.UIAxes3, ['Radial distance (um)  [', thickness_text, ']']);
            ylabel(app.UIAxes3, y_lab);
            title(app.UIAxes3, ['Radial Profile (', avg_text, ')']);

            hold(app.UIAxes3, 'off');

            % --- Update image view (UIAxes4) ---
            cla(app.UIAxes4);
            imshow(img, 'Parent', app.UIAxes4);
            [h, w, ~] = size(img);
            app.UIAxes4.XLim = [0.5, w + 0.5];
            app.UIAxes4.YLim = [0.5, h + 0.5];
            hold(app.UIAxes4, 'on');
            center = app.Fit_result(1:2); theta = linspace(0, 2*pi, 800);
            plot(app.UIAxes4, center(1)+(Ri_final/pixel_um)*cos(theta), center(2)+(Ri_final/pixel_um)*sin(theta), 'r--', 'LineWidth', 1.5);
            plot(app.UIAxes4, center(1)+(Ro_final/pixel_um)*cos(theta), center(2)+(Ro_final/pixel_um)*sin(theta), 'r--', 'LineWidth', 1.5);
            title(app.UIAxes4, ['Analysis Area (', thickness_text, ')']);
            hold(app.UIAxes4, 'off');

            app.Calc_done = true;
            app.LineWidthpixelEditField.Enable = 'off';
            app.setButtonState(app.GenerateProfileButton, false);
        end

        % Button pushed function: ManuallyselectthecladdingregionButton
        function ManuallyselectthecladdingregionButtonPushed(app, event)
            % Profile currently shown on UIAxes3
            lineObj = findobj(app.UIAxes3, 'Type', 'line', '-and', 'LineStyle', '-');
            if app.isLocalProfile && ~isempty(lineObj)
                x_v = lineObj(1).XData(:);
                y_v = lineObj(1).YData(:);
            elseif ~isempty(app.Radial_data)
                x_v = app.Radial_data(:, 1);
                y_v = app.Radial_data(:, 2);
            else
                uialert(app.UIFigure, 'Please run calculation or get radial profile first.', 'Error');
                return;
            end

            % Clear existing visualization elements
            delete(findobj(app.UIAxes3, 'Type', 'ConstantLine'));
            delete(findobj(app.UIAxes3, 'Type', 'Text'));

            % Guidance message
            app.UIAxes3.Title.String = 'Click TWO points on the graph';
            app.UIAxes3.Title.Color = [1 0 0];

            % Get user input for two points
            p1 = drawpoint(app.UIAxes3, 'Color', 'r');
            x1 = p1.Position(1);
            p2 = drawpoint(app.UIAxes3, 'Color', 'r');
            x2 = p2.Position(1);
            delete(p1); delete(p2);

            pixel_um = app.pixeltolength;
            manual_range = [min(x1, x2), max(x1, x2)];
            mask = x_v >= manual_range(1) & x_v <= manual_range(2);

            if any(mask)
                % Average concentration and width
                Total_average = mean(y_v(mask), 'omitnan');
                cladding_thickness_um = abs(x2 - x1);

                % Update UIAxes3
                hold(app.UIAxes3, 'on');
                xline(app.UIAxes3, x1, '--r', 'LineWidth', 1.5);
                xline(app.UIAxes3, x2, '--r', 'LineWidth', 1.5);

                thickness_text = sprintf('Width: %.1f um', cladding_thickness_um);
                y_limits = app.UIAxes3.YLim;
                mid_y = y_limits(1) + (y_limits(2) - y_limits(1)) * 0.92;
                mid_x = mean(manual_range);

                text(app.UIAxes3, mid_x, mid_y, thickness_text, ...
                    'HorizontalAlignment', 'center', 'Color', 'r', 'FontWeight', 'bold', 'FontSize', 11);

                unit = 'wppm';
                if app.Grayaverage && ~app.isLocalProfile, unit = '(-)'; end

                avg_text = sprintf('Manual Avg: %.2f %s', Total_average, unit);
                app.UIAxes3.Title.String = [avg_text, ' (', thickness_text, ')'];
                app.UIAxes3.Title.Color = [0 0 0];
                hold(app.UIAxes3, 'off');

                % Update UIAxes4
                delete(findobj(app.UIAxes4, 'Type', 'line'));
                hold(app.UIAxes4, 'on');

                if app.isLocalProfile && ~isempty(app.last_line_pos)
                    center = app.ContourFit(1:2);
                    if ~isempty(app.SaveRange)
                        r = app.SaveRange;
                        app.UIAxes4.XLim = [r(3), r(4)];
                        app.UIAxes4.YLim = [r(1), r(2)];
                    end

                    num_samples = round(app.LineWidthpixelEditField.Value);
                    if num_samples < 1, num_samples = 1; end

                    pos = app.last_line_pos;
                    midX = mean(pos(:, 1)); midY = mean(pos(:, 2));
                    targetAngle = atan2(midY - center(2), midX - center(1));

                    angleRange = num_samples / app.current_ro_px;
                    theta_min = targetAngle - angleRange/2;
                    theta_max = targetAngle + angleRange/2;

                    Ri_px_manual = manual_range(1) / pixel_um;
                    Ro_px_manual = manual_range(2) / pixel_um;

                    X_rect = center(1) + [Ri_px_manual*cos(theta_min), Ro_px_manual*cos(theta_min), ...
                        Ro_px_manual*cos(theta_max), Ri_px_manual*cos(theta_max), Ri_px_manual*cos(theta_min)];
                    Y_rect = center(2) + [Ri_px_manual*sin(theta_min), Ro_px_manual*sin(theta_min), ...
                        Ro_px_manual*sin(theta_max), Ri_px_manual*sin(theta_max), Ri_px_manual*sin(theta_min)];

                    plot(app.UIAxes4, X_rect, Y_rect, 'r-', 'LineWidth', 1.5);
                    title(app.UIAxes4, ['Manual Range (Sector): ', thickness_text]);
                else
                    center = app.Fit_result(1:2);
                    [h, w, ~] = size(app.LoadedImage);
                    app.UIAxes4.XLim = [0.5, w + 0.5];
                    app.UIAxes4.YLim = [0.5, h + 0.5];

                    theta = linspace(0, 2*pi, 500);
                    plot(app.UIAxes4, center(1) + (manual_range(1)/pixel_um)*cos(theta), ...
                        center(2) + (manual_range(1)/pixel_um)*sin(theta), 'r--', 'LineWidth', 1.2);
                    plot(app.UIAxes4, center(1) + (manual_range(2)/pixel_um)*cos(theta), ...
                        center(2) + (manual_range(2)/pixel_um)*sin(theta), 'r--', 'LineWidth', 1.2);

                    title(app.UIAxes4, ['Manual Range (Circles): ', thickness_text]);
                end

                hold(app.UIAxes4, 'off');
            end
        end

        % Button pushed function: ExporttoexcelButton
        function ExporttoexcelButtonPushed(app, event)
            % 1. Profile currently shown on UIAxes3 and its boundaries (xlines)
            lineObj = findobj(app.UIAxes3, 'Type', 'line', '-and', 'LineStyle', '-');
            boundaryObjs = findobj(app.UIAxes3, 'Type', 'ConstantLine');

            if app.isLocalProfile && ~isempty(lineObj)
                dist = lineObj(1).XData(:);
                val = lineObj(1).YData(:);
            elseif ~isempty(app.Radial_data)
                dist = app.Radial_data(:, 1);
                val = app.Radial_data(:, 2);
            else
                uialert(app.UIFigure, 'No data to export. Please generate a profile first.', 'Error');
                return;
            end

            % 2. Create the table
            colName = 'H_concentration_wppm';
            if app.Grayaverage && ~app.isLocalProfile
                colName = 'Transmission_ratio';
            end
            tbl = table(dist, val, 'VariableNames', {'Distance_um', colName});

            % 3. Boundary info in the 3rd column
            boundaries = cell(height(tbl), 1);
            if ~isempty(boundaryObjs)
                b_values = [boundaryObjs.Value];
                boundaries{1} = sprintf('Inner Boundary: %.2f', min(b_values));
                boundaries{2} = sprintf('Outer Boundary: %.2f', max(b_values));
            end
            tbl.Boundary_Info = boundaries;

            % 4. Save to Excel
            [file, path] = uiputfile('*.xlsx', 'Save to Excel');
            if isequal(file, 0), return; end

            try
                writetable(tbl, fullfile(path, file), 'WriteMode', 'replacefile');
                uialert(app.UIFigure, 'Data exported with boundaries successfully.', 'Success');
            catch ME
                uialert(app.UIFigure, ['Failed to save: ', ME.message], 'Error');
            end
        end

        % Button pushed function: SelecttheROIButton
        function SelecttheROIButtonPushed(app, event)
            if isempty(app.LoadedImage)
                uialert(app.UIFigure, 'Please load an image first.', 'Error');
                return;
            end

            % Update button states
            app.GetcontourmapButton.Enable = 'off';
            app.setButtonState(app.GetcontourmapButton, false);
            app.SelecttheROIButton.BackgroundColor = app.COLOR_IDLE;
            app.SelecttheROIButton.FontWeight = 'bold';

            if ~app.selectContourROI(), return; end

            % Enable and highlight next step
            app.setButtonState(app.SelecttheROIButton, false);
            app.GetcontourmapButton.Enable = 'on';
            app.setButtonState(app.GetcontourmapButton, true);
        end

        % Button pushed function: MarkInner3PointsButton_2
        function MarkInner3PointsButton_2Pushed(app, event)
            app.markContourPoints('in');
        end

        % Button pushed function: MarkOuter3PointsButton_2
        function MarkOuter3PointsButton_2Pushed(app, event)
            app.markContourPoints('out');
        end

        % Button pushed function: FitBoundariesButton_2
        function FitBoundariesButton_2Pushed(app, event)
            % Manual concentric-circle fit for the contour map (Setting 2)
            if isempty(app.ContourPoints_in) || isempty(app.ContourPoints_out)
                uialert(app.UIFigure, 'Mark 3 inner and 3 outer points first.', 'Error'); return;
            end
            updateSettings(app);

            [center, R1, R2] = fit_two_circles_same_center(app.ContourPoints_in, app.ContourPoints_out);
            R_sorted = sort([R1, R2]);
            app.ContourFit = [center, R_sorted(1), R_sorted(2)];
            app.ContourManualFit = true;
            app.isManualRange = false;      % wall boundaries are re-detected from this fit
            app.drawContourFit();

            app.setButtonState(app.FitBoundariesButton_2, false);
            if ~isempty(app.SaveRange)
                app.GetcontourmapButton.Enable = 'on';
                app.setButtonState(app.GetcontourmapButton, true);
            else
                app.setButtonState(app.SelecttheROIButton, true);
            end
        end

        % Button pushed function: GetcontourmapButton
        function GetcontourmapButtonPushed(app, event)
            app.setButtonState(app.GetcontourmapButton, false);

            % 1. Preliminary checks
            if isempty(app.LoadedImage)
                uialert(app.UIFigure, 'Please load an image first.', 'Error'); return;
            end
            if isempty(app.SaveRange)
                uialert(app.UIFigure, 'Please select a Rectangle ROI first.', 'Error'); return;
            end
            updateSettings(app);
            inputImage = app.LoadedImage;
            a = app.calibration(1); b = app.calibration(2);
            pixel_um = app.pixeltolength;

            % 2. Wall boundaries: automatic unless refined manually.
            %    The circle fit is the 3-point manual fit from Setting 2 when
            %    available, otherwise automatic.
            if ~app.isManualRange
                if app.ContourManualFit && ~isempty(app.ContourFit)
                    fit = app.ContourFit;
                else
                    fit = app.autoFitCircles(inputImage);
                    if isempty(fit)
                        uialert(app.UIFigure, 'Could not detect tube boundaries. Try the Manual Fit on Setting 2.', 'Warning'); return;
                    end
                end
                app.ContourFit = fit;

                [Tics, Average_profile] = radial_profile(inputImage, 1, fit(1), fit(2));
                x_v = Tics(:) * pixel_um;
                y_v = -log(max(Average_profile(:), eps) / a) / b;
                [Ri_um, Ro_um] = app.detectWallBoundaries(x_v, y_v, fit(3) * pixel_um, fit(4) * pixel_um);
                if isempty(Ri_um) || Ro_um <= Ri_um
                    uialert(app.UIFigure, 'Could not locate the wall on the radial profile.', 'Error'); return;
                end
                app.current_ri_px = Ri_um / pixel_um;
                app.current_ro_px = Ro_um / pixel_um;
            end
            ri_px = app.current_ri_px;
            ro_px = app.current_ro_px;

            % 3. Concentration map
            cx = app.ContourFit(1); cy = app.ContourFit(2);
            [rows, cols] = size(inputImage);
            [X, Y] = meshgrid(1:cols, 1:rows);
            dist_map = sqrt((X - cx).^2 + (Y - cy).^2);
            H_full = -log(max(double(inputImage), eps)/a)/b;

            % 4. ROI clipping and wall masking
            wall_mask = (dist_map >= ri_px) & (dist_map <= ro_px);
            r = app.SaveRange;
            H_masked = H_full;
            H_masked(~wall_mask) = NaN;
            H_final = H_masked(r(1):r(2), r(3):r(4));

            % 5. Tab transition and visualization
            app.TabGroup.SelectedTab = app.ContourmapTab;

            % Remove outliers and prepare visualization data
            H_viz = H_final;
            H_viz(isinf(H_viz)) = NaN;

            valid_values = H_viz(~isnan(H_viz));
            if isempty(valid_values)
                display_range = [0 10];
            else
                upper_cutoff = quantile(valid_values, 0.995);
                H_viz(H_viz > upper_cutoff) = upper_cutoff;
                display_range = [0, quantile(valid_values, 0.98)];
            end
            if display_range(2) <= display_range(1), display_range(2) = display_range(1) + 1; end

            % --- UIAxes_5: Raw hydride map ---
            cla(app.UIAxes_5);
            s5 = surf(app.UIAxes_5, r(3):r(4), r(1):r(2), zeros(size(H_final))-1, H_final);

            set(s5, 'edgecolor', 'none'); colormap(app.UIAxes_5, 'turbo');
            view(app.UIAxes_5, 2);
            set(app.UIAxes_5, 'YDir', 'reverse', 'CLim', display_range);
            set(app.UIAxes_5, 'XTick', [], 'YTick', [], 'Box', 'off', 'XColor', 'none', 'YColor', 'none');

            cb5 = colorbar(app.UIAxes_5);
            ylabel(cb5, 'Concentration (wppm)', 'FontSize', 11, 'FontWeight', 'normal');

            axis(app.UIAxes_5, 'image');
            app.UIAxes_5.XLim = [r(3), r(4)]; app.UIAxes_5.YLim = [r(1), r(2)];
            title(app.UIAxes_5, ['Hydride Map (Raw), Avg: ', num2str(mean(valid_values, 'omitnan'), '%.1f'), ' wppm'], ...
                'FontWeight', 'bold');

            % --- UIAxes_6: Smoothed contour ---
            cla(app.UIAxes_6);
            H_temp = H_viz;

            % Logical mask of all non-NaN data regions
            raw_mask = ~isnan(H_temp);
            full_mask = imfill(raw_mask, 'holes');

            % Clamp negative values to zero and fill missing values
            H_filled = H_temp;
            H_filled(H_filled < 0) = 0;
            H_filled = fillmissing(H_filled, 'nearest');

            % Gaussian smoothing
            sigma_val = 1.6;
            k_size = 13;
            kernel = fspecial('gaussian', [k_size k_size], sigma_val);
            H_smooth = conv2(H_filled, kernel, 'same');

            % Apply final mask to smoothed data
            H_smooth(~full_mask) = NaN;

            levels = linspace(display_range(1), display_range(2), 100);
            [~, h6] = contourf(app.UIAxes_6, r(3):r(4), r(1):r(2), H_smooth, levels);
            set(h6, 'edgecolor', 'none');
            colormap(app.UIAxes_6, 'turbo');
            set(app.UIAxes_6, 'YDir', 'reverse', 'CLim', display_range);

            set(app.UIAxes_6, 'XTick', [], 'YTick', [], 'Box', 'off', 'XColor', 'none', 'YColor', 'none');
            cb6 = colorbar(app.UIAxes_6);
            ylabel(cb6, 'Concentration (wppm)', 'FontSize', 11);

            axis(app.UIAxes_6, 'image');
            app.UIAxes_6.XLim = [r(3), r(4)];
            app.UIAxes_6.YLim = [r(1), r(2)];

            title(app.UIAxes_6,  ['Hydride Distribution (Smoothed), Avg: ', num2str(mean(valid_values, 'omitnan'), '%.1f'), ' wppm'], ...
                'FontWeight', 'bold');
            app.updateScaleBar();
        end

        % Button pushed function: ReselectROIButton
        function ReselectROIButtonPushed(app, event)
            im = app.LoadedImage;
            if isempty(im)
                uialert(app.UIFigure, 'Please load an image first.', 'Error'); return;
            end
            app.TabGroup.SelectedTab = app.Setting2Tab;
            app.GetcontourmapButton.Enable = 'off';
            app.setButtonState(app.GetcontourmapButton, false);

            % Reset UIAxes_3 view to show full image
            cla(app.UIAxes_4);
            [imgH, imgW, ~] = size(im);
            app.UIAxes_3.XLim = [0.5, imgW + 0.5];
            app.UIAxes_3.YLim = [0.5, imgH + 0.5];
            imshow(im, 'Parent', app.UIAxes_3);
            title(app.UIAxes_3, app.filename, 'Interpreter', 'none', 'FontWeight', 'bold');

            % Keep the manual fit, if any; the point markers are not redrawn
            app.deleteHandles(app.ContourBlueDotHandles); app.ContourBlueDotHandles = [];
            app.deleteHandles(app.ContourRedDotHandles);  app.ContourRedDotHandles = [];
            if app.ContourManualFit && ~isempty(app.ContourFit)
                app.drawContourFit();
            end

            if app.selectContourROI()
                app.GetcontourmapButton.Enable = 'on';
                app.setButtonState(app.GetcontourmapButton, true);
            end
        end

        % Button pushed function: RestartButton
        function RestartButtonPushed(app, event)
            confirm = uiconfirm(app.UIFigure, 'Are you sure you want to restart?', 'Confirm Restart');

            if strcmp(confirm, 'OK')
                % 1. Reset analysis state
                app.clearAnalysis();
                app.deleteHandles(app.BlueDotHandles); app.BlueDotHandles = [];
                app.deleteHandles(app.RedDotHandles);  app.RedDotHandles = [];
                app.SelectedPoints_in = []; app.SelectedPoints_out = [];
                if ~isempty(app.ContourCropHandles)
                    delete(app.ContourCropHandles(isvalid(app.ContourCropHandles)));
                end
                app.ContourCropHandles = [];
                app.clearContourPoints();
                app.LoadedImage = []; app.filename = [];
                app.ViewRange = []; app.SaveRange = []; app.ContourFit = [];
                app.isManualRange = false; app.last_line_pos = [];
                app.current_ri_px = []; app.current_ro_px = [];
                app.Grayaverage = false;

                % 2. Clear all axes (images and graphs)
                axes_to_clear = {app.UIAxes, app.UIAxes_2, app.UIAxes_3, app.UIAxes_4, ...
                    app.UIAxes3, app.UIAxes4, app.UIAxes_5, app.UIAxes_6};
                for i = 1:length(axes_to_clear)
                    colorbar(axes_to_clear{i}, 'off');
                    cla(axes_to_clear{i}, 'reset');     % 'reset' clears styles as well
                end

                % 3. Back to the start-up state (input values are kept)
                app.setButtonState([app.AverageHButton, app.ContourButton, app.AveragegrayvalueButton, ...
                    app.AutoDetectBoundariesButton, app.GenerateProfileButton, ...
                    app.SelecttheROIButton, app.GetcontourmapButton], false);
                app.startupFcn();
                app.TabGroup.SelectedTab = app.InputTab;
            end
        end

        % Button pushed function: RefineBoundariesButton
        function RefineBoundariesButtonPushed(app, event)
            % 1. Initial data check and setup
            if isempty(app.LoadedImage) || isempty(app.SaveRange) || isempty(app.ContourFit)
                uialert(app.UIFigure, 'Please generate a contour map first.', 'Error');
                return;
            end
            app.TabGroup.SelectedTab = app.Setting2Tab;
            r = app.SaveRange;
            roi_img = double(app.LoadedImage(r(1):r(2), r(3):r(4)));

            % 2. Initialize UIAxes_4
            cla(app.UIAxes_4);
            hold(app.UIAxes_4, 'on');
            imagesc(app.UIAxes_4, [r(3) r(4)], [r(1) r(2)], roi_img);
            colormap(app.UIAxes_4, 'gray');
            axis(app.UIAxes_4, 'image');
            set(app.UIAxes_4, 'YDir', 'reverse');
            app.UIAxes_4.XLim = [r(3), r(4)];
            app.UIAxes_4.YLim = [r(1), r(2)];

            % Title style (red, bold, size 14)
            updateTitle = @(txt) title(app.UIAxes_4, txt, 'Color', 'r', 'FontWeight', 'bold', 'FontSize', 14);

            % --- Step 1: inner boundary ---
            updateTitle('1. Click Inner Boundary. Drag to adjust, then ENTER');
            h_in = drawpoint(app.UIAxes_4, 'Color', 'r', 'Label', 'Inner');
            wait(h_in);
            if ~isvalid(h_in), return; end
            p1 = h_in.Position;

            % --- Step 2: outer boundary ---
            updateTitle('2. Click Outer Boundary. Drag to adjust, then ENTER');
            h_out = drawpoint(app.UIAxes_4, 'Color', 'b', 'Label', 'Outer');
            wait(h_out);
            if ~isvalid(h_out), return; end
            p2 = h_out.Position;

            % --- Step 3: store radii and plot guide circles ---
            cx = app.ContourFit(1); cy = app.ContourFit(2);
            dist1 = sqrt((p1(1) - cx)^2 + (p1(2) - cy)^2);
            dist2 = sqrt((p2(1) - cx)^2 + (p2(2) - cy)^2);

            app.current_ri_px = min(dist1, dist2);
            app.current_ro_px = max(dist1, dist2);
            app.isManualRange = true;

            theta = linspace(0, 2*pi, 500);
            plot(app.UIAxes_4, cx + app.current_ri_px*cos(theta), cy + app.current_ri_px*sin(theta), 'r--', 'LineWidth', 1.5);
            plot(app.UIAxes_4, cx + app.current_ro_px*cos(theta), cy + app.current_ro_px*sin(theta), 'b--', 'LineWidth', 1.5);

            updateTitle('Manual Set Done! Click "Get Contour Map"');
            hold(app.UIAxes_4, 'off');
            app.GetcontourmapButton.Enable = 'on';
            app.setButtonState(app.GetcontourmapButton, true);
        end

        % Button pushed function: GetradialprofileButton
        function GetradialprofileButtonPushed(app, event)
            % 1. Safety check: wall boundaries must exist
            if isempty(app.current_ri_px) || isempty(app.current_ro_px) || isempty(app.ContourFit)
                uialert(app.UIFigure, 'Please generate Contour Map first to establish wall boundaries.', 'Error');
                return;
            end
            updateSettings(app);

            % 2. Guidance on UIAxes_5
            originalTitle = app.UIAxes_5.Title.String;
            app.UIAxes_5.Title.String = 'Click and drag to draw a radial line on the map';
            app.UIAxes_5.Title.Color = [1 0 0];
            drawnow;

            % 3. User draws a radial line
            hLine = drawline(app.UIAxes_5, ...
                'Color', 'k', ...
                'StripeColor', 'k', ...
                'LineWidth', 4.5);

            % Restore original title
            app.UIAxes_5.Title.String = originalTitle;
            app.UIAxes_5.Title.Color = [0 0 0];
            if ~isvalid(hLine) || isempty(hLine.Position), return; end

            % 4. Store coordinates and compute the profile
            app.last_line_pos = hLine.Position;
            delete(hLine);
            app.UpdateLineWidth();

            % 5. UI control and tab transition
            app.LineWidthpixelEditField.Enable = 'on';
            app.TabGroup.SelectedTab = app.RadialprofileandEntireviewTab;
        end

        % Value changed function: ScalebarlengthEditField
        function ScalebarlengthEditFieldValueChanged(app, event)
            app.updateScaleBar();
        end

        % Value changed function: LineWidthpixelEditField
        function LineWidthpixelEditFieldValueChanged(app, event)
            app.UpdateLineWidth();
        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.Color = [0.9412 0.9412 0.9412];
            app.UIFigure.Position = [100 100 1365 946];
            app.UIFigure.Name = 'NRICH';

            % Create TabGroup
            app.TabGroup = uitabgroup(app.UIFigure);
            app.TabGroup.Position = [18 18 1331 840];

            % Create InputTab
            app.InputTab = uitab(app.TabGroup);
            app.InputTab.Title = 'Input';

            % Create UIAxes
            app.UIAxes = uiaxes(app.InputTab);
            title(app.UIAxes, 'Title')
            xlabel(app.UIAxes, 'X')
            ylabel(app.UIAxes, 'Y')
            zlabel(app.UIAxes, 'Z')
            app.UIAxes.Colormap = zeros(0,3);
            app.UIAxes.Box = 'on';
            app.UIAxes.Position = [61 95 624 621];

            % Create ContourButton
            app.ContourButton = uibutton(app.InputTab, 'push');
            app.ContourButton.ButtonPushedFcn = createCallbackFcn(app, @ContourButtonPushed, true);
            app.ContourButton.FontSize = 18;
            app.ContourButton.Position = [925 148 242 38];
            app.ContourButton.Text = 'Contour';

            % Create OptionalPanel
            app.OptionalPanel = uipanel(app.InputTab);
            app.OptionalPanel.TitlePosition = 'centertop';
            app.OptionalPanel.Title = 'Optional';
            app.OptionalPanel.FontSize = 18;
            app.OptionalPanel.Position = [729 329 528 410];

            % Create ODmmEditField_2Label_3
            app.ODmmEditField_2Label_3 = uilabel(app.InputTab);
            app.ODmmEditField_2Label_3.HorizontalAlignment = 'center';
            app.ODmmEditField_2Label_3.FontSize = 18;
            app.ODmmEditField_2Label_3.FontWeight = 'bold';
            app.ODmmEditField_2Label_3.Position = [793 134 135 68];
            app.ODmmEditField_2Label_3.Text = 'Analysis 2';

            % Create AverageHButton
            app.AverageHButton = uibutton(app.InputTab, 'push');
            app.AverageHButton.ButtonPushedFcn = createCallbackFcn(app, @AverageHButtonPushed, true);
            app.AverageHButton.FontSize = 18;
            app.AverageHButton.Position = [925 206 242 38];
            app.AverageHButton.Text = 'Average H';

            % Create ODmmEditField_2Label_2
            app.ODmmEditField_2Label_2 = uilabel(app.InputTab);
            app.ODmmEditField_2Label_2.HorizontalAlignment = 'center';
            app.ODmmEditField_2Label_2.FontSize = 18;
            app.ODmmEditField_2Label_2.FontWeight = 'bold';
            app.ODmmEditField_2Label_2.Position = [793 191 135 68];
            app.ODmmEditField_2Label_2.Text = 'Analysis 1';

            % Create AveragegrayvalueButton
            app.AveragegrayvalueButton = uibutton(app.InputTab, 'push');
            app.AveragegrayvalueButton.ButtonPushedFcn = createCallbackFcn(app, @AveragegrayvalueButtonPushed, true);
            app.AveragegrayvalueButton.FontSize = 18;
            app.AveragegrayvalueButton.Position = [925 92 242 37];
            app.AveragegrayvalueButton.Text = 'Average gray value';

            % Create ODmmEditField_2Label_4
            app.ODmmEditField_2Label_4 = uilabel(app.InputTab);
            app.ODmmEditField_2Label_4.HorizontalAlignment = 'center';
            app.ODmmEditField_2Label_4.FontSize = 18;
            app.ODmmEditField_2Label_4.FontWeight = 'bold';
            app.ODmmEditField_2Label_4.Position = [793 77 135 67];
            app.ODmmEditField_2Label_4.Text = 'Calibration';

            % Create RunanalysisLabel
            app.RunanalysisLabel = uilabel(app.InputTab);
            app.RunanalysisLabel.FontSize = 20;
            app.RunanalysisLabel.FontWeight = 'bold';
            app.RunanalysisLabel.Position = [768 247 336 65];
            app.RunanalysisLabel.Text = '4. Run analysis';

            % Create yTransmissionLabel
            app.yTransmissionLabel = uilabel(app.InputTab);
            app.yTransmissionLabel.FontName = 'Times New Roman';
            app.yTransmissionLabel.FontSize = 17;
            app.yTransmissionLabel.FontAngle = 'italic';
            app.yTransmissionLabel.FontColor = [0.2 0.2 0.2];
            app.yTransmissionLabel.Position = [943 329 196 65];
            app.yTransmissionLabel.Text = 'y: Transmission';

            % Create yaexpbxLabel
            app.yaexpbxLabel = uilabel(app.InputTab);
            app.yaexpbxLabel.FontName = 'Times New Roman';
            app.yaexpbxLabel.FontSize = 17;
            app.yaexpbxLabel.FontAngle = 'italic';
            app.yaexpbxLabel.FontColor = [0.2 0.2 0.2];
            app.yaexpbxLabel.Position = [823 329 196 65];
            app.yaexpbxLabel.Text = 'y= a exp(-bx)';

            % Create xHconcentrationLabel
            app.xHconcentrationLabel = uilabel(app.InputTab);
            app.xHconcentrationLabel.FontName = 'Times New Roman';
            app.xHconcentrationLabel.FontSize = 17;
            app.xHconcentrationLabel.FontAngle = 'italic';
            app.xHconcentrationLabel.FontColor = [0.2 0.2 0.2];
            app.xHconcentrationLabel.Position = [1068 329 242 65];
            app.xHconcentrationLabel.Text = 'x: H concentration';

            % Create bsensitivityofneutronstohydrogenLabel
            app.bsensitivityofneutronstohydrogenLabel = uilabel(app.InputTab);
            app.bsensitivityofneutronstohydrogenLabel.FontSize = 16;
            app.bsensitivityofneutronstohydrogenLabel.FontColor = [0.2 0.2 0.2];
            app.bsensitivityofneutronstohydrogenLabel.Position = [968 369 289 65];
            app.bsensitivityofneutronstohydrogenLabel.Text = 'b: sensitivity  of neutrons to hydrogen';

            % Create CalibrationparametersLabel
            app.CalibrationparametersLabel = uilabel(app.InputTab);
            app.CalibrationparametersLabel.FontSize = 19;
            app.CalibrationparametersLabel.FontWeight = 'bold';
            app.CalibrationparametersLabel.FontColor = [0.2 0.2 0.2];
            app.CalibrationparametersLabel.Position = [768 450 336 65];
            app.CalibrationparametersLabel.Text = '3. Calibration parameters';

            % Create CladdinggeometryinformationLabel
            app.CladdinggeometryinformationLabel = uilabel(app.InputTab);
            app.CladdinggeometryinformationLabel.FontSize = 19;
            app.CladdinggeometryinformationLabel.FontWeight = 'bold';
            app.CladdinggeometryinformationLabel.FontColor = [0.2 0.2 0.2];
            app.CladdinggeometryinformationLabel.Position = [768 639 396 68];
            app.CladdinggeometryinformationLabel.Text = '2. Cladding geometry information';

            % Create atransmissionofHfreematerialLabel
            app.atransmissionofHfreematerialLabel = uilabel(app.InputTab);
            app.atransmissionofHfreematerialLabel.FontSize = 16;
            app.atransmissionofHfreematerialLabel.FontColor = [0.2 0.2 0.2];
            app.atransmissionofHfreematerialLabel.Position = [968 407 242 65];
            app.atransmissionofHfreematerialLabel.Text = 'a: transmission of H-free material';

            % Create LoadyourtiffileLabel
            app.LoadyourtiffileLabel = uilabel(app.InputTab);
            app.LoadyourtiffileLabel.FontSize = 20;
            app.LoadyourtiffileLabel.Position = [320 735 270 26];
            app.LoadyourtiffileLabel.Text = 'Load your .tif file';

            % Create LoadfileButton
            app.LoadfileButton = uibutton(app.InputTab, 'push');
            app.LoadfileButton.ButtonPushedFcn = createCallbackFcn(app, @LoadfileButtonPushed, true);
            app.LoadfileButton.FontSize = 20;
            app.LoadfileButton.FontWeight = 'bold';
            app.LoadfileButton.Position = [91 728 212 40];
            app.LoadfileButton.Text = '1. Load file';

            % Create ODmmEditField_2Label
            app.ODmmEditField_2Label = uilabel(app.InputTab);
            app.ODmmEditField_2Label.HorizontalAlignment = 'right';
            app.ODmmEditField_2Label.FontSize = 18;
            app.ODmmEditField_2Label.FontColor = [0.2 0.2 0.2];
            app.ODmmEditField_2Label.Position = [787 610 155 41];
            app.ODmmEditField_2Label.Text = 'OD (mm)';

            % Create ODmmEditField
            app.ODmmEditField = uieditfield(app.InputTab, 'numeric');
            app.ODmmEditField.HorizontalAlignment = 'center';
            app.ODmmEditField.FontSize = 18;
            app.ODmmEditField.FontColor = [0.2 0.2 0.2];
            app.ODmmEditField.Position = [953 618 169 22];
            app.ODmmEditField.Value = 9.5;
            app.ODmmEditField.Limits = [0 Inf];
            app.ODmmEditField.LowerLimitInclusive = 'off';

            % Create ThicknessmmEditField_2Label
            app.ThicknessmmEditField_2Label = uilabel(app.InputTab);
            app.ThicknessmmEditField_2Label.HorizontalAlignment = 'right';
            app.ThicknessmmEditField_2Label.FontSize = 18;
            app.ThicknessmmEditField_2Label.FontColor = [0.2 0.2 0.2];
            app.ThicknessmmEditField_2Label.Position = [773 579 169 38];
            app.ThicknessmmEditField_2Label.Text = 'Thickness (mm)';

            % Create ThicknessmmEditField
            app.ThicknessmmEditField = uieditfield(app.InputTab, 'numeric');
            app.ThicknessmmEditField.HorizontalAlignment = 'center';
            app.ThicknessmmEditField.FontSize = 18;
            app.ThicknessmmEditField.FontColor = [0.2 0.2 0.2];
            app.ThicknessmmEditField.Position = [953 585 169 22];
            app.ThicknessmmEditField.Value = 0.57;
            app.ThicknessmmEditField.Limits = [0 Inf];
            app.ThicknessmmEditField.LowerLimitInclusive = 'off';

            % Create aEditField_2Label
            app.aEditField_2Label = uilabel(app.InputTab);
            app.aEditField_2Label.HorizontalAlignment = 'right';
            app.aEditField_2Label.FontSize = 18;
            app.aEditField_2Label.FontColor = [0.2 0.2 0.2];
            app.aEditField_2Label.Position = [771 429 37 22];
            app.aEditField_2Label.Text = 'a';

            % Create aEditField
            app.aEditField = uieditfield(app.InputTab, 'numeric');
            app.aEditField.FontSize = 18;
            app.aEditField.FontColor = [0.2 0.2 0.2];
            app.aEditField.Position = [818 429 121 22];
            app.aEditField.Value = 0.9107;
            app.aEditField.Limits = [0 Inf];
            app.aEditField.LowerLimitInclusive = 'off';

            % Create bEditField_2Label
            app.bEditField_2Label = uilabel(app.InputTab);
            app.bEditField_2Label.HorizontalAlignment = 'right';
            app.bEditField_2Label.FontSize = 18;
            app.bEditField_2Label.FontColor = [0.2 0.2 0.2];
            app.bEditField_2Label.Position = [771 390 37 22];
            app.bEditField_2Label.Text = 'b';

            % Create bEditField
            app.bEditField = uieditfield(app.InputTab, 'numeric');
            app.bEditField.FontSize = 18;
            app.bEditField.FontColor = [0.2 0.2 0.2];
            app.bEditField.Position = [818 390 121 22];
            app.bEditField.Value = 0.0001;
            app.bEditField.Limits = [0 Inf];
            app.bEditField.LowerLimitInclusive = 'off';

            % Create ThicknessmmEditField_2Label_2
            app.ThicknessmmEditField_2Label_2 = uilabel(app.InputTab);
            app.ThicknessmmEditField_2Label_2.HorizontalAlignment = 'right';
            app.ThicknessmmEditField_2Label_2.FontSize = 18;
            app.ThicknessmmEditField_2Label_2.FontColor = [0.2 0.2 0.2];
            app.ThicknessmmEditField_2Label_2.Position = [787 542 155 41];
            app.ThicknessmmEditField_2Label_2.Text = '1 pixel = (um)';

            % Create pixelumEditField
            app.pixelumEditField = uieditfield(app.InputTab, 'numeric');
            app.pixelumEditField.HorizontalAlignment = 'center';
            app.pixelumEditField.FontSize = 18;
            app.pixelumEditField.FontColor = [0.2 0.2 0.2];
            app.pixelumEditField.Position = [953 550 169 22];
            app.pixelumEditField.Value = 2.7;
            app.pixelumEditField.Limits = [0 Inf];
            app.pixelumEditField.LowerLimitInclusive = 'off';

            % Create Setting1Tab
            app.Setting1Tab = uitab(app.TabGroup);
            app.Setting1Tab.Title = 'Setting1';

            % Create UIAxes_2
            app.UIAxes_2 = uiaxes(app.Setting1Tab);
            title(app.UIAxes_2, 'Title')
            xlabel(app.UIAxes_2, 'X')
            ylabel(app.UIAxes_2, 'Y')
            zlabel(app.UIAxes_2, 'Z')
            app.UIAxes_2.Colormap = [];
            app.UIAxes_2.Box = 'on';
            app.UIAxes_2.Position = [61 95 624 621];

            % Create OptionalPanel_2
            app.OptionalPanel_2 = uipanel(app.Setting1Tab);
            app.OptionalPanel_2.TitlePosition = 'centertop';
            app.OptionalPanel_2.Title = 'Optional';
            app.OptionalPanel_2.FontSize = 16;
            app.OptionalPanel_2.Position = [761 157 496 347];

            % Create MarkInner3PointsButton
            app.MarkInner3PointsButton = uibutton(app.OptionalPanel_2, 'push');
            app.MarkInner3PointsButton.ButtonPushedFcn = createCallbackFcn(app, @MarkInner3PointsButtonPushed, true);
            app.MarkInner3PointsButton.FontSize = 18;
            app.MarkInner3PointsButton.Position = [82 129 200 29];
            app.MarkInner3PointsButton.Text = 'Mark Inner 3-Points';

            % Create ResetinnerButton
            app.ResetinnerButton = uibutton(app.OptionalPanel_2, 'push');
            app.ResetinnerButton.ButtonPushedFcn = createCallbackFcn(app, @ResetinnerButtonPushed, true);
            app.ResetinnerButton.FontSize = 18;
            app.ResetinnerButton.Position = [294 129 166 29];
            app.ResetinnerButton.Text = 'Reset inner';

            % Create MarkOuter3PointsButton
            app.MarkOuter3PointsButton = uibutton(app.OptionalPanel_2, 'push');
            app.MarkOuter3PointsButton.ButtonPushedFcn = createCallbackFcn(app, @MarkOuter3PointsButtonPushed, true);
            app.MarkOuter3PointsButton.FontSize = 18;
            app.MarkOuter3PointsButton.Position = [82 83 200 29];
            app.MarkOuter3PointsButton.Text = 'Mark Outer 3-Points';

            % Create ResetouterButton
            app.ResetouterButton = uibutton(app.OptionalPanel_2, 'push');
            app.ResetouterButton.ButtonPushedFcn = createCallbackFcn(app, @ResetouterButtonPushed, true);
            app.ResetouterButton.FontSize = 18;
            app.ResetouterButton.Position = [297 83 163 29];
            app.ResetouterButton.Text = 'Reset outer';

            % Create RedrawButton
            app.RedrawButton = uibutton(app.OptionalPanel_2, 'push');
            app.RedrawButton.ButtonPushedFcn = createCallbackFcn(app, @RedrawButtonPushed, true);
            app.RedrawButton.FontSize = 18;
            app.RedrawButton.Position = [266 222 193 29];
            app.RedrawButton.Text = 'Redraw';

            % Create DefineAnalysisAreaLabel
            app.DefineAnalysisAreaLabel = uilabel(app.OptionalPanel_2);
            app.DefineAnalysisAreaLabel.FontSize = 18;
            app.DefineAnalysisAreaLabel.FontWeight = 'bold';
            app.DefineAnalysisAreaLabel.Position = [31 267 183 22];
            app.DefineAnalysisAreaLabel.Text = 'Define Analysis Area';

            % Create SelectAreaButton
            app.SelectAreaButton = uibutton(app.OptionalPanel_2, 'push');
            app.SelectAreaButton.ButtonPushedFcn = createCallbackFcn(app, @SelectAreaButtonPushed, true);
            app.SelectAreaButton.FontSize = 18;
            app.SelectAreaButton.Position = [55 222 191 29];
            app.SelectAreaButton.Text = 'Select Area';

            % Create ManualFitLabel
            app.ManualFitLabel = uilabel(app.OptionalPanel_2);
            app.ManualFitLabel.FontSize = 18;
            app.ManualFitLabel.FontWeight = 'bold';
            app.ManualFitLabel.Position = [31 171 99 22];
            app.ManualFitLabel.Text = ' Manual Fit';

            % Create Label
            app.Label = uilabel(app.OptionalPanel_2);
            app.Label.FontSize = 18;
            app.Label.Position = [55 133 25 22];
            app.Label.Text = '1.';

            % Create Label_2
            app.Label_2 = uilabel(app.OptionalPanel_2);
            app.Label_2.FontSize = 18;
            app.Label_2.Position = [55 87 25 22];
            app.Label_2.Text = '2.';

            % Create Label_3
            app.Label_3 = uilabel(app.OptionalPanel_2);
            app.Label_3.FontSize = 18;
            app.Label_3.Position = [55 42 25 22];
            app.Label_3.Text = '3.';

            % Create FitBoundariesButton
            app.FitBoundariesButton = uibutton(app.OptionalPanel_2, 'push');
            app.FitBoundariesButton.ButtonPushedFcn = createCallbackFcn(app, @FitBoundariesButtonPushed, true);
            app.FitBoundariesButton.FontSize = 18;
            app.FitBoundariesButton.Position = [82 38 377 29];
            app.FitBoundariesButton.Text = 'Fit Boundaries';

            % Create GenerateProfileButton
            app.GenerateProfileButton = uibutton(app.Setting1Tab, 'push');
            app.GenerateProfileButton.ButtonPushedFcn = createCallbackFcn(app, @GenerateProfileButtonPushed, true);
            app.GenerateProfileButton.FontSize = 18;
            app.GenerateProfileButton.FontWeight = 'bold';
            app.GenerateProfileButton.Position = [1020 580 224 78];
            app.GenerateProfileButton.Text = 'Generate Profile';

            % Create AutoDetectBoundariesButton
            app.AutoDetectBoundariesButton = uibutton(app.Setting1Tab, 'push');
            app.AutoDetectBoundariesButton.ButtonPushedFcn = createCallbackFcn(app, @AutoDetectBoundariesButtonPushed, true);
            app.AutoDetectBoundariesButton.FontSize = 18;
            app.AutoDetectBoundariesButton.FontWeight = 'bold';
            app.AutoDetectBoundariesButton.Position = [772 579 224 80];
            app.AutoDetectBoundariesButton.Text = 'Auto-Detect Boundaries';

            % Create RadialprofileandEntireviewTab
            app.RadialprofileandEntireviewTab = uitab(app.TabGroup);
            app.RadialprofileandEntireviewTab.Title = 'Radial profile and Entire view';

            % Create UIAxes4
            app.UIAxes4 = uiaxes(app.RadialprofileandEntireviewTab);
            title(app.UIAxes4, 'Title')
            zlabel(app.UIAxes4, 'Z')
            app.UIAxes4.Colormap = [];
            app.UIAxes4.FontSize = 16;
            app.UIAxes4.Position = [712 185 545 546];

            % Create UIAxes3
            app.UIAxes3 = uiaxes(app.RadialprofileandEntireviewTab);
            title(app.UIAxes3, 'Title')
            xlabel(app.UIAxes3, 'X')
            ylabel(app.UIAxes3, 'Y')
            zlabel(app.UIAxes3, 'Z')
            app.UIAxes3.Colormap = [];
            app.UIAxes3.FontSize = 16;
            app.UIAxes3.Position = [61 199 628 531];

            % Create ManuallyselectthecladdingregionButton
            app.ManuallyselectthecladdingregionButton = uibutton(app.RadialprofileandEntireviewTab, 'push');
            app.ManuallyselectthecladdingregionButton.ButtonPushedFcn = createCallbackFcn(app, @ManuallyselectthecladdingregionButtonPushed, true);
            app.ManuallyselectthecladdingregionButton.FontSize = 20;
            app.ManuallyselectthecladdingregionButton.FontWeight = 'bold';
            app.ManuallyselectthecladdingregionButton.Position = [250 98 358 45];
            app.ManuallyselectthecladdingregionButton.Text = 'Manually select the cladding region';

            % Create ExporttoexcelButton
            app.ExporttoexcelButton = uibutton(app.RadialprofileandEntireviewTab, 'push');
            app.ExporttoexcelButton.ButtonPushedFcn = createCallbackFcn(app, @ExporttoexcelButtonPushed, true);
            app.ExporttoexcelButton.FontSize = 20;
            app.ExporttoexcelButton.FontWeight = 'bold';
            app.ExporttoexcelButton.Position = [250 34 357 46];
            app.ExporttoexcelButton.Text = 'Export to excel';

            % Create LineWidthpixelEditFieldLabel
            app.LineWidthpixelEditFieldLabel = uilabel(app.RadialprofileandEntireviewTab);
            app.LineWidthpixelEditFieldLabel.HorizontalAlignment = 'right';
            app.LineWidthpixelEditFieldLabel.FontSize = 19;
            app.LineWidthpixelEditFieldLabel.FontWeight = 'bold';
            app.LineWidthpixelEditFieldLabel.Position = [737 84 164 23];
            app.LineWidthpixelEditFieldLabel.Text = 'Line Width (pixel)';

            % Create LineWidthpixelEditField
            app.LineWidthpixelEditField = uieditfield(app.RadialprofileandEntireviewTab, 'numeric');
            app.LineWidthpixelEditField.ValueChangedFcn = createCallbackFcn(app, @LineWidthpixelEditFieldValueChanged, true);
            app.LineWidthpixelEditField.FontSize = 19;
            app.LineWidthpixelEditField.FontWeight = 'bold';
            app.LineWidthpixelEditField.Position = [916 82 88 24];
            app.LineWidthpixelEditField.Value = 10;
            app.LineWidthpixelEditField.Limits = [1 Inf];
            app.LineWidthpixelEditField.RoundFractionalValues = 'on';

            % Create EntertoUpdateLabel_2
            app.EntertoUpdateLabel_2 = uilabel(app.RadialprofileandEntireviewTab);
            app.EntertoUpdateLabel_2.FontSize = 16;
            app.EntertoUpdateLabel_2.Position = [1020 79 157 33];
            app.EntertoUpdateLabel_2.Text = '[Enter to Update]';

            % Create Setting2Tab
            app.Setting2Tab = uitab(app.TabGroup);
            app.Setting2Tab.Title = 'Setting 2';

            % Create UIAxes_3
            app.UIAxes_3 = uiaxes(app.Setting2Tab);
            title(app.UIAxes_3, 'Title')
            xlabel(app.UIAxes_3, 'X')
            ylabel(app.UIAxes_3, 'Y')
            zlabel(app.UIAxes_3, 'Z')
            app.UIAxes_3.Colormap = [];
            app.UIAxes_3.Position = [68 168 570 553];

            % Create UIAxes_4
            app.UIAxes_4 = uiaxes(app.Setting2Tab);
            title(app.UIAxes_4, 'Title')
            xlabel(app.UIAxes_4, 'X')
            ylabel(app.UIAxes_4, 'Y')
            zlabel(app.UIAxes_4, 'Z')
            app.UIAxes_4.Colormap = [];
            app.UIAxes_4.Position = [663 166 570 553];

            % Create SelecttheROIButton
            app.SelecttheROIButton = uibutton(app.Setting2Tab, 'push');
            app.SelecttheROIButton.ButtonPushedFcn = createCallbackFcn(app, @SelecttheROIButtonPushed, true);
            app.SelecttheROIButton.FontSize = 20;
            app.SelecttheROIButton.FontWeight = 'bold';
            app.SelecttheROIButton.Position = [121 100 208 36];
            app.SelecttheROIButton.Text = 'Select the ROI';

            % Create GetcontourmapButton
            app.GetcontourmapButton = uibutton(app.Setting2Tab, 'push');
            app.GetcontourmapButton.ButtonPushedFcn = createCallbackFcn(app, @GetcontourmapButtonPushed, true);
            app.GetcontourmapButton.FontSize = 20;
            app.GetcontourmapButton.FontWeight = 'bold';
            app.GetcontourmapButton.Position = [121 48 213 36];
            app.GetcontourmapButton.Text = 'Get contour map';

            % Create ClickanddragtoselecttherectangularROIontheimageLabel
            app.ClickanddragtoselecttherectangularROIontheimageLabel = uilabel(app.Setting2Tab);
            app.ClickanddragtoselecttherectangularROIontheimageLabel.FontSize = 18;
            app.ClickanddragtoselecttherectangularROIontheimageLabel.Position = [345 99 478 38];
            app.ClickanddragtoselecttherectangularROIontheimageLabel.Text = 'Click and drag to select the rectangular ROI on the image.';

            % Create ManualFitPanel_2
            app.ManualFitPanel_2 = uipanel(app.Setting2Tab);
            app.ManualFitPanel_2.TitlePosition = 'centertop';
            app.ManualFitPanel_2.Title = 'Optional: Manual Fit';
            app.ManualFitPanel_2.FontSize = 16;
            app.ManualFitPanel_2.Position = [848 20 385 138];

            % Create MarkInner3PointsButton_2
            app.MarkInner3PointsButton_2 = uibutton(app.ManualFitPanel_2, 'push');
            app.MarkInner3PointsButton_2.ButtonPushedFcn = createCallbackFcn(app, @MarkInner3PointsButton_2Pushed, true);
            app.MarkInner3PointsButton_2.FontSize = 16;
            app.MarkInner3PointsButton_2.Position = [14 62 175 30];
            app.MarkInner3PointsButton_2.Text = '1. Mark Inner 3-Points';

            % Create MarkOuter3PointsButton_2
            app.MarkOuter3PointsButton_2 = uibutton(app.ManualFitPanel_2, 'push');
            app.MarkOuter3PointsButton_2.ButtonPushedFcn = createCallbackFcn(app, @MarkOuter3PointsButton_2Pushed, true);
            app.MarkOuter3PointsButton_2.FontSize = 16;
            app.MarkOuter3PointsButton_2.Position = [196 62 175 30];
            app.MarkOuter3PointsButton_2.Text = '2. Mark Outer 3-Points';

            % Create FitBoundariesButton_2
            app.FitBoundariesButton_2 = uibutton(app.ManualFitPanel_2, 'push');
            app.FitBoundariesButton_2.ButtonPushedFcn = createCallbackFcn(app, @FitBoundariesButton_2Pushed, true);
            app.FitBoundariesButton_2.FontSize = 16;
            app.FitBoundariesButton_2.Position = [14 24 357 30];
            app.FitBoundariesButton_2.Text = '3. Fit Boundaries';

            % Create ManualFitHintLabel_2
            app.ManualFitHintLabel_2 = uilabel(app.ManualFitPanel_2);
            app.ManualFitHintLabel_2.FontSize = 12;
            app.ManualFitHintLabel_2.FontColor = [0.4 0.4 0.4];
            app.ManualFitHintLabel_2.Position = [14 2 357 20];
            app.ManualFitHintLabel_2.Text = 'Used instead of auto-detection. Click a Mark button again to redo.';

            % Create ContourmapTab
            app.ContourmapTab = uitab(app.TabGroup);
            app.ContourmapTab.Title = 'Contour map';

            % Create UIAxes_5
            app.UIAxes_5 = uiaxes(app.ContourmapTab);
            title(app.UIAxes_5, 'Title')
            xlabel(app.UIAxes_5, 'X')
            ylabel(app.UIAxes_5, 'Y')
            zlabel(app.UIAxes_5, 'Z')
            app.UIAxes_5.Colormap = [];
            app.UIAxes_5.Position = [91 172 570 553];

            % Create UIAxes_6
            app.UIAxes_6 = uiaxes(app.ContourmapTab);
            title(app.UIAxes_6, 'Title')
            xlabel(app.UIAxes_6, 'X')
            ylabel(app.UIAxes_6, 'Y')
            zlabel(app.UIAxes_6, 'Z')
            app.UIAxes_6.Colormap = [];
            app.UIAxes_6.Position = [682 172 570 553];

            % Create ReselectROIButton
            app.ReselectROIButton = uibutton(app.ContourmapTab, 'push');
            app.ReselectROIButton.ButtonPushedFcn = createCallbackFcn(app, @ReselectROIButtonPushed, true);
            app.ReselectROIButton.FontSize = 18;
            app.ReselectROIButton.FontWeight = 'bold';
            app.ReselectROIButton.Position = [98 59 193 31];
            app.ReselectROIButton.Text = 'Reselect ROI';

            % Create RefineBoundariesButton
            app.RefineBoundariesButton = uibutton(app.ContourmapTab, 'push');
            app.RefineBoundariesButton.ButtonPushedFcn = createCallbackFcn(app, @RefineBoundariesButtonPushed, true);
            app.RefineBoundariesButton.FontSize = 18;
            app.RefineBoundariesButton.FontWeight = 'bold';
            app.RefineBoundariesButton.Position = [98 98 193 31];
            app.RefineBoundariesButton.Text = 'Refine Boundaries';

            % Create AdjustwallboundarieswithinthecurrentROILabel
            app.AdjustwallboundarieswithinthecurrentROILabel = uilabel(app.ContourmapTab);
            app.AdjustwallboundarieswithinthecurrentROILabel.FontSize = 15;
            app.AdjustwallboundarieswithinthecurrentROILabel.Position = [300 92 417 43];
            app.AdjustwallboundarieswithinthecurrentROILabel.Text = 'Adjust wall boundaries within the current ROI.';

            % Create SelectanewROIfromthestartLabel
            app.SelectanewROIfromthestartLabel = uilabel(app.ContourmapTab);
            app.SelectanewROIfromthestartLabel.FontSize = 15;
            app.SelectanewROIfromthestartLabel.Position = [300 47 300 50];
            app.SelectanewROIfromthestartLabel.Text = 'Select a new ROI  from the start.';

            % Create ScalebarlengthLabel
            app.ScalebarlengthLabel = uilabel(app.ContourmapTab);
            app.ScalebarlengthLabel.HorizontalAlignment = 'right';
            app.ScalebarlengthLabel.FontSize = 18;
            app.ScalebarlengthLabel.FontWeight = 'bold';
            app.ScalebarlengthLabel.Position = [848 83 151 22];
            app.ScalebarlengthLabel.Text = 'Scale bar length:';

            % Create ScalebarlengthEditField
            app.ScalebarlengthEditField = uieditfield(app.ContourmapTab, 'numeric');
            app.ScalebarlengthEditField.ValueChangedFcn = createCallbackFcn(app, @ScalebarlengthEditFieldValueChanged, true);
            app.ScalebarlengthEditField.FontSize = 18;
            app.ScalebarlengthEditField.Position = [1014 72 62 43];
            app.ScalebarlengthEditField.Value = 100;
            app.ScalebarlengthEditField.Limits = [0 Inf];
            app.ScalebarlengthEditField.LowerLimitInclusive = 'off';

            % Create GetradialprofileButton
            app.GetradialprofileButton = uibutton(app.ContourmapTab, 'push');
            app.GetradialprofileButton.ButtonPushedFcn = createCallbackFcn(app, @GetradialprofileButtonPushed, true);
            app.GetradialprofileButton.FontSize = 18;
            app.GetradialprofileButton.FontWeight = 'bold';
            app.GetradialprofileButton.Position = [649 73 159 42];
            app.GetradialprofileButton.Text = 'Get radial profile';

            % Create EntertoUpdateLabel
            app.EntertoUpdateLabel = uilabel(app.ContourmapTab);
            app.EntertoUpdateLabel.FontSize = 16;
            app.EntertoUpdateLabel.Position = [1088 78 157 33];
            app.EntertoUpdateLabel.Text = '[Enter to Update]';

            % Create NRICHLabel
            app.NRICHLabel = uilabel(app.UIFigure);
            app.NRICHLabel.FontName = 'Times New Roman';
            app.NRICHLabel.FontSize = 40;
            app.NRICHLabel.FontWeight = 'bold';
            app.NRICHLabel.Position = [30 865 1008 68];
            app.NRICHLabel.Text = 'NRICH';

            % Create RestartButton
            app.RestartButton = uibutton(app.UIFigure, 'push');
            app.RestartButton.ButtonPushedFcn = createCallbackFcn(app, @RestartButtonPushed, true);
            app.RestartButton.FontSize = 18;
            app.RestartButton.FontWeight = 'bold';
            app.RestartButton.Position = [1201 865 148 38];
            app.RestartButton.Text = 'Restart';

            % Create NeutronRadiographInferenceofConcentrationofHydrogenLabel
            app.NeutronRadiographInferenceofConcentrationofHydrogenLabel = uilabel(app.UIFigure);
            app.NeutronRadiographInferenceofConcentrationofHydrogenLabel.VerticalAlignment = 'bottom';
            app.NeutronRadiographInferenceofConcentrationofHydrogenLabel.FontName = 'Times New Roman';
            app.NeutronRadiographInferenceofConcentrationofHydrogenLabel.FontSize = 27;
            app.NeutronRadiographInferenceofConcentrationofHydrogenLabel.Position = [172 877 698 48];
            app.NeutronRadiographInferenceofConcentrationofHydrogenLabel.Text = ': Neutron Radiograph Inference of Concentration of Hydrogen';

            % 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 = NRICH

            % 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


% =========================================================================
%  Local functions
% =========================================================================

function [Tics, Average] = radial_profile(data, radial_step, x0, y0)
% Azimuthally averaged profile around (x0, y0).
%   Tics    : mean radius of each circular layer (px)
%   Average : mean image value of each circular layer
    [X, Y] = meshgrid(1:size(data, 2), 1:size(data, 1));
    X = X - x0;
    Y = Y - y0;

    % Circular layers of width radial_step
    Z_integer = round(abs(X + 1i*Y) / radial_step) + 1;

    Tics = accumarray(Z_integer(:), abs(X(:) + 1i*Y(:)), [], @mean);
    Average = accumarray(Z_integer(:), data(:), [], @mean);
end

function [center, r_in, r_out, resnorm] = fit_two_circles_same_center(inner_pts, outer_pts)
% Least-squares fit of two concentric circles (shared center, two radii).
%   inner_pts, outer_pts : N-by-2 [x y] points on each circle
    all_pts = [inner_pts; outer_pts];

    % Initial guess
    xc0 = mean(all_pts(:, 1));
    yc0 = mean(all_pts(:, 2));
    r_in0 = mean(sqrt((inner_pts(:, 1) - xc0).^2 + (inner_pts(:, 2) - yc0).^2));
    r_out0 = mean(sqrt((outer_pts(:, 1) - xc0).^2 + (outer_pts(:, 2) - yc0).^2));
    params0 = [xc0, yc0, r_in0, r_out0];

    % Residuals: distance to center minus radius, for both point sets
    fun = @(params) [sqrt((inner_pts(:, 1) - params(1)).^2 + (inner_pts(:, 2) - params(2)).^2) - params(3);
                     sqrt((outer_pts(:, 1) - params(1)).^2 + (outer_pts(:, 2) - params(2)).^2) - params(4)];

    opts = optimoptions('lsqnonlin', 'Display', 'off');
    [params_fit, resnorm] = lsqnonlin(fun, params0, [], [], opts);

    center = params_fit(1:2);
    r_in = params_fit(3);
    r_out = params_fit(4);
end

function im = cleanInf(im)
% Replace infinite values with the max/min finite value
    infMask = isinf(im);
    if any(infMask(:))
        validData = im(~infMask);
        if ~isempty(validData)
            im(infMask & im > 0) = max(validData);
            im(infMask & im <= 0) = min(validData);
        end
    end
end
