function hfvt = fvtoolwaddnreplace(Hd)
%FVTOOLWADDNREPLACE   Utility to enable FVTool with an Add/Replace property.
%   FVTOOLWADDNREPLACE(Hd) Adds a property to FVTool for enabling the
%   'Add Filter' and 'Replace Filter' features and return an FVTool object
%   handle.  These properties are to be used with FVTool's API methods:
%   addfilter and setfilter.
%   
%   See also LNKFVTOOL2MASK

%   Author(s): J. Schickler, P. Costa
%   Copyright 1988-2021 The MathWorks, Inc.

narginchk(1,1);

hfvt = fvtool(Hd,'IsOpenWithReplaceOnly', true);

p = hfvt.addprop('LinkMode');
p.SetObservable = true;
set(hfvt, 'LinkMode', 'Replace');

appContainer = sigtools.fvtool.setGetInstance();
userData = appContainer.getDocumentGroup("fvToolFigureDocumentGroup").UserData;

% Add Value Change callback to FVTool ReplaceCheckBox
replaceCheckBox = userData.ReplaceCheckBox;
replaceCheckBox.ValueChangedFcn = {@fullview_mode_cb, hfvt};

addlistener(hfvt, p, 'PostSet', @(s,e)linkmode_listener(hfvt,e));

linkmode_listener(hfvt);
end

% ----------------------------------------------------------------------
function fullview_mode_cb(~, eventStruct, hfvt)
    % Callback to the menu items
    appContainer = sigtools.fvtool.setGetInstance();
    selectedDocument = appContainer.getDocument(appContainer.SelectedChild.documentGroupTag, appContainer.SelectedChild.tag);

    % Update the state of Replace Check Box
    selectedDocument.UserData.ReplaceCheckBoxSelectedState = eventStruct.EventData.NewValue;

    if eventStruct.EventData.NewValue
        set(hfvt, 'LinkMode', 'Replace');
    else
        set(hfvt, 'LinkMode', 'Add');
    end

end

% ----------------------------------------------------------------------
function linkmode_listener(hfvt, ~)

if strcmpi(hfvt.LinkMode, 'Replace')
    hfvt.setfilter(hfvt.Filters{end});
end

set(hfvt, 'Children', get(hfvt, 'Children'));
end
% [EOF]
