%**************************************************************************
%I1_I2_combine.m
%
%This function reads the output of the long coil analysis program for the
%first and second field integrals.  It then calculates a user specified
%linear combination of them.
%
%Zachary Wolf, 9/6/08

function [] = I1_I2_combine()

%Clear the workspace
clear

%Set the working directory
cd('c:\Analysis\Insertion Device Analysis\Long Coil Analysis');

%Set parameter values by executing the parameter file
I1_I2_combine_param;

%Make the parameter structure
param.i1_input_file_dir = I1_INPUT_FILE_DIR;
param.i1_input_file_name = I1_INPUT_FILE_NAME;
param.i2_input_file_dir = I2_INPUT_FILE_DIR;
param.i2_input_file_name = I2_INPUT_FILE_NAME;
param.output_file_dir = OUTPUT_FILE_DIR;
param.meas_type = MEAS_TYPE;
param.coil_length = COIL_LENGTH;
param.und_start_pos = UND_START_POS;
param.und_end_pos = UND_END_POS;

%Output files
dat_file = [param.output_file_dir, 'I1_I2_combine.dat'];
plt_file = [param.output_file_dir, 'I1_I2_combine.ps'];
mat_file = [param.output_file_dir, 'I1_I2_combine.mat'];

%Initialize the data file
idanal_dat_init(dat_file);

%Initialize the plot file
idanal_long_coil_combine_plot_init(plt_file, param);

%Input the results of the long coil analysis program
param_combine = param;
I1_file = [param_combine.i1_input_file_dir, param_combine.i1_input_file_name];
load(I1_file, 'param', 'header', 'pos', 'integ_raw', 'integ', 'pos_ave', 'integ_ave', 'integ_rms');
pos_ave_1 = pos_ave;
integ_ave_1 = integ_ave;
integ_rms_1 = integ_rms;
I2_file = [param_combine.i2_input_file_dir, param_combine.i2_input_file_name];
load(I2_file, 'param', 'header', 'pos', 'integ_raw', 'integ', 'pos_ave', 'integ_ave', 'integ_rms');
pos_ave_2 = pos_ave;
integ_ave_2 = integ_ave;
integ_rms_2 = integ_rms;
param = param_combine;
    
%Check
if length(pos_ave_1) ~= length(pos_ave_2)
    warning('I1 and I2 positions different, return.');
    return;
end
pos_diff = pos_ave_1 - pos_ave_2;
if max(abs(pos_diff)) > 0.0001
    warning('I1 and I2 positions different, return.');
    return;
end

%Calculate the combination of I1 and I2
pos_combine = pos_ave_1;
integ_combine = integ_ave_2 - (param.coil_length - param.und_end_pos) * integ_ave_1;

%Write the results to the data file
idanal_long_coil_dat_combine(dat_file, param, pos_combine, integ_ave_1, integ_ave_2, integ_combine);

%Plot the results
idanal_long_coil_plot_combine(plt_file, param, pos_combine, integ_combine);

%Save all data
save(mat_file, 'param', 'pos_combine', 'integ_combine');

%Done
