%**************************************************************************
%This function calculates field integrals (int B dz) from the calculated
%field values.  The x and y position of the line to integrate along is
%specified.  The closest values are used and returned.
%
%Input:
%field, structure containing the magnetic field information
%x_val_req, requested x position of line (m)
%y_val_req, requested y position of line (m)
%
%Output:
%x_val, x position of the integral (m)
%y_val, y position of the integral (m)
%z, z position of the cumulative integral (m)
%int_bx_dz, cumulative integral of Bx along z at (x_int, y_int) (Tm)
%int_by_dz, cumulative integral of By along z at (x_int, y_int) (Tm)
%int_int_bx_dz_dz, cumulative second integral of Bx along z at (x_int, y_int) (Tm)
%int_int_by_dz_dz, cumulative second integral of By along z at (x_int, y_int) (Tm)
%
%Zachary Wolf, 2/7/11

function [x_val, y_val, z, int_bx_dz, int_by_dz, int_int_bx_dz_dz, int_int_by_dz_dz] = pm_field_calc_int_bxy_dz(field, x_val_req, y_val_req)

%Find the closest line to the requested line
[x_close, ix_close] = min(abs(field.pos(:, 1) - x_val_req));
x_val = field.pos(ix_close(1), 1);
[y_close, iy_close] = min(abs(field.pos(:, 2) - y_val_req));
y_val = field.pos(iy_close(1), 2);

%Extract the field data
index_array = find(((field.pos(:, 1) == x_val) & (field.pos(:, 2) == y_val)) == 1);
z = field.pos(index_array, 3);
bx = field.b(index_array, 1);
by = field.b(index_array, 2);

%Calculate the field integrals
int_bx_dz = cumtrapz(z, bx);
int_by_dz = cumtrapz(z, by);

%Calculate the second integrals
int_int_bx_dz_dz = cumtrapz(z, int_bx_dz);
int_int_by_dz_dz = cumtrapz(z, int_by_dz);

%Done
end