function vfitpoly = gppolyf(data,deg,ipic) 
% GPPOLYF, General Purpose POLYnomial Fit
%     This fits a polynomial to a set of data,
%        and makes plots for assessing goodness of fit
%
% Inputs:
%     data  -  n x 2 matrix of input data, 
%                  first column is x's, i.e. design points
%                  second column is y's, i.e. data values
%     deg   -  degree of polynomial to fit
%     ipic  -  picture control (optional)
%                  0 - don't make plots
%                  1 - (default) make plots in a new figure window
%                  2 - make plots in current figure window
%
% Output:
%     vfitpoly    -  n x 1 column vector of polynomial fit to y's,
%                        evaluated at x's

%    Copyright (c) J. S. Marron 1998



%  set up picture parameter
%
if nargin == 2 ;    %  only 2 arguments input, use default iipic
  iipic = 1 ;
else ;              %  xgrid was specified, use that
  iipic = ipic ;
end ;



%  do polynomial fit
%
vcoeff = polyfit(data(:,1),data(:,2),deg) ;
vfitpoly = polyval(vcoeff,data(:,1)) ;



%  get sum of squares stuff
%
totss = sum((data(:,2) - mean(data(:,2))).^2) ;
pss = sum((vfitpoly - mean(vfitpoly)).^2) ;
percpss = 100 * pss / totss ;
percrss = 100 - percpss ;




if iipic >= 1 ;     %  Then show graphics with result

  if iipic == 1 ;    %  then make a new figure window for graphics
    figure ;
  end ;

  subplot(2,1,1) ;
    plot(data(:,1),[data(:,2),vfitpoly]) ;
      titstr = ['L. S. Fit of deg ' num2str(deg) ' Poly.,'] ;
      titstr = [titstr, ' % of SS = ' num2str(percpss)] ;
      title(titstr) ;
      vax = axis ;

  subplot(2,1,2) ;
    plot(data(:,1),(data(:,2)-vfitpoly)) ;
      title(['Residuals, % of SS = ' num2str(percrss)]) ;
      hold on ;
        plot([vax(1);vax(2)],[0;0],'--') ;
      hold off ;
      vaxhr = (vax(4) - vax(3)) / 2 ;
          %  half range of vertical axis
      axis([vax(1) vax(2) -vaxhr vaxhr]) ;
          %  make range of this axis same as for raw data,
          %  for good visual understanding


end ;


