function varargout = tiremSetup(libFolder)
%tiremSetup   Set up access to Terrain Integrated Rough Earth Model (TIREM)
%   tiremSetup opens a dialog to select the TIREM library folder. The TIREM
%   library folder must contain the "tirem3" shared library, where the
%   full library name is platform-dependent.
%
%       --------------------------------------
%       Platform | Shared library name
%       ---------|----------------------------
%       Windows  | libtirem3.dll or tirem3.dll
%       ---------|----------------------------
%       Linux    | libtirem3.so
%       ---------|----------------------------
%       Mac      | libtirem3.dylib
%       --------------------------------------
%
%   tiremSetup(LIBFOLDER) sets the TIREM library folder to LIBFOLDER,
%   which is specified as a string scalar or character vector.
%
%   LIBFOLDER = tiremSetup returns the current TIREM library folder. If
%   TIREM access has not been set up, LIBFOLDER is empty. 
%
%   The TIREM library folder is used in this session and future sessions of
%   MATLAB to access the external TIREM shared library.
%
% See also tirempl

%   Copyright 2018 The MathWorks, Inc.

if nargout
    narginchk(0,0) % Do not allow input if returning output
    libFolder = char(tirem.internal.PropagationAnalyzer.libraryFolder);
    varargout = {libFolder};
else
    % Open folder chooser if no inputs
    if nargin < 1        
        libFolder = uigetdir(pwd,message('shared_channel:tirem:LibraryFolderDialogTitle').getString);
        if libFolder == 0 % Cancel
            return
        end
    end

    % Validate folder value
    validateattributes(libFolder, {'char','string'}, {'scalartext','nonempty'}, 'tiremSetup');
    libFolder = char(libFolder);
    
    % Validate folder existence
    tirem.internal.Validators.validateLibraryFolder(libFolder);
    
	% Unload old library so that new version is used
    libAlias = tirem.internal.PropagationAnalyzer.LibraryAlias;
    oldLibFolder = tirem.internal.PropagationAnalyzer.libraryFolder;
    if libisloaded(libAlias) 
        if strcmp(oldLibFolder, libFolder)
			% No action needed since library is already loaded 
            return
        end
        unloadlibrary(libAlias);
    end
    
    % Load library so that an early error is thrown if there is a problem
    tirem.internal.PropagationAnalyzer.loadLibrary(libFolder);
    
    % Update persistent value
    tirem.internal.PropagationAnalyzer.libraryFolder(libFolder);
end

