%Get the data
load tunnelfluxplt.ru1;
z = tunnelfluxplt(:, 6);
bx = tunnelfluxplt(:, 7);
by = tunnelfluxplt(:, 8);
bz = tunnelfluxplt(:, 9);

%Correct for probe orientation
bx = -bx;
by = -by;

%Field in MMF at Kugler bench
bx_bench = 1.5e-5;
by_bench = -3.7e-5;

%Limits on field difference from tunnel to MMF from I2
GAP_BX_AMPL_FACT = 0.;               %Increase in field in the gap due to steel
GAP_BY_AMPL_FACT = 2.4;              %Increase in field in the gap due to steel
SHIELD_BX_ATTEN_FACT = 1. / 6.;      %Fraction of the earth's field in the gap after the shield is added
SHIELD_BY_ATTEN_FACT = 1. / 6.;      %Fraction of the earth's field in the gap after the shield is added
dbgap_max = 8.65e-6;  %From I2
dby_lim = dbgap_max / SHIELD_BX_ATTEN_FACT / GAP_BY_AMPL_FACT;

%Plot the data
figure;
hold on;
plot(z, bx, 'r', 'linewidth', 0.8);
plot(z, by, 'b', 'linewidth', 0.8);
plot(z, bz, 'g', 'linewidth', 0.8);
line([0, 35], [bx_bench, bx_bench], 'color', 'r', 'linewidth', 0.8);
line([0, 35], [by_bench, by_bench], 'color', 'b', 'linewidth', 0.8);
line([0, 35], [by_bench - dby_lim, by_bench - dby_lim], 'color', 'b', 'linewidth', 2., 'linestyle', '--');
line([0, 35], [by_bench + dby_lim, by_bench + dby_lim], 'color', 'b', 'linewidth', 2., 'linestyle', '--');
legend('Bx (T)', 'By (T)', 'Bz (T)', 'Bx Bench (T)', 'By Bench (T)', 'By Limit (T)');
title('Magnetic Field In LCLS Tunnel, Girders Installed, No Undulators');
ylabel('Bx, By, Bz (T)');
xlabel('Girder Number');
grid on;
zoom on;

%Average field at each girder
for ii = 1 : 33
    girder(ii) = ii;
    index_array = find((z > ii) & (z - ii <= 0.5));
    bx_ave(ii) = mean(bx(index_array));
    by_ave(ii) = mean(by(index_array));
    bz_ave(ii) = mean(bz(index_array));
end

%Plot the average data
figure;
hold on;
plot(girder, bx_ave, 'r*', 'linewidth', 0.8);
plot(girder, by_ave, 'b*', 'linewidth', 0.8);
plot(girder, bz_ave, 'g*', 'linewidth', 0.8);
line([0, 35], [bx_bench, bx_bench], 'color', 'r', 'linewidth', 0.8);
line([0, 35], [by_bench, by_bench], 'color', 'b', 'linewidth', 0.8);
line([0, 35], [by_bench - dby_lim, by_bench - dby_lim], 'color', 'b', 'linewidth', 2., 'linestyle', '--');
line([0, 35], [by_bench + dby_lim, by_bench + dby_lim], 'color', 'b', 'linewidth', 2., 'linestyle', '--');
legend('Bx ave (T)', 'By ave (T)', 'Bz ave (T)', 'Bx Bench (T)', 'By Bench (T)', 'By Limit (T)');
title('Average Magnetic Field On Each Girder In LCLS Tunnel, No Undulators');
ylabel('Bx, By, Bz (T)');
xlabel('Girder Number');
grid on;
zoom on;

%Save the workspace
save tunnel_field.mat

%Done
