%**************************************************************************
%This function reads insertion device analysis results.  It gets the measured K
%information and performs fits.
%
%Zachary Wolf
%6/22/16

function [] = pid_fit_k()

%Clear the workspace
clear

%Set parameter values by executing the parameter file
pid_fit_k_param

%Output files
dat_file = [OUTPUT_DIR, 'pid_fit_k.dat'];
plt_file = [OUTPUT_DIR, 'pid_fit_k.ps'];
%mat_file = [OUTPUT_DIR, 'pid_fit_k.mat'];
xls_file = [OUTPUT_DIR, 'pid_fit_k.xls'];

%Initialize the data file
util_dat_init(dat_file);
util_dat_msg(dat_file, cellstr(' '));
util_dat_msg(dat_file, cellstr('Fit K Results:'));
util_dat_msg(dat_file, cellstr(FIT_NAME));

%Initialize the plots
pid_fit_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', 'gap', 'temp', 'field', 'traj', 'phas');
    
    %Get the analysis results
    gapm(ii) = gap;
    k_eff(ii) = phas.k_eff;
    
    %Get the run number
    [run_num] = util_get_run_header(header);
    run(ii) = run_num;
    
%End loop over analysis results
end
gap = gapm;

%Write values to the data file
pid_fit_dat_k(dat_file, gap, k_eff);

%Plot the entrance phase matching error vs K
k = k_eff;
[k_resid, k_fit, gap_fit_plt, k_fit_plt, msg_fit] = pid_fit_kvsgap(gap, k);
pid_fit_plot_kvsgap_fit(plt_file, gap, k, gap_fit_plt, k_fit_plt, msg_fit);
pid_fit_plot_kvsgap_fit_resid(plt_file, gap, k_resid);

%Save the results to the mat file
%save(mat_file, 'FIT_NAME', 'OUTPUT_DIR', 'INPUT_FILE', 'INPUT_NAME',  'k_eff', 't_ave', 'date_num');

%Write the data to an Excel file
col_names = {'Run #', 'Gap (mm)', 'Keff'};
xlswrite(xls_file, col_names, 1, 'a1:c1');
xlswrite(xls_file, run', 1, 'a2');
xlswrite(xls_file, (gap * 1000)', 1, 'b2');
xlswrite(xls_file, k_eff', 1, 'c2');

%Done
