% 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 = 25.415; % mm
DS_gap = 25.394; % mm

present_gap = (DS_gap + US_gap)/(2*25.4); % inches  Faro arm measured DS = 25.394 mm (0.99976"), US = 25.415 mm (1.006").  Gage blocks measured 1.000" US and DS


% Measured fields and currents.

BL_meas = 0.6587749;
I_meas = 126.3297006;

BL_m6_mean = mean([0.6376858, 0.6382588]);    
BL_p6_mean = mean([0.6804393, 0.6804495]);    

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*(I_nom/I_meas);  % 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_4510', Correct_gap_inches);
 assignin('base', 'Trim_per_diff_4510', Trim_per_diff);
  assignin('base', 'I_ratio_4510', Current_ratio);
  
  % Write summary file with name and # of completed magnets. 
   
  data_file = 'Correct_Gap_Inches_4510.txt';   
    f_title = '         Final Gap for LCLS-II Dipole 4510. \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/25.4, DS_gap/25.4);
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);
