% im = setup_figure_window(cdata)
% Given a bitmap of indexed colors (cdata), create a figure window
% containing an image with same size as the color data (cdata) matrix.
% Return the handle of the image object.
function im = setup_figure_window(cdata) %#codegen

%   Copyright 2010 The MathWorks, Inc.

% These functions are exempt for code generation; MATLAB runtime will be
% used.
coder.extrinsic('figure', 'findobj', 'image', 'gca', 'set', 'jet', 'colormap');

fig = findobj('Name', 'MATLAB Coder Bouncing Balls');
if isempty(fig)
    fig = figure;
    pos = [0 0 0 0]; 
    pos = get(fig, 'Position');
    pos(2) = pos(2) - 64;
    pos(3) = size(cdata,2);
    pos(4) = size(cdata,1);
    set(fig, 'Position', pos);
end
% We need a "dummy" initialization of 'cm' to determine its
% type. The return type of the 'jet' function is unknown as it is declared extrinsic.
% The compiler cannot analyze extrinsic functions, so the trick is to
% initialize the variable with the right type. If the function would return
% a different type (than we've specified) a runtime error will occur.
cm = zeros(128,3);

% Get a JET color table with 128 colors.
cm = jet(128);
% Ensure the first color is black (RGB = 0 0 0)
cm(1,:) = [0 0 0];
% Set the current colormap to use the color table.
colormap(cm);
% Resize the figure window to use the size of the colordata (cdata) bitmap.
% Create an image in this figure window
im = image(cdata);
% Set a title and make the axes invisible
set(fig, 'Name', 'MATLAB Coder Bouncing Balls');
set(gca, 'Visible', 'off');
