function [kvPair] = findKeyValuePair(h, Type, keyName)
%FINDKEYVALUEPAIR This function searches for a specific Key value Pair that has
%the matching key passed in.

% Copyright 2011-2019 The MathWorks, Inc.

kvPair = [];

%check the args to make sure they all conform to the expected format
args_ok = locCheckArgs(Type, keyName);
if ~(args_ok)
    DAStudio.error('RTW:buildInfo:badMethodArguments',...
                   'RTW.BuildInfo.findKeyValuePair');
end

% if any of the Keys are already in the list, remove them.
switch (Type)
  case 'BuildArg'
    kvVec = h.BuildArgs;
  case 'Token'
    kvVec = h.Tokens;
end

keys = get(kvVec,'Key');

% if there are no keypairs, then just return
if isempty(keys)
    return;
end

% if there is only one buildarg, then the names returned will be a char
% array.  this needs to be turned into a cell array;
if ~iscell(keys)
    keys = {keys};
end

idx = strcmp(keyName,keys);
if any(idx)
    kvPair = kvVec(idx);
end

function args_ok = locCheckArgs(Type, keyName)

args_ok = false;

% the first arg is the type of Key Value pair, and affects which list
% it will get added to.
validTypes = {'BuildArg' 'Token'};
if ~ischar(Type) || ~any(strcmp(Type, validTypes))
    return;
end

% the keyName must be a char

if ~ischar(keyName)
    return;
end

args_ok = true;
