%**************************************************************************
%This function reads long coil measurements.  It plots the data.  It
%corrects the data when the coil is long compared to the undulator.
%
%Zachary Wolf
%9/5/08, 5/12/16

function [] = long_coil_anal()

%Clear the workspace
clear

%Set parameter values by executing the parameter file
[param] = long_coil_anal_param;

%Output files
dat_file = [param.input_file_dir, 'long_coil_anal.dat'];
plt_file = [param.input_file_dir, 'long_coil_anal.ps'];
mat_file = [param.input_file_dir, 'long_coil_anal.mat'];

%Read the long coil measurements
[header, gap_m, x_pos_m, y_pos_m, type_m, integ_m] = long_coil_get_meas(param);

%Initialize the data file
util_dat_init(dat_file);
long_coil_dat_header(dat_file, header);

%Initialize the plot file
long_coil_plot_init(plt_file, param, header);

% %Apply a correction, if required
% integ_raw = integ_m;
% if param.corr_required == true
% 	[integ_corr] = long_coil_calc_corr(param, dat_file, plt_file, pos_m, integ_m);
%     integ_m = integ_corr;
% end

%Average measurements taken at the same position
%[pos_ave, integ_ave, integ_rms] = long_coil_calc_integ_ave(pos, integ);
[gap, x_pos, y_pos, type, integ_ave, integ_rms] = long_coil_calc_integ_ave_var_gap(gap_m, x_pos_m, y_pos_m, type_m, integ_m);

%Write results
%long_coil_dat_integ(dat_file, param, pos, integ);
long_coil_dat_integ_gap(dat_file, gap_m, x_pos_m, y_pos_m, type_m, integ_m);
%long_coil_dat_integ_ave(dat_file, param, pos, integ_ave, integ_rms);
%long_coil_dat_integ_ave_ssrl_bl13(dat_file, param, pos_ave, integ_ave, integ_rms);
long_coil_dat_integ_ave_gap(dat_file, gap, x_pos, y_pos, type, integ_ave, integ_rms);

%Plot the data
%long_coil_plot_integ(plt_file, param, pos, integ);
%long_coil_plot_integ_ave(plt_file, param, pos, integ, pos_ave, integ_ave, integ_rms);
title = 'I1X vs Gap';
index_array = find(type == 5);
long_coil_plot_i1vsgap(plt_file, title, gap(index_array), integ_ave(index_array), integ_rms(index_array));
title = 'I1Y vs Gap';
index_array = find(type == 0);
long_coil_plot_i1vsgap(plt_file, title, gap(index_array), integ_ave(index_array), integ_rms(index_array));
title = 'I2X vs Gap';
index_array = find(type == 7);
long_coil_plot_i2vsgap(plt_file, title, gap(index_array), integ_ave(index_array), integ_rms(index_array));
title = 'I2Y vs Gap';
index_array = find(type == 2);
long_coil_plot_i2vsgap(plt_file, title, gap(index_array), integ_ave(index_array), integ_rms(index_array));

%Save all data
save(mat_file, 'param', 'header', 'gap', 'x_pos', 'y_pos', 'type', 'integ_ave', 'integ_rms');

%Done
