%%%% detect objetc by single leyer of model

function  MMAX2=detectObject(imageLoaded, clusters, iImg, numFilter, sx, sy, nOrient, ...  % general parameters
       rotateShiftLimit, detectedCroppedSavingFolder, boundingBoxSavingFolder, RatioDisplacementSUM2)


numResolution = length(imageLoaded.ImageMultiResolution);
rotationRange= -rotateShiftLimit:rotateShiftLimit;
numRotate = length(rotationRange);


%%%% align the object by detection
%% compute SUM3map
tic
SUM2map = cell(numRotate, numResolution);

for iRes = 1:numResolution
        
   SUM2map(:, iRes)=sparseFRAME_SUM2_logZ_partial(single(imageLoaded.allSizex(iRes)), single(imageLoaded.allSizey(iRes)), single(numFilter), clusters.S2T(:), single(clusters.logZ), imageLoaded.MAX1mapFind(iRes,:), single(RatioDisplacementSUM2));         
   
end

MAX2score = single(zeros(1, numResolution));  % maximum log-likelihood score at each resolution
allFx = zeros(1, numResolution); % detected location at each resolution
allFy = zeros(1, numResolution); % detected location at each resolution
MMAX2 = -1e10;
for r = 1:numRotate
    for iResolution=1:numResolution
        [MAX2score(iResolution), ind]=max(SUM2map{r,iResolution}(:));
        [allFx(iResolution), allFy(iResolution)] = ind2sub([imageLoaded.allSizex(iResolution), imageLoaded.allSizey(iResolution)],ind);
    end
    
    [maxOverResolution, ind] = max(MAX2score);   % most likely resolution
    if (MMAX2 < maxOverResolution)
        MMAX2 = maxOverResolution;
        Mrot = rotationRange(r);
        Mind = ind;  % best resoltion
        MFx = allFx(ind);
        MFy = allFy(ind);
    end
end

bestRotInd = find(Mrot==rotationRange); % best object rotation index, starting from 1
disp(['finished SUM2 map of image ' num2str(iImg) ' and detect the object: '  num2str(toc) ' seconds']);

%%% from here, we have located the object.

%%
drawBigBoundingBox;   % a section of codes to draw bounding box

%% save the croped detected object
cropedImage=single(zeros(sx, sy));
Ccopy(cropedImage, single(imageLoaded.ImageMultiResolution{Mind}), MFx, MFy, floor(sx/2), floor(sy/2), sx, sy, imageLoaded.allSizex(Mind), imageLoaded.allSizey(Mind), -Mrot*pi/nOrient);

gLow = min(cropedImage(:));
gHigh = max(cropedImage(:));
img_tem = (cropedImage-gLow)/(gHigh-gLow);
imwrite(img_tem,fullfile(detectedCroppedSavingFolder,['detected-img-' num2str(iImg,'%04d') '.png']));
save(fullfile(detectedCroppedSavingFolder,['detected-img-' num2str(iImg,'%04d') '.mat']), 'cropedImage');

