function [overwritefit,overwritenorm,errmsg] = bfitsavefit(datahandle,fit,savefit,fitname,savenorm,normname,overwriteok)
% BFITSAVEFIT Save a fit, as a struct, and the norm of resids to the workspace. 
%
%   [OVERWRITEFIT,OVERWRITENORM,ERRMSG] = BFITSAVEFIT(DATAHANDLE,FIT,SAVEFIT,...
%                                         FITNAME,SAVENORM,NORMNAME,OVERWRITEOK)
%   saves the coefficients and type of FIT for data DATAHANDLE to a struct variable 
%   FITNAME in the base workspace if SAVEFIT is 1, and saves the norm of the
%   residuals to a variable NORMNAME if SAVENORM is 1.  If the variable exists,
%   then it won't overwrite unless OVERWRITEOK is 1.  If FITNAME and NORMNAME
%   are the same, then the residual norm will be saved as a third field in the
%   fit struct.

%   Copyright 1984-2000 The MathWorks, Inc.
%   $Revision: 1.7 $  $Date: 2000/06/13 18:21:18 $

coeff = getappdata(datahandle,'_Basic_Fit_Coeff');
resids = getappdata(datahandle,'_Basic_Fit_Resids');
normvalue = norm(resids{fit+1});
fitvalue.type = fittype(fit);
fitvalue.coeff = coeff{fit+1};
combovalue = fitvalue;
combovalue.residnorm = normvalue;

fitname = deblank(fitname);
normname = deblank(normname);

err1.empty = sprintf('%s\n','              Fit:  an empty string is not a valid choice for a variable name.'); 
err1.invalid = sprintf('%s %s %s\n','              Fit:  the string',fitname,'is not a valid choice for a variable name.'); 

err2.empty = sprintf('%s\n','Norm of residuals:  an empty string is not a valid choice for a variable name.');    
err2.invalid = sprintf('%s %s %s\n','Norm of residuals:  the string',normname,'is not a valid choice for a variable name.');

[overwritefit,overwritenorm,errmsg] = ...
    bfitsavetoworkspace('fit',savefit,fitname,fitvalue,err1,savenorm,normname,normvalue,err2,combovalue,overwriteok);


%------------------------------------------------------
function s = fittype(fit)
% FITTYPE Create fit type string.

switch fit
case 0
    s = 'spline';
case 1
    s = 'hermite';
otherwise
    s = ['polynomial degree ',num2str(fit-1)];
end
