function [f,msg] = fcnchk(fun,varargin)
%FCNCHK Check FUNFUN function argument.
%   FCNCHK(FUN,...) returns either a function name string or an
%   inline object depending on whether the string contains an expression
%   involving parentheses, variables, and math operators.
%
%   FCNCHK is a helper function for FMIN, FMINS, FZERO, etc. so they
%   can compute with string expressions in addition to m-file functions.
%
%   FCNCHK(FUN,...,'vectorized') processes the string (e.g., replacing
%   '*' with '.*') to produce a vectorized function.
%
%   When FUN contains an expression then FCNCHK(FUN,...) is the same as
%   INLINE(FUN,...) except that the optional trailing argument 'vectorized'
%   can be used to produce a vectorized function.
%
%   [F,MSG] = FCNCHK(...) returns an empty string in MSG if successful
%   or an error message string if not.
%
%   See also INLINE.

%   Copyright (c) 1984-98 by The MathWorks, Inc.
%   $Revision: 1.10 $  $Date: 1998/07/16 21:37:02 $

msg = '';

nin = nargin;
if (nin>1) & strcmp(varargin{end},'vectorized')
  vectorizing = 1;
  nin = nin-1;
else
  vectorizing = 0;
end

if isstr(fun)
   fun = strtrim(fun);
   % Check for non-alphanumeric characters that must be part of an
   % expression.
   if isempty(fun),
     f = inline('[]');
   elseif ~vectorizing & isidentifier(fun)
     f = fun; % Must be a function name only
   else
     if vectorizing
       f = inline(vectorize(fun),varargin{1:nin-1});
       var = argnames(f);
       f = inline([formula(f) '.*ones(size(' var{1} '))'],var{1:end});
     else
       f = inline(fun,varargin{1:nin-1});
     end 
   end
elseif isa(fun,'inline')
   f = fun; 
else
   f = '';
   msg = ['FUN must be a function name, valid string expression, ',...
         sprintf('\n'),'or inline function object.'];
end
    
    
%-----------------------------
function F = vectorize(F)
%VECTORIZE Vectorize a symbolic expression.
%   VECTORIZE(F) inserts a '.' before any '^', '*' and '/' in F.

l = length(F);
for k = fliplr(find((F=='^') | (F=='*') | (F=='/')))
   F = [F(1:k-1) '.' F(k:l)];
   l = l+1;
end
F(findstr(F,'..')) = []; % Remove any possible ..*, ../, etc.

%------------------------------------------
function s1 = strtrim(s)
%STRTRIM Trim spaces from string.

if ~isempty(s) & ~isstr(s)
    warning('Input must be a string.')
end

if isempty(s)
    s1 = s;
else
  % remove leading and trailing blanks (including nulls)
  c = find(s ~= ' ' & s ~= 0);
  s1 = s(min(c):max(c));
end

%-------------------------------------------
function tf = isidentifier(str)

tf = 0;

if ~isempty(str)
    first = str(1);
    if (isletter(first))
        letters = isletter(str);
        numerals = (48 <= str) & (str <= 57);
        underscore = (95 == str);
        if (all(letters | numerals | underscore))
            tf = 1;
        end
    end
end

tf = logical(tf);
