function  [c2_local] = C2_LocalMaxInBox(SSIdxs, BBoxs, S2Root, SourceLocations, PoolSize);
%function  [c2_local] = C2_LocalMaxInBox(SSIdxs, BBoxs, S2Root, SourceLocations, PoolSize);
%
%input:  the root of the c2 data (in JPGWrite3DMatrix format);
%        a list of object boxs = {ssidx, bbox}
%
%output: the maximum c2 response within a window around the expected location.

nBoxs = size(BBoxs,1);
[n_c2Features,SSResolution] = GetNC2Features(S2Root);
c2_local = zeros(n_c2Features, nBoxs);
t = cputime;
n=0;
previdx = -1;
for i = 1:nBoxs
   n = n+1;
   e = cputime;
   fprintf('%d of %d.  %d mins elapsed:  ',n,nBoxs,round((e-t)/60));
   if(SSIdxs(i) ~= previdx)
      A = JPEGRead3DMatrix(fullfile(S2Root, sprintf('%.5d',SSIdxs(i))),'C2_Data');
      previdx = SSIdxs(i);
   end
   bbox = BBoxs(i,:);
   bbox = round(CoordinateRespace(bbox,[960 1280], SSResolution,'bbox'));
   z1 = imcrop_pad(A,bbox,'symmetric');
   r = ceil(PoolSize * [size(z1,1),(size(z1,2))]);
   z2 = zeros(2*r(1)+1,2*r(2)+1,size(z1,3));
   for j = 1:size(z1,3)
     yx_rc = SourceLocations(j).yx_RelativeCenterInBBox;
     yx_c = round(yx_rc .* [size(z1,1), size(z1,2)]);
     InternalBBox = [yx_c(2:-1:1) - r(2:-1:1), 2*r(2:-1:1)];
     z2(:,:,j) = imcrop_pad(z1(:,:,j),InternalBBox,-inf);
   end
   c2_local(:,i) = permute(max(max(z2,[],1),[],2),[3,1,2]);
   e = cputime;
   cpe = ((e-t) / n)/60;
   fprintf('Cost Per Each = %f min:  ', cpe);
   fprintf('Time Remaining = %f min:  \r', cpe * (nBoxs - n));
end
fprintf('\n');

function [n_c2Features,SSResolution] = GetNC2Features(S2Root);
A = JPEGRead3DMatrix(fullfile(S2Root, sprintf('%.5d',1)),'C2_Data');
s = size(A);
n_c2Features = s(3);
SSResolution = s([1,2]);
