% Final gap calculation for 4580
% The 4D102.36 dipoles 4D102.36 dipoles should ideally (according to Mark Woodley) give an integrated field strength of 4.9485 kG-m at 216.886 amps, 
% since that is the current that the BYD magnets will run at 17 GeV (the maximum beam current).   

I_nom = 216.886; % amps.  Nominal current for the BYD dipoles at 17 GeV.
BL_nom = 0.49485; % T-m. Nominal integrated field for the 0.679D102.36 (their new name) dipoles when set to 216.886 amps. 

present_gap = 1.382; % inches  

% Measured fields and currents near the nominal current

BL_meas =  0.243660;
I_meas = 216.7849;

BL_m6_mean = mean([0.232869  0.233019]);    
BL_p6_mean = 0.254849;    

Trim_per_diff = 100*(BL_p6_mean - BL_m6_mean)/BL_meas;

% Calculate the current needed for BL_nom.  

 [Wire, BL_I_up, dBL_I_up] = Plot_wireplt_intstr_dev(1, 4, 1, 1);
 close all
 I_nom_calc = polyval(BL_I_up, BL_nom);
 
 Correct_gap_inches = present_gap/(I_nom_calc/I_nom); % inches

 Current_ratio = I_nom_calc/I_nom;  % Ratio of currents at nominal integrated field of 0.49485 Tm
 BL_ratio = BL_nom/BL_meas*(I_meas/I_nom);  % Ratio of the integrated field at 217.0283 and 216.886 amps
 Gap_ratio = present_gap/Correct_gap_inches;  % Ratio of the gap changes

 
 assignin('base', 'Correct_gap_inches_4580', Correct_gap_inches);
 assignin('base', 'Trim_per_diff_4580', Trim_per_diff);
  assignin('base', 'I_ratio_4580', Current_ratio);
  
  % Write summary file with name and # of completed magnets. 
   
  data_file = 'Correct_Gap_Inches_4580.txt';   
    f_title = '         Final Gap for LCLS-II Dipole 4580. \n\n' ;
    
fidC = fopen(data_file,'w');
fprintf(fidC,f_title);
fprintf(fidC,'Present Gap Average = %5.4f inches \n', present_gap);
%fprintf(fidC,'Present US Gap = %5.4f and DS Gap = %5.4f inches \n', US_gap, DS_gap);
fprintf(fidC,'Final Gap = %6.4f inches \n', Correct_gap_inches);
fprintf(fidC,'Trim %% Difference = +/- %5.2f %%  \n', Trim_per_diff/2);

fprintf(fidC,'\nCalculation Checks: \n');
fprintf(fidC,'Gap Ratio = %6.4f  (Present/Calculated) \n', Gap_ratio);
fprintf(fidC,'Integrated Field Ratio at 216.886 A near nominal current (Nominal/Measured) = %6.4f  \n', BL_ratio);
fprintf(fidC,'Current Ratio at 0.49485 Tm (Nominal Field) (Calculated/Nominal) =  %6.4f   \n', Current_ratio);

fclose(fidC);
