function r = hdlcoderfdtd_gui(varargin)
% GUI control of the FDTD demo.
%
% hdlcoderfdtd_gui(varargin)
%
% hdlcoderfdtd_gui('INITIAL')       - setup the display
% hdlcoderfdtd_gui('CLEAR')         - reset the display
% hdlcoderfdtd_gui('PLAYMOVIE')     - replay the result in movie

% Copyright 2006-2011 The MathWorks, Inc.
%   

persistent fig;
persistent timestep;
persistent pix_w pix_h;
persistent data_dbl_sim data_int_mat;
persistent Movie_sim;
persistent axe1;
r = [];

foundFig = findobj('Tag','FDTDDemoScreen');

if isempty(fig)||isempty(foundFig)
    if isempty(foundFig)
        fig = figure;
    else
        fig = figure(foundFig);
    end;
    set(fig, 'Unit', 'normalized');
    set(fig, 'Position', [0.1,0.5,0.4,0.3]);
    clf(fig);
    set(fig, 'Tag', 'FDTDDemoScreen');
end

if nargin == 1
    % Initialize the gui.
    switch varargin{1}
        case 'INITIAL',
            pix_w = 20;
            pix_h = 20;
            timestep = 0;
            set(fig, 'Name', ['FDTD Demo', sprintf(' -- Time Step %d',timestep)]);
            data_dbl_sim  = zeros(pix_h,pix_w);  
            data_int_mat  = zeros(pix_h,pix_w);
            Movie_sim  = moviein(30);
            mlock;
        case 'PLAYMOVIE',
            figure(fig);
            subplot(axe1);
            movie(Movie_sim);
        case 'CLEAR',
            munlock;
            clear;
        otherwise,
            error(message('hdlcoder:hdlcoderdemos:caseerror'));
    end

elseif nargin == 2
    % update (draw) the picture
    i = varargin{2};
    switch varargin{1}
        case 'SIM',
                axe1 = subplot(121);
                pcolor(data_dbl_sim), shading interp, axis image, colorbar, title 'Stateflow Model';
                Movie_sim(i) = getframe(axe1);
                set(fig, 'Name', ['FDTD Demo', sprintf(' -- Time Step %d',timestep)]); 
                timestep = timestep +1;              
        otherwise,
            error(message('hdlcoder:hdlcoderdemos:caseerror'));
    end
    
elseif nargin == 3
    % receive data from Simulink line by line
    i = varargin{2};
    v2 = varargin{3};
    switch varargin{1}
        case 'SIM',
            data_dbl_sim(i,:) = v2(1:pix_w);
        case 'MAT',
            for k = 1:pix_h
                for j = 1:pix_w
                     data_int_mat(k,j)= v2(k*pix_w+j);
                     if i == (k*pix_w+j)
                         data_int_mat(k,j) = -2;
                     end
                end
            end
            subplot(122)
            pcolor(data_int_mat), shading interp, axis image, colorbar, title 'Material Type';
        otherwise,
            error(message('hdlcoder:hdlcoderdemos:caseerror'));
    end
   
else
    error(message('hdlcoder:hdlcoderdemos:inputerror'));
end

