%**************************************************************************
%This function fits the phase matching error as a function of K.
%
%Input:
%gap, undulator gap (m)
%k, undulator K values
%
%Output:
%k_resid, fit residuals
%k_fit, fitted K values
%gap_fit_plt, gap values for plotting (m)
%k_fit_plt, fitted K values for plotting
%msg_fit, message about the fit
%
%Zachary Wolf
%6/22/16

function [k_resid, k_fit, gap_fit_plt, k_fit_plt, msg_fit] = pid_fit_kvsgap(gap, k)

%Fit K vs gap
ln_k = log(k);
p = polyfit(gap, ln_k, 4);
k_fit = exp(polyval(p, gap));

%Calculate the residuals
k_resid = k - k_fit;

%Make a set of fitted points for plotting
gap_fit_plt = min(gap) : .0001 : max(gap);
k_fit_plt = exp(polyval(p, gap_fit_plt));

%Compose a message about the fit
msg_fit{1} = 'Fit:';
msg_fit{2} = '  K = exp(p1*g^4 + p2*g^3 + p3*g^2 + p4*g + p5)';
msg_fit{3} = 'Coefficients:';
msg_fit{4} = ['  p1 = ', num2str(p(1))];
msg_fit{5} = ['  p2 = ', num2str(p(2))];
msg_fit{6} = ['  p3 = ', num2str(p(3))];
msg_fit{7} = ['  p4 = ', num2str(p(4))];
msg_fit{8} = ['  p5 = ', num2str(p(5))];

%Done
