function [result,status] = maple(varargin)
%MAPLE  Calls Maple with SYM inputs and outputs.
%   MAPLE(FUN,A1,A2,A3,...) takes SYMs, numbers, and strings as inputs. 
%   It converts any SYM objects to their corresponding Maple string 
%   representations and then calls MAPLEMEX to do the calculation.
%   The result is converted to a SYM object.
%
%   [RESULT,STATUS] = MAPLE(...) returns the warning/error status.
%   When the statement execution is successful, RESULT is the result
%   and STATUS is 0. If the execution fails, RESULT is the corresponding 
%   warning/error message, and STATUS is a positive integer.
%
%   MAPLE is not available for general use in the Student Edition.

%   Copyright (c) 1993-98 by The MathWorks, Inc.
%   $Revision: 1.23 $  $Date: 1997/11/29 01:05:51 $

% Convert all arguments to Maple text strings and concatenate arguments.

if nargin == 1
   if ~isa(varargin{1},'sym')
      error('Please do not use symbolic/@sym as the working directory.')
   end
   statement = char(varargin{1});

elseif (nargin==3) & isstr(varargin{2}) &  ...
   (length(varargin{2})==1 | strcmp(varargin{2},'&*'))

   % Special case, maple(A,'op',B)

   statement = ['(' char(varargin{1}) ')' varargin{2} ...
                '(' char(varargin{3}) ')'];
   if ~isempty(findstr('array',statement))
      statement = ['evalm(' statement ')'];
   end

else

   % Four possibilities:
   % maple('function',arg1,arg2,...)
   % maple('map','function',arg1,arg2,...)
   % maple('map2','function',arg1,arg2,...)
   % maple('evalm','function',arg1,arg2,...)

   map = strcmp(varargin{1},'map') | strcmp(varargin{1},'map2') | ...
         strcmp(varargin{1},'evalm');
   statement = [];
   for k = map+2:nargin
      switch class(varargin{k})
        case 'sym'
           statement = [statement char(varargin{k}) ','];
        case 'double'
           statement = [statement char(sym(varargin{k})) ','];
        case 'char'
           statement = [statement varargin{k} ','];
        otherwise
           error('Input must be type sym, double, and/or char.')
      end;
   end
   statement(end) = [];
   if map & ~isempty(findstr('array',statement))
      statement = [varargin{1} '(' varargin{2} ',' statement ')'];
   else
      statement = [varargin{map+1} '(' statement ')'];
   end
end

if length(statement) >= 9 & ~isempty(findstr('array([])',statement))
   result = sym([]); status = 0;
   return
end

% Access the Maple kernel via the string version of MAPLE function.
[result,status] = maple(statement);
if nargout < 2 & status ~= 0
   error(result)
end

% Convert result to a SYM 
if ~status
   result = sym(result);
end
