function isinstalled = istbxinstalled(verstr,dirstr)
% ISTBXINSTALLED - Returns true if toolbox specified by input is installed
%
% INPUTS:
% verstr - Used in desktop mode, a char array passed to VER
%
% dirstr - Used in deployed mode, a char array passed to TOOLBOXDIR, i.e.
% it must be relative to matlabroot/toolbox.  In addition, the path
% specified by this input must be on the MATLAB path and belong to the
% toolbox being tested
%
% EXAMPLE:
% % Test for DSP System Toolbox
% b = istbxinstalled('dsp','dsp/dsp');

if isdeployed
    % VER does not work with MATLAB complied applications.
    % Instead, check for the presence of the toolbox directory (specified
    % by the input) using toolboxdir, and make sure it exists in the path.

    % path() returns a character array of  path entries separated by
    % [pathsep]. Append a [pathsep] to both the search path array and the
    % toolboxdir path.

    try
        tbxroot  = sprintf('%s%s',toolboxdir(dirstr),pathsep);
        srchpath = sprintf('%s%s',path(),pathsep);

        pathidx = strfind(srchpath, tbxroot);
        isinstalled = isscalar(pathidx);
    catch me
        % toolboxdir throws a DirectoryNotFound error in case dirstr does
        % not exist, in which case we infer the toolbox isn't installed.
        if me.identifier == "MATLAB:toolboxdir:DirectoryNotFound"
            isinstalled = false;
        else
            rethrow(me);
        end
    end
else
    isinstalled = ~isempty(ver(verstr));
end
