function fit_thermistor_calibration(npoly,fname)
% fit_thermistor_calibration  Polynomial curve fits of calibration data for thermistor

% -- Supply default values for npoly and fname
if nargin<1, npoly=2;  end
if nargin<2, fname='thermistor_data.txt';  end

% -- Load the data and compute summary statistics for each column
D = load(fname);
T = D(1,:);         %  Temperature values in first row
V = D(2:end,:);     %  Voltage data in columns from second row until end
Vave = mean(V);     %  Mean of data in each column
Vmed = median(V);   %  Median of data in each column
Vstd = std(V);      %  Standard deviation of each column

% -- Print summary data
fprintf('\n    T(C)   mean(V) median(V) std_dev(V)\n');
for j=1:size(V,2)
  fprintf('%8.1f %8.1f %8.1f %8.2f\n',T(j),Vave(j),Vmed(j),Vstd(j));
end

% -- Perform curve fit
c = polyfit(T,Vave,npoly);
fprintf('\nCurve fit coefficients\n');   fprintf('\t%12.7e\n',c);

% -- Plot the curve fit
Tfit = linspace(min(T),max(T));
vfit = polyval(c,Tfit);
subplot(2,1,1)
plot(T,Vave,'o',Tfit,vfit,'r--');
xlabel('Temperature (C)');   ylabel('Analog output');
legend('Data',sprintf('Degree %d poly fit',npoly),'Location','Northwest');

% -- Evaluate residuals at the known (measured) input values
rfit = Vave - polyval(c,T);
subplot(2,1,2)
plot(T,rfit,'o');
xlabel('Temperature (C)');   ylabel('Residual of the fit');