%**************************************************************************
%This function reads data analysis results and performs fits.
%
%Zachary Wolf
%11/6/14

function [] = ps_fit_meas()

%Clear the workspace
clear

%Set parameter values by executing the parameter file
ps_fit_meas_param

%Output files
plt_file = [OUTPUT_DIR, 'ps_meas_fits.ps'];

%Initialize the plots
ps_comp_plot_init(plt_file, FIT_NAME, INPUT_FILE);

%Loop over analysis results, get data
[r, c] = size(INPUT_FILE);
for ii = 1 : c
    
    %Get the input file
    in_mat_file = INPUT_FILE{ii};

    %Input the analysis results
    load(in_mat_file, 'param', 'header', 'field', 'traj', 'phas');
    
    %Get scalar data
    phase_integral_end(ii) = phas.phase_integral_end;
    
    %Get the gap
    %gap(ii) = ps_comp_get_gap_header(header);
    gap(ii) = sscanf(INPUT_NAME{ii}, 'g = %f mm');
    gap(ii) = gap(ii) / 1000;  %(m)
    
%End loop over analysis results
end

%Remove the largest gap for phase integral fits
index_array = find(gap < .06);
p_i = phase_integral_end(index_array);
g = gap(index_array);

%Fit the phase integral as a function of gap
% ps_comp_plot_phase_int_vs_gap(plt_file, g, p_i);
% cftool(g, log(p_i))
g_fit = .009 : .001 : .100;
[p_i_fit, msg_fit] = ps_fit_meas_calc_phase_int_fit(g_fit);
ps_fit_meas_plot_phase_int_vs_gap_fit(plt_file, msg_fit, g, p_i, g_fit, p_i_fit);
[p_i_fit, msg_fit] = ps_fit_meas_calc_phase_int_fit(g);
p_i_resid = p_i - p_i_fit;
ps_fit_meas_plot_phase_int_vs_gap_fit_resid(plt_file, msg_fit, g, p_i_resid);

%Fit the gap as a function of phase integral
% ps_comp_plot_gap_vs_phase_int(plt_file, p_i, g);
% cftool(log(p_i), g)
p_i_fit = 1.e-8 : 1.e-8 : 8.e-6;
[g_fit, msg_fit] = ps_fit_meas_calc_gap_fit(p_i_fit);
ps_fit_meas_plot_gap_vs_phase_int_fit(plt_file, msg_fit, p_i, g, p_i_fit, g_fit);
[g_fit, msg_fit] = ps_fit_meas_calc_gap_fit(p_i);
g_resid = g - g_fit;
ps_fit_meas_plot_gap_vs_phase_int_fit_resid(plt_file, msg_fit, p_i, g_resid);

%Done
