function y = mfun(fun,p1,p2,p3,p4)
%MFUN	Numeric evaluation of a Maple function.
%	MFUN('fun',p1,p2,p3,p4), where 'fun' is the name of a Maple function
%	and p1, p2, p3 and p4 are numeric quantities corresponding to fun's 
%	parameters.  The last parameter specified may be a matrix. All other 
%	parameters must be the type specified by the Maple function.
%	MFUN numerically evaluates 'fun' with the specified parameters
%	and returns MATLAB numeric quantities. Any singularity in 'fun' is
%	returned as NaN.
%
%	Example:
%	    x = 0:0.1:5.0;
%	    y = mfun('FresnelC',x)
%
%	See also MFUNLIST, MHELP.

%	Copyright (c) 1993-95 by The MathWorks, Inc.
%	$Revision: 1.14 $  $Date: 1995/03/01 21:38:53 $

currd = digits;
d = 16;
digits(d);

if nargin == 2
   x = p1;
   a = '';
elseif nargin == 3
   a = [sym(p1) ','];
   x = p2;
elseif nargin == 4
   a = [sym(p1) ',' sym(p2) ','];
   x = p3;
elseif nargin == 5
   a = [sym(p1) ',' sym(p2) ',' sym(p3) ','];
   x = p4;
end;

if isstr(x), x = eval(x); end

[m,n] = size(x);
x = x(:).';
nans = find(isnan(x));
x(nans) = zeros(size(nans));


% format arguments for integer and real x
if all(imag(x) == 0)
   if all(x == fix(x))
      form = ['%' int2str(d) '.0f,'];
   else
      form = ['%' int2str(d+6) '.' int2str(d) 'e,'];
   end
   y = sprintf(form,x);

% format arguments for complex x
else
   form = ['%' int2str(d+6) '.' int2str(d) 'e'];
   y = sprintf([form '#' form '*i,'],[real(x); abs(imag(x))]);
   p = find(y == '#');

   % add the correct signs for imaginary parts
   s = find(imag(x) >= 0);
   if any(s)
      y(p(s)) = setstr('+'*ones(1,length(s)));
   end
   s = find(imag(x) < 0);
   if any(s)
      y(p(s)) = setstr('-'*ones(1,length(s)));
   end
end

% additional format for the Maple MEX file
y(length(y)) = [];
y = ['[' y ']'];

[r,st] = maple(['evalf(map(s->' fun '(' a 's),' y '))']); 

emsg = 'error(''argument type not yet available.'')';
if st == 0
   r = eval(r,emsg);
   r(nans) = NaN*ones(size(nans));
   y = reshape(r,m,n);
elseif isempty(findstr(r,'singular'))
   error(r)

% singularities in r
else
   y = [',' y(2:length(y)-1) ','];  % use commas as delimiters for ALL elements
   c = find(y == ',');
   u = NaN*ones(1,m*n);

   for k = 2:length(c)
      r = y( c(k-1)+1 : c(k)-1 );
      [r,st] = maple(['evalf(' fun '(' a r '))']);
      if isempty(findstr(r,'singular')), u(k-1) = eval(r,emsg); end
   end

   u(nans) = NaN*ones(size(nans));
   y = reshape(u,m,n);
end

digits(currd);
