function [id,match] = listmatch(item, list, warn)
% id = LISTMATCH(item, list) matches "item" in (cell) string array "list" & returns a unique index "id".
%
% "id" is found by interactive extension of "item" by he user until an exact match is found.
% "id" == [] means no match.
%
% id = LISTMATCH(item, list, warn) chooses the first match automatically.
% A warning message is issued if warn=='warn' or warn==1.
%
% [id,match] = LISTMATCH(item, ...) also returns the match.
%
%
% Author: Joerg Bretschneider 2009/06/03
% Platform: Matlab4+
% See also: STRMATCH
list = char(list);
while 1,
id = strmatch(item, list);
if length(id) < 2, if nargout > 1, match = deblank(list(id,:)); end, return, end
% --- if the was no match at all or exactly one match, all is ok.
% If there are multiple matches,
if nargin > 2, % --- choose the first match automatically, with a warning or not:
if isempty(warn), warn = 'nowarn'; end
if strcmpi(warn,'warn'), warn = 1; end
if warn(1) == 1, disp(['WARNING: multiple matches found for "' item '", first match was chosen.']), end
id = id(1); if nargout > 1, match = deblank(list(id,:)); end, return
end
% --- or find the common token of the matches and offer interactive extension:
M = [list(id,:)]; % --- reduced list of matching entries
D = diff(M); % --- check the differences
D(end+1,:) = 0; % --- add a line of all zeros to ensure that D is actually 2D
D = sum(D); % --- (for SUM to work on its columns)
idx = find(D); % --- number of zeros indicates number of matching characters
item = M(1,1:idx(1)-1); % --- extend item to cover all these characters, further extension by the user:
E = sprintf('%c | ', M(:,idx(1))); E = E(1:end-2);
ext = input(['Multiple matches found for "' item '". Extend by ' E 'to get a unique match: >' item],'s');
item = [item ext];
end
if nargout > 1, match = deblank(list(id,:)); end,