function varargout=loadlibrary(library,header,varargin)
%CODER.LOADLIBRARY loads an Embedded Coder shared library into MATLAB.
%
%   Suppose your model, "modelSharedLib", is configured for the Embedded Coder
%   host-based shared library target. Code generation produces the folder
%   modelSharedLib_ert_shrlib_rtw and a shared library, for example,
%   modelSharedLib_win64.dll. The name of the shared library depends on your
%   host operating system.
%
%   To load the library, run:
%
%   coder.loadlibrary('modelSharedLib_win64', ...
%                     'modelSharedLib_ert_shrlib_rtw/modelSharedLib.h', ...
%                     'mfilename', 'modelShareLib_Import')
%
%   See also LOADLIBRARY

%   Copyright 2014-2015 The MathWorks, Inc.

if nargin > 0
    library = convertStringsToChars(library);
end

if nargin > 1
    header = convertStringsToChars(header);
end

if nargin > 2
    [varargin{:}] = convertStringsToChars(varargin{:});
end

[path,f,e] = fileparts(header);

% Wrapper header file must have same name as the original header file
wrapperHeader = fullfile(pwd, [f e]);
assert(exist(wrapperHeader, 'file')==0, 'Header file, %s, must not already exist in the current folder');

% Ensure that wrapper header is deleted
cleanupVar = onCleanup(@()delete(wrapperHeader));

% get buildInfo so we can query include paths and extra defines
buildDir = fullfile(path);
bi = load(fullfile(buildDir, 'buildInfo.mat'));

% Add #defines from buildInfo to the wrapper header file.
defines = string(bi.buildInfo.getDefines());
defines = coder.internal.convertDefineToSourceStyle(defines);

coder.internal.writeTemporaryHeader(wrapperHeader, header, defines);

% Add extra include paths from buildInfo to the loadlibrary arguments.
includes = string(bi.buildInfo.getIncludePaths(true));
args = coder.internal.addIncludeArguments(varargin, includes);

% Invoke loadlibrary

[varargout{1:nargout}] = loadlibrary(library, wrapperHeader, args{:});
end

