%**************************************************************************
%This function analyzes the fringe fields at the device entrance and exit.
%
%Input:
%z, z positions the field was measured at (m)
%b, measured field strength (T)
%int_b_dz, first integral of the field (Tm)
%z_dev_enter, device entrance z position (m)
%z_dev_exit, device exit z position (m)
%int_b_dz_fringe_lim, field integral threshold where fringe field starts and ends (Tm)
%
%Output:
%z_field_start, z position where the fringe field starts at the entrance end (m)
%z_field_end, z position where the fringe field ends at the exit end (m)
%len_fringe_enter, length of the fringe field at the entrance (m)
%len_fringe_exit, length of the fringe field at the exit (m)
%
%Zachary Wolf
%8/5/11

function [z_field_start, z_field_end, len_fringe_enter, len_fringe_exit] = field_calc_fringe_fields(z, b, int_b_dz, z_dev_enter, z_dev_exit, int_b_dz_fringe_lim)

%Local parameters
b_thresh = .0010;  %10 Gauss threshold

%Initialize
z_field_start = z_dev_enter;
z_field_end = z_dev_exit;
len_fringe_enter = 0;
len_fringe_exit = 0;

%Test for sufficient conditions to evaluate fringe field
if ((z_dev_enter <= z(1)) || (z_dev_enter >= z(end)))
    return;
end
if ((z_dev_exit <= z(1)) || (z_dev_exit >= z(end)))
    return;
end
index_array = find((z > z_dev_enter - .1) & (z < z_dev_enter + .1));
if (max(abs(b(index_array))) < b_thresh)
    return;
end
index_array = find((z > z_dev_exit - .1) & (z < z_dev_exit + .1));
if (max(abs(b(index_array))) < b_thresh)
    return;
end

%Start of entrance fringe field
index_array = find(z < z_dev_enter);
z_enter = z(index_array);
int_b_dz_enter = int_b_dz(index_array);
index_array = find(abs(int_b_dz_enter - int_b_dz_enter(1)) > int_b_dz_fringe_lim);
z_field_start = z_enter(index_array(1));

%Determine the length of the fringe field at the entrance
len_fringe_enter = z_dev_enter - z_field_start;

%End of exit fringe field
index_array = find(z > z_dev_exit);
z_exit = z(index_array);
int_b_dz_exit = int_b_dz(index_array);
index_array = find(abs(int_b_dz_exit - int_b_dz_exit(end)) > int_b_dz_fringe_lim);
z_field_end = z_exit(index_array(end));

%Determine the length of the fringe field at the exit
len_fringe_exit = z_field_end - z_dev_exit;

%Done