function launch(system, debug)
% LAUNCH Launch the Fixed-Point Tool.

% Copyright 2015-2020 The MathWorks, Inc.

    % g2009485 - FPT will not open when there is no license
    if ~fxptui.checkInstall 
        [msg, msgID] = fxptui.message('msgnoslfxptlicense');
        fpt_exception = MException(msgID, msg);
        throwAsCaller(fpt_exception);     
    end
    
    if nargin < 2
        debug = false;
    end
    
    model = bdroot(system);
    
    fptInstance = fxptui.FixedPointTool.getExistingInstance;
    if isempty(fptInstance)
        createInstance = true;
    elseif ~strcmpi(fptInstance.getModel, model)
        close(fptInstance);
        createInstance = true;
    else
        createInstance = false;
    end
    
    if createInstance
        fptInstance = fxptui.FixedPointTool.getInstance(model);
        % need to loadReferencedModels for SUD selection
        fptInstance.loadReferencedModels;
        fptInstance.ExternalViewer = fptInstance.createExternalViewer;
    else
        fptInstance.loadReferencedModels;
    end
    
    currentSystemForConversion = fptInstance.getSystemForConversion;
    blk = get_param(system, 'Object');
    if isa(blk,'Simulink.ModelReference')
        % Point to the referenced model if the model block is intended to
        % be the SUD. If not, retain the model block selection.
        if isempty(currentSystemForConversion)
            selectedSystem = blk.ModelName;
        else
            selectedSystem = blk.getFullName;
        end
        
    else
        [b, maskedSubsys] = fxptui.isUnderMaskedSubsystem(blk);
        if b
            selectedSystem = maskedSubsys.getFullName;
        else
            selectedSystem = blk.getFullName;
        end
    end
    
    
    % if launching FPT while a FPT window is open,
    % currentSystemForConversion will not be empty
    % only reset the converter, selectedSystemToScale if not set
    if isempty(currentSystemForConversion)
        % g2006017 - set the SystemForConversion under Converter; if 
        % the SUD cannot be set, FPT errors out
        err = fptInstance.updateSelectedSystem(selectedSystem);
        if ~isempty(err)
            throw(err);
        end
        
    end
    
    fptInstance.setupCodeView;
    
    % g1754563 - Reset the isReadyPostCallback flag to false just in case
    % FPT was closed quickly after opening and the flag was left as true
    % unless FPT is being opened again while open
    dc = fptInstance.getDataController;
    if isempty(dc)
        fptInstance.isReadyPostCallback = false;
    end
    
    if debug
        debugPort = matlab.internal.getDebugPort;
        fptInstance.open(debugPort);
    else
        fptInstance.open;
    end
    
    % Re-launch FPT with the updated model name on save as operation
    % g2245666
    fptInstance.attachPostSaveCallback;
end
% LocalWords: FPT msgnoslfxptlicense
