function plot_envelope_spectrum(freq, mag, fmax, ss)
%PLOT_ENVELOPE_SPECTRUM  Figure 3: envelope spectrum with live f-limit boxes.
%   Edit boxes on the right adjust the x-axis without recalculating.

    figure(3); clf; set(gcf, 'Color', 'w', 'Position', [100 100 900 350]);

    % axes — leave room on the right for the edit boxes
    ax = axes('Parent', gcf, 'Units', 'normalized', ...
              'Position', [0.08 0.15 0.78 0.75]);
    plot(ax, freq, mag, 'k');
    title(ax, 'Envelope Spectrum (FFT)');
    xlabel(ax, 'Frequency (Hz)'); ylabel(ax, ss); grid(ax, 'on');

    fmin0 = 0;
    fmax0 = fmax;
    xlim(ax, [fmin0 fmax0]);

    % --- f max edit box (upper right) ---
    uicontrol('Style','text','Units','normalized', ...
        'Position',[0.88 0.72 0.10 0.06],'String','f max (Hz)', ...
        'BackgroundColor',get(gcf,'Color'),'HorizontalAlignment','left');
    hMax = uicontrol('Style','edit','Units','normalized', ...
        'Position',[0.88 0.66 0.10 0.06],'String',num2str(fmax0));

    % --- f min edit box (below it) ---
    uicontrol('Style','text','Units','normalized', ...
        'Position',[0.88 0.52 0.10 0.06],'String','f min (Hz)', ...
        'BackgroundColor',get(gcf,'Color'),'HorizontalAlignment','left');
    hMin = uicontrol('Style','edit','Units','normalized', ...
        'Position',[0.88 0.46 0.10 0.06],'String',num2str(fmin0));

    % wire callbacks (handles passed explicitly)
    set(hMax,'Callback',{@updateLimits, ax, hMin, hMax});
    set(hMin,'Callback',{@updateLimits, ax, hMin, hMax});
end

function updateLimits(~, ~, ax, hMin, hMax)
    lo = str2double(get(hMin,'String'));
    hi = str2double(get(hMax,'String'));
    if isnan(lo) || isnan(hi) || hi <= lo || lo < 0
        cur = xlim(ax);
        set(hMin,'String',num2str(cur(1)));
        set(hMax,'String',num2str(cur(2)));
        return;
    end
    xlim(ax, [lo hi]);
end