%% Save bisection iterations as images (and optional GIF)
% Function and initial bracket
f = @(x) x.^3 - 5*x + 1;
a = 0; b = 2;

% Plot grid
x = linspace(-1, 3, 400);
y = f(x);

% Settings
numIters   = 4;       % how many frames to save
ylimVals   = [-10 10];
pauseSecs  = 0.2;     % small pause so the figure updates smoothly
outPrefix  = 'fig_bisection_iter';  % PNG base name
makeGIF    = true;    % set false if you don't want a GIF
gifName    = 'bisection_iter.gif';

% Prepare figure
fig = figure('Color','w'); box on; grid on;

for iter = 1:numIters
    clf; hold on; box on; grid on;
    
    % Plot function and x-axis
    plot(x, y, 'b', 'LineWidth', 1.5);
    yline(0, 'k', 'LineWidth', 1);
    
    % Midpoint
    c = (a + b)/2;
    
    % Mark points and vertical lines
    scatter([a b c], [f(a) f(b) f(c)], 60, 'r', 'filled');
    xline(a, '--r', 'LineWidth', 1);
    xline(b, '--r', 'LineWidth', 1);
    xline(c, '-.g', 'LineWidth', 1.2);
    
    % Labels
    text(a, ylimVals(1)+1, sprintf('a_%d', iter), 'Color','r', ...
        'FontSize',11, 'HorizontalAlignment','center');
    text(b, ylimVals(1)+1, sprintf('b_%d', iter), 'Color','r', ...
        'FontSize',11, 'HorizontalAlignment','center');
    text(c, ylimVals(1)+1, sprintf('c_%d', iter), 'Color','g', ...
        'FontSize',11, 'HorizontalAlignment','center');
    
    % Cosmetics
    ylim(ylimVals);
    title(sprintf('Bisection Method — Iteration %d', iter));
    legend('f(x) = x^3 - 5x + 1', 'Location','best');
    set(gca, 'GridLineStyle','--', 'FontSize',11);
    drawnow; pause(pauseSecs);
    
    % ===== Save PNG frame =====
    pngName = sprintf('%s%d.png', outPrefix, iter);
    exportgraphics(fig, pngName, 'Resolution', 300);
    fprintf('Saved %s\n', pngName);
    
    % ===== Append to GIF (optional) =====
    if makeGIF
        frame = getframe(fig);
        [A,map] = rgb2ind(frame.cdata, 256);
        if iter == 1
            imwrite(A, map, gifName, 'gif', 'LoopCount', Inf, 'DelayTime', 0.9);
        else
            imwrite(A, map, gifName, 'gif', 'WriteMode', 'append', 'DelayTime', 0.9);
        end
    end
    
    % Update bracket for next iteration
    if f(a) * f(c) < 0
        b = c;
    else
        a = c;
    end
end

if makeGIF
    fprintf('Animated GIF saved as %s\n', gifName);
end