function openExample(file, varargin)
%openExample Open an example for modification and execution.
%   openExample(E) opens an example, identified by E, in a new folder. If
%   the folder already exists, it opens the existing version.
%   openExample(E,'supportingFile', SF) opens an example, identified by E, and launches a supporting file,
%   identified by SF.
%   openExample(E,'workDir', WD) opens an example, identified by E, in a folder,
%   identified by WD.


%   Copyright 2015-2020 The MathWorks, Inc.

% parse the input.
p = inputParser;
validationFcn = @(x) validateattributes(x,{'char','string'},{'nonempty'});
addRequired(p,'file', validationFcn);
addParameter(p,'supportingFile', '', validationFcn);
addParameter(p,'workDir', '', validationFcn);
parse(p, file, varargin{:});
file = p.Results.file;
workDir = p.Results.workDir;
supportingFile = p.Results.supportingFile;

[exampleId, isMainFile] = matlab.internal.examples.identifyExample(file);
if ~isMainFile
    openExample(exampleId, 'supportingFile', file)
    return;
end

metadata = findExample(exampleId);
if isfield(metadata, 'project') && strcmp(metadata.project.open, 'open')
    workDir = setupProjectExample(exampleId, workDir);
else
    workDir = setupExample(exampleId, workDir);
end

override = false;
if ~isempty(supportingFile)
    override = true;
    overrideFile = supportingFile;
end


% Change folder for runnability and such.
cd(workDir)

% Reset workDir to account for symbolic links in user's $HOME path
workDir = pwd;

% Open.
openCompleted = false;
if override
    openCompleted = matlab.internal.examples.openSupportingFile(workDir, metadata, overrideFile);
end

if ~openCompleted
    for iFiles = 1:numel(metadata.files)
        f = metadata.files{iFiles};
        if f.open
            open(fullfile(workDir,f.filename))
            openCompleted = true;
            break;
        end
    end
end

if ~openCompleted
    if isfield(metadata,'callback')
        eval(metadata.callback)
        openCompleted = true;
    end
end

if ~openCompleted
    if isfield(metadata, 'project') && strcmp(metadata.project.open, 'open')
        [~, ~, topLevelProjectRoot] = matlab.internal.project.example.projectDemoSetUp(fullfile(matlabroot, metadata.project.path), ...
        workDir, metadata.project.cmSystem);
        openProject(topLevelProjectRoot);
        openCompleted = true;
    end
end

if ~openCompleted
    mainFile = matlab.internal.examples.getMainFile(metadata);
    edit(fullfile(workDir, mainFile))
end
