function [tcRegistry, errorMsg] = getToolchainRegistry(toolchainName, toolchainAlias)
%GETTOOLCHAINREGISTRY Get the ToolchainRegistry for the specified toolchain.

% Copyright 2013-2020 The MathWorks, Inc.

tcRegistry = [];
errorMsg = [];

% --------------------------------
% Get all registered toolchains
% --------------------------------

tr = coder.targetreg.internal.TargetRegistry.getWithoutDataLoad();
toolchainsInRegistry = coder.make.internal.getToolchainInfos(tr);
if isempty(toolchainsInRegistry)
exc = message('coder_compile:toolchain:ToolchainRegistryIsEmpty', toolchainName);
errorMsg = exc.getString();
return
end

% --------------------------------
% Search by toolchain's name
% --------------------------------

if ~isempty(toolchainName)
names = {toolchainsInRegistry.Name};
toolchainNameEscaped = regexptranslate('escape', toolchainName);
idx = find(cellfun(@(x)~isempty(x),regexpi(names, toolchainNameEscaped)));
if ~isempty(idx)
tcRegistry = toolchainsInRegistry(idx);
if numel(idx)>1
for ii=1:numel(idx)
if isequal(names{idx(ii)}, toolchainName)
tcRegistry = toolchainsInRegistry(idx(ii));
return
end
end
exc = message('Coder:configSet:MultipleMatchingToolchainName', toolchainName, coder.make.internal.cell2str([{newline} names(idx)],newline));
errorMsg = exc.getString();
return
end
end
end

% --------------------------------
% Search by toolchain's alias
% --------------------------------

if isempty(tcRegistry) && nargin>1 && ~isempty(toolchainAlias)
toolchainsInRegistryAliases = {toolchainsInRegistry.Alias};
idx = [];
for ii=1:numel(toolchainsInRegistryAliases)
if iscell(toolchainAlias) && (numel(toolchainAlias)==1)
toolchainAlias = toolchainAlias{1};
end
if ischar(toolchainAlias)
if ismember(toolchainAlias, toolchainsInRegistryAliases{ii})
idx = ii;
break
end
else
[valid, validIndices] = ismember(toolchainsInRegistryAliases{ii}, toolchainAlias);
if ~isempty(validIndices(valid))
idx = ii;
break;
end
end
end
% Found it. Now get the ToolchainInfo object.
if ~isempty(idx)
tcRegistry = toolchainsInRegistry(idx(1));
end
end

% LocalWords: toolchain's toolchains