% balls = run_balls(n)
% Given 'n' number of balls, run a simulation until the balls come to a
% complete halt (or when the system has no more kinetic energy).
function balls = run_balls(n) %#codegen

coder.extrinsic('fprintf');

%   Copyright 2010-2013 The MathWorks, Inc.

% Seeding the random number generator will guarantee that we get
% precisely the same simulation every time we call this function.
old_settings = rng(1283,'V4');

% The 'cdata' variable is a matrix representing the colordata bitmap which
% will be rendered at every time step.
cdata = zeros(400,600,'uint8');

% Setup figure windows
im = setup_figure_window(cdata);

% Get the initial configuration for 'n' balls.
balls = initialize_balls(cdata, n);

energy = 2; % Something greater than 1
iteration = 1;
while energy > 1
    % Clear the bitmap
    cdata(:,:) = 0;
    % Apply one iteration of movement
    [cdata,balls,energy] = step_function(cdata,balls);
    % Render the current state
    cdata = draw_balls(cdata, balls);
    iteration = iteration + 1;
    if mod(iteration,10) == 0
        fprintf(1, 'Iteration %d\n', iteration);
    end
    refresh_image(im, cdata);
end
fprintf(1, 'Completed iterations: %d\n', iteration);

% Restore RNG settings.
rng(old_settings);
