% Final gap calculation for 4509
% The dipoles BX31B (4510) and BX32B (4509) are on the same power supply
% and the BYD dipoles (4519 (BYD3B), 4520 (BYD2B), 4521 (BYD1B))

I_nom = 126.4349; % amps.  Nominal current fo the BYDB dipoles at 10 GeV.
BL_nom = 0.62154; % T-m. Nominal integrated field for the BX31B and BX32B dipoles when set to 126.4349 amps. 

% Calculate the final gap.
US_gap = 1.002; % inches
DS_gap = 1.005; % inches

 present_gap = mean([US_gap, DS_gap]); % inches  Mesasured by gage blocks  Upstream = 1.002 Downstream = 1.005.  Faro Arm got 1.008" +/- 0.003"

% Measured fields and currents.

BL_meas = 0.6529899;
I_meas = 126.3325561;

BL_m6_mean = mean([0.6321918, 0.6327361]);    
BL_p6_mean = mean([0.6746143, 0.6745590]);    

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/I_nom_calc;  % Ratio of integrated field at nominal integrated field of 0.62154 Tm
 BL_ratio = BL_meas/BL_nom*(126.4349/126.3297006);  % Ratio of the integrated field at 126.4349 amps, corrected for slight current difference 
Gap_ratio = Correct_gap_inches/present_gap;  % Ratio of the gap changes

 
 assignin('base', 'Correct_gap_inches_4509', Correct_gap_inches);
 assignin('base', 'Trim_per_diff_4509', Trim_per_diff);
  assignin('base', 'I_nom_calc_4509', I_nom_calc);
  
   data_file = 'Correct_Gap_Inches_4509.txt';   
    f_title = '         Final Gap for LCLS-II Dipole 4509. \n\n' ;
    
fidC = fopen(data_file,'w');
fprintf(fidC,f_title);
fprintf(fidC,'Present Gap = %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 = %5.3f 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 = %5.3f  \n', Gap_ratio);
fprintf(fidC,'Integrated Field Ratio at 126.4349 A (Nominal Current) = %5.3f  \n', BL_ratio);
fprintf(fidC,'Current Ratio at 0.62154 Tm (Nominal Field) =  %5.3f   \n', Current_ratio);

fclose(fidC);