function newmodel = slvnvextract(sys, showModel)
%SLVNVEXTRACT - Extract subsystem or subchart contents into new model
%
%   NEWMODEL = SLVNVEXTRACT(SUBSYSTEM) extracts the contents of the 
%   Atomic Subsystem block SUBSYSTEM and creates a new model. Returns the 
%   name of the new model in NEWMODEL. SLVNVEXTRACT uses the subsystem 
%   name for the model name, appending a numeral to the model name if that 
%   model name already exists. 
%
%   NEWMODEL = SLVNVEXTRACT(SUBCHART) extracts the contents of the 
%   Atomic Subchart SUBCHART and creates a new model. SUBCHART should
%   specify the full path of the Atomic Subchart. SLVNVEXTRACT uses the
%   subchart name for the model name, appending a numeral to the model 
%   name if that model name already exists. 
%     
%   NEWMODEL = SLVNVEXTRACT(SUBSYSTEM, SHOWMODEL) 
%   NEWMODEL = SLVNVEXTRACT(SUBCHART, SHOWMODEL) opens the extracted
%   model if you set SHOWMODEL to true. Extracted model will be only loaded
%   if SHOWMODEL is set to false.

%   Copyright 2010-2018 The MathWorks, Inc.


    narginchk(1, 2);
    
    if nargin<2
        showModel = true;
    end    
    
    isExportFcnExtraction = false;
    try
        type = get_param(sys,'type');
        isExportFcnExtraction = strcmp(type,'block_diagram') && ...
                strcmp(get_param(sys,'IsExportFunctionModel'),'on');
        
    catch 
    end
    
    try
        if isExportFcnExtraction
            extractObj = Sldv.ExportFcnExtract(mfilename);
        else
            extractObj = Sldv.SubSystemExtract(mfilename);
        end
        [status, modelH, err_msg] = extractObj.extract(sys, ...
            showModel);
    catch Mex
        Sldv.Token.get.release;
        throw(Mex);
    end
    
    if ~status 
        if isempty(err_msg)
            error(message('Slvnv:EXTRACT:Failed'));                
        elseif ~isstruct(err_msg)
            error('Slvnv:EXTRACT:Failed',err_msg);                
        else
            error('Slvnv:EXTRACT:Failed',err_msg.msg);                
        end
    else
    	newmodel = get_param(modelH,'Name');
    end
end
% LocalWords:  NEWMODEL SHOWMODEL SLVNV EXTRACT
