% Data format: [CRC_wavelength, Mechanical_counter, Error on mean]
raw_data = load('hg_3600_fits.txt');
N = length(raw_data(:,1));

data = zeros(N,3);
syserr = 0.04;
for i = 1:N
    data(i,1) = raw_data(i,1);
    data(i,2) = raw_data(i,2);
    data(i,3) = syserr; % Dominated by systematic error
end

errorbar(data(:,1),data(:,2),data(:,3),'o','markersize',4);

function_quad = @(x,a) a(1)*x.^2 + a(2)*x+a(3);
a0 = [3.484e-7 0.9971 -79.29];
dYda = {@(x,a) 1}; sgn = 0;
[afit,aerr,chisq,yfit,corr_ruler] = levmar(data(:,1),data(:,2),data(:,3),...
    function_quad,a0,dYda,sgn);
 
M = 1000;
x = linspace(data(1,1),data(N,1),M);
y = function_quad(x,afit);
hold on;
plot(x,y,'r','linewidth',2);
xlabel('CRC wavelength (Angstroms)');
ylabel('Mechanical readings');
chisqdof = chisq/5; 
fprintf(1,'Normalized chi sq is %f\n', chisqdof);