%**************************************************************************
%This program takes field measurements and fits them using a sinusiod.  The
%fit is used to reduce noise in the measurements.
%
%Input:
%param, structure containing program parameters
%dat_file, file to write data to
%plt_file, file to send plots to
%b_meas, structure containing measured fields
%
%Output:
%b_fit, structure containing the fitted fields
%
%Zachary Wolf
%10/29/13

function [b_fit] = hall2_anal_fit_meas(param, dat_file, plt_file, b_meas)

%Extract the fields from the b_meas structure
z = b_meas.z;
bx1 = b_meas.bx1;
by1 = b_meas.by1;
bz1 = b_meas.bz1;
bx2 = b_meas.bx2;
by2 = b_meas.by2;
bz2 = b_meas.bz2;
period = param.und_period_nom;

%Local parameters
NUM_FIT_PER = 1;  %Default

%Print a warning if parameter values are changed
%warndlg('hall2_anal_fit_meas: parameter values are changed');

%Initialize
b_fit = struct('z', z, 'bx1', zeros(1, length(z)), 'by1', zeros(1, length(z)), 'bz1', zeros(1, length(z)), 'bx2', zeros(1, length(z)), 'by2', zeros(1, length(z)), 'bz2', zeros(1, length(z)));
len_fit = NUM_FIT_PER * period;

%Fit the Bx1 measurements
for ii = 1 : length(bx1)
    if (z(ii) - z(1) <= len_fit / 2) || (z(end) - z(ii) <= len_fit / 2)
        b_fit.bx1(ii) = bx1(ii);
    else
        index_array = find((z > z(ii) - len_fit / 2) & (z < z(ii) + len_fit / 2));
        z_fit = z(index_array);
        bx1_fit = bx1(index_array);
        a0 = (1 / len_fit) * trapz(z_fit, bx1_fit);
        a1 = (2 / len_fit) * trapz(z_fit, bx1_fit .* cos(2 * pi * z_fit / period));
        b1 = (2 / len_fit) * trapz(z_fit, bx1_fit .* sin(2 * pi * z_fit / period));
        a2 = (2 / len_fit) * trapz(z_fit, bx1_fit .* cos(2 * 2 * pi * z_fit / period));
        b2 = (2 / len_fit) * trapz(z_fit, bx1_fit .* sin(2 * 2 * pi * z_fit / period));
        b_fit.bx1(ii) = a0 + a1 * cos(2 * pi * z(ii) / period) + b1 * sin(2 * pi * z(ii) / period);
        %b_fit.bx1(ii) = a0 + a1 * cos(2 * pi * z(ii) / period) + b1 * sin(2 * pi * z(ii) / period) + a2 * cos(2 * 2 * pi * z(ii) / period) + b2 * sin(2 * 2 * pi * z(ii) / period);
    end
end

%Plot the bx1 fit
halln_field_plot_b_bfit_vs_z(plt_file, 'Bx1', z, bx1, b_fit.bx1)
   
%Done