function [close,inside,thislevel] = matchbrk(c,open,fill)
% matchbrk  Match an opening bracket found at the beginning of char string.
%
% Syntax
% =======
%
%     [CLOSE,INSIDE,THISLEVEL] = strfun.matchbrk(TEXT)
%     [CLOSE,INSIDE,THISLEVEL] = strfun.matchbrk(TEXT,OPEN)
%     [CLOSE,INSIDE,THISLEVEL] = strfun.matchbrk(TEXT,OPEN,FILL)
%
% Input arguments
% ================
%
% * `TEXT` [ char ] - Text string.
%
% * `OPEN` [ numeric ] - Position of the requested opening bracket; if not
% specified, the opening bracket is expected at the beginning of the
% string.
%
% * `FILL` [ char ] - Character that will be used to replace the content of
% nested brackets in `THISLEVEL`.
%
% Output arguments
% =================
%
% * `CLOSE` [ numeric ] - Position of the matching closing bracket.
%
% * `INSIDE` [ char ] - Text string inside the matching brackets.
%
% * `THISLEVEL` [ char ] - Text string inside the matching brackets where
% nested brackets are replaced with `FILL`.
%

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

if nargin < 2
   open = 1;
end

if nargin < 3
   fill = ' ';
end

% Parse input arguments.
P = inputParser();
P.addRequired('TEXT',@ischar);
P.addRequired('OPEN',@isnumericscalar);
P.addRequired('FILL',@(x) ischar(x) && length(x) == 1);
P.parse(c,open,fill);

close = [];
inside = '';
thislevel = '';

if open > length(c)
   return
end

%**************************************************************************

c = c(:).';
openbrk = c(open);
switch openbrk
   case '('
      closebrk = ')';
   case '['
      closebrk = ']';
   case '{'
      closebrk = '}';
   case '<'
      closebrk = '>';
   otherwise
      return
end

% Find out the positions of opening and closing brackets.
x = zeros(size(c));
x(c == openbrk) = 1;
x(c == closebrk) = -1;
x(1:open-1) = NaN;
% Assign the level numbers to the content of nested brackets. The closing
% brackets have always the level number of the outside content.
cumx = x;
cumx(open:end) = cumsum(x(open:end));
close = find(cumx == 0,1,'first');
if nargout > 1
   if ~isempty(close)
      inside = c(open+1:close-1);
      if ~isempty(inside)
         x = x(open+1:close-1);
         cumx = cumx(open+1:close-1);
         thislevel = inside;
         % Replace the content of higher-level nested brackets with `FILL`.
         thislevel(cumx > cumx(1)) = fill;
         % Replace also the closing higher-level brackets (they are not
         % captured above).
         thislevel(x == -1) = fill;
      else
         thislevel = '';
      end
   end
end

end
