function [coef,mon,idx]=monomialindexes(poly,vars)
% [coef,mon,idx]=monomialindexes(poly,vars)
%
% Returns the coefficients and indices of the monomials in a given
% polynomial
%
% Input:
% poly - polynomial on variables 'vars' (symbolica variable)
% vars - array with variables (array of symbolic variables)
%
% Output:
% coef - array of coefficients (symbolic variable)
% mon  - array of monomials (symbolic variable)
% idx  - indices of the monomial, one integers >=0 per variable
%
% Copyright (C) 2006  Joao Hespanha

% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License along
% with this program; if not, write to the Free Software Foundation, Inc.,
% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
%
% Modification history:
%
% Created October 13, 2006 

nvars=length(vars);
charvars=char(vars(:).');
if length(vars)>1
    charvars=charvars(9:end-2);
end

poly=expand(poly);

%% complicated 
%
%maple('unassign','''mon''');
%[coef,err]=maple('coeffs',char(expand(poly)),charvars,'mon')
%if err
%  error('expression is not a polynomial')
%end
%coef=sym(coef)
%mon=sym(maple('mon'))

%% simple
%poly
%charvars
[coef,mon]=coeffs(poly,charvars);

if nargout>=3
  
  % convert symbolic expression of monomials into vectors of indexes
  idx=zeros(length(coef),nvars);

  for i=1:nvars
    for j=1:length(mon)
      idx(j,i)=double(maple('degree',mon(j),vars(i)));
    end
    
    %    m=mon.';
    %    k=0;
    %    while any(m~=0)
    %       m=diff(m,vars(i));
    %        idx(:,i)=idx(:,i)+(m~=0);
    %	k=k+1;
    %	if k>100
    %	  error('monomialindexes: degree of ''%s'' larger than 100 or negative',char(poly))
    %	end
    %    end
  end
end
