function [coeff,R,jvec,dbox] = dPOLYFIT(deg,nodes,w,f,jvec,dbox)

%--------------------------------------------------------------------------
% Object:
% This routine computes the coefficients of the weighted-regression 
% polynomial for total-degree "deg", w.r.t. a "w"-orthogonal basis on a 
% d-dim point cloud "nodes".
%--------------------------------------------------------------------------
% Input:
% deg: total degree of the algebraic regression polynomial; 
% nodes: d-column array of point coordinates;
% w: 1-column array of positive weights, or positive scalar in
%    case of equal weights;
% f: 1-column array of sampled function values at "nodes"; 
% * jvec: vector of column indices, selects a polynomial basis; 
% * dbox: variable that defines a hyperrectangle with 
%    sides parallel to the axis, containing the domain (or pointset "nodes"  
%    in the discrete case). 
%    If "dbox" is not provided, it is the smaller "hyperrectangle", with 
%    sides parallel to the cartesian axes, containing the pointset "nodes".
%    It is a matrix with dimension "2 x d", where "d" is the dimension of
%    the space in which it is embedded the domain. 
%    For instance, for a 2-sphere, it is "d=3", for a 2 dimensional  
%    polygon it is "d=2".
%    As example, the set "[-1,1] x [0,1]" is described as 
%                          "dbox=[-1 0; 1 1]".
%
% Note: the variables with an asterisk "*" are not mandatory and can be 
% also set as empty matrix.
%--------------------------------------------------------------------------
% Output:
% coeff: 1-column array of weighted regression coefficients; 
% R: triangular factor in the economy size QR decomposition 
%                   diag(sqrt(w))*C(:,jvec)=Q*R 
%         where "C=dCHEBVAND(n,Y)";
% jvec: vector of column indices, selects a polynomial basis
% dbox: variable that defines the d-dim box where to adapt the 
%       product-Chebyshev basis.
%--------------------------------------------------------------------------
% Dates:
% Written by M. Dessole, F. Marcuzzi, M. Vianello - July 2020
%
% Modified by M. Dessole, A. Sommariva, M. Vianello - November 2020
%--------------------------------------------------------------------------

% .........................  Function Body ................................

% ..... troubleshooting .....

if nargin < 6, dbox=[]; end
if nargin < 5, jvec=[]; end
if nargin < 4, w=[]; end


% FUNCTION BODY

[~,jvec,Q,R,dbox]=dORTHVAND(deg,nodes,w,jvec,[],dbox);

coeff=Q'*(sqrt(w).*f);

end

