%**************************************************************************
%This function reads measurement data from an ANL data file.  The columns
%are z and the calculated By field.  
%
%Input:
%file_name, name of the measurement data file
%
%Output:
%header, header information of the data file
%z, z positions of the measurements (m)
%by, measurements of the By field (T)
%
%Zack Wolf, 3/9/04

function [header, z, by] = read_meas_zbyh_anl(file_name)

%Open the wiggler data file
fid = fopen(file_name, 'r');
if fid == -1
    disp('idanal_read_meas_zbyh_anl: unable to open input file');
end

%Extract the header information
ii = 0;
while 1
    in_line = fgetl(fid);
    ii = ii +1;
    header{ii} = in_line;
    if findstr('Position(mm), Field(T)', in_line) > 0
%    if findstr('Z_mm', in_line) > 0
        break;
    end
end

%Read the wiggler data
data_array = fscanf(fid, '%f , %f', [2, inf]);
z = data_array(1, :);
by = data_array(2, :);

%ANL uses mm, convert to m
z = z / 1000.;

%Sign convention
by = -by;

%Probe drift correction
b_start = mean(by(1 : 20));
b_end = mean(by(end - 19 : end));
coef = polyfit([z(1), z(end)], [0, b_end - b_start], 1);
slope = coef(1);
inter = coef(2);
by = by - (slope * z + inter);

%Close the file
fclose(fid);

%Done