function [cf_, d1] = linear_polynomial_fit(time_dim,f0_dim, figNr)
%LINEAR_POLYNOMIAL_FILT    Create plot of datasets and fits
%   LINEAR_POLYNOMIAL_FILT(time_dim,f0_dim)
%   Creates a plot, similar to the plot in the main curve fitting
%   window, using the data that you provide as input.  You can
%   apply this function to the same data you used with cftool
%   or with different data.  You may want to edit the function to
%   customize the code and this help message.
%
%   Number of datasets:  1
%   Number of fits:  1
% val: the fitted function
% d1: the 1st derivative

 
% Data from dataset "f0_dim vs. time_dim":
%    X = time_dim:
%    Y = f0_dim:
%    Unweighted
%
% This function was automatically generated on 16-Apr-2008 15:22:32
time_dim = time_dim(:);
f0_dim = f0_dim(:);

if nargin < 3
  figNr = 0;
end

if figNr
% Set up figure to receive datasets and fits
 f_ = figNr;
 clf;
 figure(f_);
 set(f_,'Units','Pixels','Position',[278 361 680 485]);
 legh_ = []; legt_ = {};   % handles and text for legend
 xlim_ = [Inf -Inf];       % limits of x axis
 ax_ = axes;
 set(ax_,'Units','normalized','OuterPosition',[0 0 1 1]);
 set(ax_,'Box','on');
 axes(ax_); hold on;

 
% --- Plot data originally in dataset "f0_dim vs. time_dim"

 h_ = line(time_dim,f0_dim,'Parent',ax_,'Color',[0.333333 0 0.666667],...
      'LineStyle','none', 'LineWidth',1,...
      'Marker','.', 'MarkerSize',12);
 xlim_(1) = min(xlim_(1),min(time_dim));
 xlim_(2) = max(xlim_(2),max(time_dim));
 legh_(end+1) = h_;
 legt_{end+1} =  'originale F0 der Phrase';

% Nudge axis limits beyond data limits
 if all(isfinite(xlim_))
    xlim_ = xlim_ + [-1 1] * 0.01 * diff(xlim_);
    set(ax_,'XLim',xlim_)
 end
end

% --- Create fit "fit 1"
ok_ = isfinite(time_dim) & isfinite(f0_dim);
ft_ = fittype('poly1');

if length(ok_) < 2
  d1 = [];
  cf_ = [];
  return;
end

% Fit this model using new data
cf_ = fit(time_dim(ok_),f0_dim(ok_),ft_);

% find d1
d1 = differentiate(cf_,time_dim(ok_));
d1 = d1(1);


if figNr
% Plot this fit
 h_ = plot(cf_,'fit',0.95);
 legend off;  % turn off legend from plot method call
 set(h_(1),'Color',[1 0 0],...
      'LineStyle','-', 'LineWidth',2,...
      'Marker','none', 'MarkerSize',6);
 legh_(end+1) = h_(1);
 legt_{end+1} = 'Durch Regression ermittelte Deklination';
 
 % Done plotting data and fits.  Now finish up loose ends.
 hold off;
 leginfo_ = {'Orientation', 'vertical', 'Location', 'NorthEast'}; 
 h_ = legend(ax_,legh_,legt_,leginfo_{:});  % create legend
 set(h_,'Interpreter','none');
 xlabel(ax_,'');               % remove x label
 ylabel(ax_,'');               % remove y label
end
