%   Coil_Resistance_Checkout

%  Checking the coils using resistance measurements for atleast 24 hours.

cd('C:\Magnet_Data\LCLS-II\Radiation_Detection_System\Coil')

[runs] = find_coil_resistanceplt;

for i = 1:length(runs)
   [ Coil(i), Temp(i)] = Plot_coil_resistance(runs(i));
    close all
end

% Sort data by coil number

 [coil_numbers,index] = sort([Coil.number]);
  coil_resist_coor_mean = [Coil.Coil_Resist_Corr_Mean];
  coil_resist_coor_std = [Coil.Coil_Resist_Corr_Stdev];
  coil_resist_coor_rerror = [Coil.Coil_Resist_Corr_Rerror];
  coil_rho = [Coil.rho];
  coil_run = [Coil.run];
  
  % Sort Temp data by run
  
  for i = 1:length(Temp)
      temp_diff(i) = max(Temp(i).Coil) - min(Temp(i).Coil);
  end
  
  % Does coil pass resistance test?
  for i = 1:length(coil_rho)
   CR_logic(i) = Check_Coil_Resist(coil_rho(i), coil_resist_coor_rerror(i));
  end
  
  % Sort Good from Bad coils
     num_good_coil = 1;
     num_bad_coil = 1;
   
  for i = 1:length(coil_numbers) 
    if CR_logic(index(i)) == 'Y' 
        good_coils_index(num_good_coil) = index(i);
        good_coils_num(num_good_coil) = coil_numbers(i); 
        num_good_coil = num_good_coil+1;
    end
  end

  bad_coils = setdiff(coil_numbers, good_coils_num);
  
  
  
% Write summary file with name and # of coil. 
  data_file = 'Completed Resistance Coil Checkout.txt';   
    f_title = '         Completed Resistance Coil Checkout \n' ;
    
fidC = fopen(data_file,'w');
fprintf(fidC,f_title);
fprintf(fidC,'# Complete   Coil#   Resist Mean   Resist Std   Resist Rerror  Resist-Temp Correlation  Delta Temp  Pass\n');

for i = 1:length(good_coils_index)
    fprintf(fidC,'%5i      %5i     %9.3f   %9.3f       %9.3g          %9.3f         %9.2f      %s\n', i, good_coils_num(i), coil_resist_coor_mean(good_coils_index(i)), coil_resist_coor_std(good_coils_index(i)), coil_resist_coor_rerror(good_coils_index(i)), coil_rho(good_coils_index(i)), temp_diff(coil_run(good_coils_index(i))), CR_logic(good_coils_index(i)) );        
end

 fprintf(fidC,'\nBad Coils\n')
% Print Bad Coil Runs
for i = 1:length(coil_numbers)
    for j = 1:length(bad_coils)
        if coil_numbers(i) == bad_coils(j)
         fprintf(fidC,'%5i      %5i     %9.3f   %9.3f       %9.3g          %9.3f         %9.2f      %s\n', i, coil_numbers(i), coil_resist_coor_mean(i), coil_resist_coor_std(i), coil_resist_coor_rerror(i), coil_rho(i), temp_diff(coil_run(i)), CR_logic(i) );        
        end
    end
end

 fprintf(fidC,'\n\n');
 
 
fclose(fidC);