function index = searchcell(cellArray, value, varargin)
%--------------------------------------------------------------------------
% function index = searchcell(cellArray, value, [mode])
%
% DESCRIPTION: Searches a cell array and returns the cell index containing
% a match to the specified value. This value can be a number, NaN, or
% string, and you can either specify that it must be an EXACT match or that
% it must CONTAIN the match as a subset. Outputs the indices that match.
%
% USAGE:
%
% Example 1 - 'exact' (default)
%  myPresidents = {'George H.W.', 'Bill', 'George W.', 'Barack', 'Donald'}
%  searchcell(myPresidents, 'Bill')
%  returns the value 2
%
%  searchcell(myPresidents,'George','exact')
%  returns an empty vector []
%
% Example 2 - 'match' (for use only with character strings)
%  searchcell(myPresidents,'George','contains')
%  returns a 2-element array containing the values 1 and 3
%
%
%  Author: Cendri Hutcherson
%  Last updated: 05-27-2018
%--------------------------------------------------------------------------

% specify default search behavior to be an exact match, otherwise use the
% mode specified by varargin
if isempty(varargin)
    type = 'exact';
else
    type = varargin{1};
end

% initialize an array to store the results of comparison to each cell
isTrue = zeros(1,length(cellArray));

% select the mode in which to search
switch type
    case 'exact'
        % test whether the value is NaN, then uses the appropriate
        % comparison method (isnan or isequal)
        if isnan(value)
            for i = 1:length(cellArray)
                isTrue(i) = isnan(cellArray{i});
            end
        else
            for i = 1:length(cellArray)
                isTrue(i) = isequal(cellArray{i},value);
            end
        end
    case 'contains'
        % use regular expression to determine whether there is at least one
        % match to the specified string
        for i = 1:length(cellArray)
            isTrue(i) = ~isempty(regexp(cellArray{i},value,'once'));
        end
end

% find and return the appropriate index values
index = find(isTrue==1);