% Configure the installed Ansys Electronics Desktop MATLAB coupling interface.

lemModelDir = fileparts(mfilename('fullpath'));
lemProjectFile = fullfile(fileparts(lemModelDir), 'LinearSimulink.aedt');
assert(isfile(lemProjectFile), ...
    'LEM:MissingAedtProject', ...
    'The coupled AEDT project does not exist: %s', lemProjectFile);

lemAnsysRoot = getenv('ANSYSEM_ROOT252');
assert(~isempty(lemAnsysRoot) && isfolder(lemAnsysRoot), ...
    'LEM:MissingAnsysInstallation', ...
    'ANSYSEM_ROOT252 is not configured or does not point to an Ansys installation.');

lemInterfaceRoot = fullfile(lemAnsysRoot, 'cpl', 'matlab');
lemInterfaceFolders = dir(fullfile(lemInterfaceRoot, 'r20*'));
lemInterfaceFolders = lemInterfaceFolders([lemInterfaceFolders.isdir]);
assert(~isempty(lemInterfaceFolders), ...
    'LEM:MissingAnsysMatlabInterface', ...
    'No Ansys MATLAB coupling interface was found below: %s', lemInterfaceRoot);

lemCurrentRelease = regexp(lower(version('-release')), ...
    '^(\d{4})([ab])$', 'tokens', 'once');
assert(~isempty(lemCurrentRelease), ...
    'LEM:UnsupportedMatlabRelease', ...
    'Unable to parse the current MATLAB release: %s', version('-release'));
lemCurrentScore = str2double(lemCurrentRelease{1}) * 2 + ...
    double(lemCurrentRelease{2} == 'b');

lemCandidateScores = -inf(1, numel(lemInterfaceFolders));
for lemIndex = 1:numel(lemInterfaceFolders)
    lemTokens = regexp(lower(lemInterfaceFolders(lemIndex).name), ...
        '^r(\d{4})([ab])$', 'tokens', 'once');
    if ~isempty(lemTokens)
        lemScore = str2double(lemTokens{1}) * 2 + double(lemTokens{2} == 'b');
        if lemScore <= lemCurrentScore
            lemCandidateScores(lemIndex) = lemScore;
        end
    end
end

[lemSelectedScore, lemSelectedIndex] = max(lemCandidateScores);
assert(isfinite(lemSelectedScore), ...
    'LEM:NoCompatibleAnsysMatlabInterface', ...
    'No Ansys MATLAB interface compatible with MATLAB %s was found.', ...
    version('-release'));

lemAnsysMatlabDir = fullfile(lemInterfaceFolders(lemSelectedIndex).folder, ...
    lemInterfaceFolders(lemSelectedIndex).name);
addpath(lemAnsysMatlabDir, '-begin');
rehash;
assert(exist('AnsoftSFunction', 'file') == 3, ...
    'LEM:MissingAnsoftSFunction', ...
    'AnsoftSFunction could not be loaded from: %s', lemAnsysMatlabDir);

clear lemModelDir lemProjectFile lemAnsysRoot lemInterfaceRoot ...
    lemInterfaceFolders lemCurrentRelease lemCurrentScore lemCandidateScores ...
    lemIndex lemTokens lemScore lemSelectedScore lemSelectedIndex ...
    lemAnsysMatlabDir
