%**************************************************************************
%This function reads measurement data from a file.  The columns
%are z, measured voltages, drift corrected voltages, and the calculated
%fields.
%
%Input:
%param, structure containing coil analysis parameters
%
%Output:
%header, header information of the data file
%z, z positions of the measurements (m)
%bx, measurements of the Bx field (T)
%by, measurements of the By field (T)
%
%Zack Wolf, 01/02/07, 8/5/07

function [header, z, bx, by] = read_meas_zvxybxyc(param)

%Construct the input file
file_name = strcat(param.input_file_dir, param.input_file_name);

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

%Extract the header information
%Read down to the title line
ii = 0;
while 1
    in_line = fgetl(fid);
    ii = ii +1;
    header{ii} = in_line;
    if findstr('Magnetic Field Measurements vs Z', in_line) > 0
        break;
    end
end

%Continue reading until the data begins
%Look for the column headers
while 1
    in_line = fgets(fid);
    if findstr('----------', in_line) > 0
        break;
    end
end

%Read the data
data_array = fscanf(fid, '%f %f %f %f %f %f %f', [7, inf]);
z = data_array(1, :);
vy = data_array(2, :);
vx = data_array(3, :);
vy_corr = data_array(4, :);
vx_corr = data_array(5, :);
by = data_array(6, :);
bx = data_array(7, :);

%Close the file
fclose(fid);

%Correct for the coil resistance and the input resistance of the integrator
bxcoil_resist_corr = (param.bxinteg_resist / (param.bxinteg_resist + param.bxcoil_resist))^-1;
vx_corr_imp = vx_corr * bxcoil_resist_corr;
bycoil_resist_corr = (param.byinteg_resist / (param.byinteg_resist + param.bycoil_resist))^-1;
vy_corr_imp = vy_corr * bycoil_resist_corr;

%Use the voltages, calculate the flux in the coil
flux_x = vx_corr_imp * param.bxinteg_scale;
flux_y = vy_corr_imp * param.byinteg_scale;

%Use the flux, apply a calibration to calculate the average field in the coil
bx = flux_x / param.bxcoil_area;
by = flux_y / param.bycoil_area;

%Done