function PROC_RecordSSDBC2(RecordingRoot, caS2Centroids,Mandate);
%function PROC_RecordSSDBC2(RecordingRoot, caS2Centroids,Mandate);
%
%Note, the title of this function is a misnomer, it shoudl be S2.
%
%This function will overwrite previous results if it thinks there is an error
%for instance if a layer has a NaN, imaginary value, or all zeros
%any indicies in mandate will automatically be recomputed.
bReweightLayers = 1;

if(size(caS2Centroids{1},3) == 4)
   USE_ALL_C1_SCALES = 0;
else
   USE_ALL_C1_SCALES = 1;
end

if(USE_ALL_C1_SCALES)
   level = 'all';
else
   level = 1;
end
seedrand;
p = randperm(3547);
n = 0;
t=cputime;
%for i = p;
for i = 1:3547   
   n = n+1;
   e = cputime;
   fprintf('%d of %d.  %d mins elapsed\r',n,length(p),round((e-t)/60));
   %[bIsOk,txt] = check_JPEGMatrix(fullfile(RecordingRoot, sprintf('%.5d',i)), 'C2_Data');
   bIsOk = 1;,txt = '';
   if(not(bIsOk) || not(isempty(intersect(i,Mandate))))
      fprintf('\nediting %d (%d)\n',n,i);
      sprintf(txt);
      if(not(isdir(fullfile(RecordingRoot, sprintf('%.5d',i)))))
         mkdir(RecordingRoot, sprintf('%.5d',i));
      end
      c1Im = GetC1Img(i,level);
%      S2Map = C1Im_caS2Centroid_2_S2Map_SumNormXCorr(c1Im, caS2Centroids,bReweightLayers);
      S2Map = C1Im_caS2Centroid_2_S2Map_EucDist(c1Im, caS2Centroids);
      JPEGWrite3DMatrix(S2Map,fullfile(RecordingRoot, sprintf('%.5d',i)),'C2_Data');
%      [bIsOk,txt,A] = check_JPEGMatrix(fullfile(RecordingRoot, sprintf('%.5d',i)), 'C2_Data');
%      if(not(bIsOk))
%         fprintf('Error: PROC_RecordSSDBC2, item %d\n',i);
%	 fprintf('JPEG Matrix was still unsatisfactory after a safe build\n');
%	 keyboard;
%      end
   end
end

