%Load the data
clear;
run_num = 6;
load bscanx_018.dat
data_num = 18;
x = bscanx_018(:, 1);
b = bscanx_018(:, 3);
b_abs = abs(b);

%Fit the peak
index_array = find(b_abs > 0.8 * max(b_abs));
x_fit = x(index_array);
b_abs_fit = b_abs(index_array);
p = polyfit(x_fit, b_abs_fit, 4);
b_abs_fit_val = polyval(p, x_fit);

%Find the field peak
[b_abs_fit_max, index_fit_max] = max(b_abs_fit_val);
x_max = x_fit(index_fit_max);

%Plot the data
figure;
hold on;
plot(x, b_abs);
plot(x_fit, b_abs_fit_val, 'r');
plot(x_max, b_abs_fit_max, 'r*');
xlabel('X (m)');
ylabel('B abs (T)');
title(['Run ', int2str(run_num), ', Data ', int2str(data_num), ', Peak Field Value']);
msg_b = ['B max = ', num2str(b_abs_fit_max), ' (T)'];
msg_x = ['X max = ', num2str(x_max * 1000), ' (mm)'];
text(x_max, b_abs_fit_max - .1, msg_b);
text(x_max, b_abs_fit_max - .12, msg_x);
grid on;
hold off;

%Done