function animrule(block)
%ANIMRULE call fuzzy rule viewer during simulation.
%   Animation of fuzzy rules during simulation. This function calls ruleview 
%   during simulation to show how rules are fired. 
%
%   Animation S-function: animrule.m
%   Target library block: Fuzzy Logic Controller with Ruleviewer
%
%   Type sltankrule in MATLAB command line to see a demo.

%   Copyright 1994-2022 The MathWorks, Inc.

setup(block)
end
%% Local functions
function setup(block)
%%

block.NumInputPorts  = 1;
block.NumOutputPorts = 0;
block.NumDialogPrms = 1;
block.NumDworks = 0;

% Register as scope block (i.e. will be skipped in codegen, input data will
% be streamed to host during rapid accelerator mode or external mode)
block.SetSimViewingDevice(true);

fis = block.DialogPrm(1).Data;
if isempty(fis)
   return
end
fuzzy.internal.utility.errorIfType2FIS(fis)

initializeRuleViewer(block)

block.RegBlockMethod('Outputs',@updateRuleViewer);
end

function initializeRuleViewer(block)
%%
fis = block.DialogPrm(1).Data;
fig = findall(0,'Type','figure','Name',sprintf('Rule Viewer: %s',fis.name));
preWarn = warning('query','fuzzy:general:warnDeprecation_Ruleview');
if isempty(fig)
    if isequal(preWarn.state,'on')
        preState = warning('off','fuzzy:general:warnDeprecation_Ruleview');
    end
    ruleview(fis);
    fig = findall(0,'Type','figure','Name',sprintf('Rule Viewer: %s',fis.name));
    position=get(fig, 'Position');
    set(fig, 'Position', position+[.2 -.2 0 0]);
    if isequal(preWarn.state,'on')
        listener = addlistener(fig,'ObjectBeingDestroyed',@(src,evt)cbFigureDestroyed(src));
        fig.UserData.listener = listener;
        fig.UserData.preState = preState;
    end
else
    if isequal(preWarn.state,'on')
        if isstruct(fig.UserData) && isfield(fig.UserData,'listener')
            listener = fig.UserData.listener;
            delete(listener)
        end
        preState = warning('off','fuzzy:general:warnDeprecation_Ruleview');
        listener = addlistener(fig,'ObjectBeingDestroyed',@(src,evt)cbFigureDestroyed(src));
        fig.UserData.listener = listener;
        fig.UserData.preState = preState;
    end

    figure(fig);
end
end

function updateRuleViewer(block)
%%
fis = block.DialogPrm(1).Data;
fig = findall(0,'Type','figure','Name',sprintf('Rule Viewer: %s',fis.name));
if ~isempty(fig)
    set(fig, 'HandleVisibi', 'on');
    ruleview('#simulink', block.InputPort(1).Data, fig);
    set(fig, 'HandleVisibi', 'callback');
end
drawnow
end

function cbFigureDestroyed(src)
%%
s = src.UserData.preState;
warning(s)
h = src.UserData.listener;
delete(h)
end