function fNumber = freblkPlotResponses(responses,frequencies,fNumber,Data1,Data2,IsFRD,Ts,blkh)
%   Utility function of FRE block

%   Author: R. Chen
%   Copyright 2018 The MathWorks, Inc.

% #1: The file is mlocked.  During debugging, use "munlock" then "clear
% all" to let ML honor the latest edition in the file.
%
% #2: Ts is always positive because plotting is disabled when Ts = -1.
%
% #3: One figure and one bodeplot object per block as it is always
% refreshed by new simulation run. A hash map is used to ensure that.
%
% #4: First response is the baseline plant (nan if baseline does not exist)
% and second response is the estimation 

mlock
persistent hashmap;

Key = num2str(blkh);
KeyFigure = [Key 'Figure'];
KeyBode = [Key 'Bode'];
%% Create hashmap, a singleton per ML session in the scope of this file
if isempty(hashmap)
    hashmap = containers.Map();
end
%% Create a figure when (1) first time, or (2) invalid at compile time (fNumber = 0)
if isKey(hashmap,KeyFigure)
    % figure exists
    fig = hashmap(KeyFigure);
    % during simulation, do not create a new figure if the current one
    % becomes invalid (because user closes it).
    if ~isvalid(fig) && fNumber==0
        fig = figure();
        hashmap(KeyFigure) = fig;
    end
else
    % new figure needed
    fig = figure();
    hashmap(KeyFigure) = fig;
end
%% At compile time (fNumber = 0), create and store new bodeplot object and plot baseline once
if fNumber==0
    % do nothing during linearization
    if strcmp(get_param(bdroot(blkh),'AnalyticLinearization'),'on')
        return
    end
    if Data1==0
        % no baseline, use NaN in first response
        baseline = frd(nan(length(frequencies),1),frequencies,Ts);
        estimated = frd(responses,frequencies,Ts);
        h = bodeplot(baseline,'*b',estimated,'*b');
    else
        % have baseline
        if IsFRD
            baseline = frd(Data1,Data2);
        else
            plant = tf(Data1,Data2,Ts);
            if length(frequencies)==1
                [~,~,w] = bode(plant,frequencies);
            else
                [~,~,w] = bode(plant,{min(frequencies),max(frequencies)});
            end
            baseline = frd(plant,w);
        end
        estimated = frd(responses,frequencies,Ts);
        h = bodeplot(baseline,'-r',estimated,'*b');
        legend('baseline','estimated','location','southwest');
    end
    hashmap(KeyBode) = h;
    fNumber = 1;
%% During simulation (fNumber > 0), plot estimation only when figure is valid
elseif isvalid(fig)
    % only update the second response (est) during simulation
    h = hashmap(KeyBode);
    estimated = frd(responses,frequencies,Ts);
    updateSystem(h,estimated,2);
end    
