%% Compute SUM1 and MAX1 maps
clear all; close all; 
disp(['===============> Getting the SUM1 and MAX1 maps for testing images']);
load working/parameter; 
load working/testing; 
for (ii=1:nn)
testName = ['working/testingimage' num2str(ii)]; 
load(testName); 
for (s = 1 : numScale)
storeName = ['working/storedExponentialModel' num2str(s)];   
load(storeName); 
%% Prepare spaces for variables
allSizex = zeros(1, numResolution); allSizey = zeros(1, numResolution); 
MAX1maps = cell(numResolution, numOrient); 
trackMap = cell(numResolution, numOrient);
SUM2map = cell(1, numResolution); 
for(img=1:numResolution)
    [sizex, sizey] = size(J{img}); 
    allSizex(img) = sizex; allSizey(img) = sizey; % sizes of images at multiple resolutions
    sizexSubsample = floor(sizex/subsample); sizeySubsample = floor(sizey/subsample); 
    SUM2map{img} = single(zeros(floor((sizex+sizeTemplatex)/subsample), floor((sizey+sizeTemplatey)/subsample)));  % log-likelihood score maps for testing images
    averageMap{img} = single(zeros(sizex, sizey));
    for (orient=1:numOrient)
        MAX1map{img, orient} = single(zeros(sizexSubsample, sizeySubsample)); 
        trackMap{img, orient} = single(zeros(sizexSubsample, sizeySubsample));
    end
    translatedTemplate{img} = single(zeros(sizex, sizey));  % symbolic sketch on testing image
end
MAX2score = single(zeros(1, numResolution));  % maximum log-likelihood score at each resolution
Fx = zeros(1, numResolution); Fy = zeros(1, numResolution); % maximum likelihood location at each resolution
%% Compute SUM1 maps
disp(['start filtering image ' num2str(ii) ' at Gabor length ' num2str(2*halfFilterSize+1) ' at all resolutions']); tic
SUM1map = ApplyFilterfft(J, allFilter, localOrNot, localHalfx, localHalfy, thresholdFactor);  % filter testing image at all resolutions
disp(['filtering time: ' num2str(toc) ' seconds']);
%% Compute average maps
Caverage(numResolution, allSizex, allSizey, numOrient, halfFilterSize, SUM1map, averageMap, templateHalfx, templateHalfy, windowNormalizeOrNot, thresholdFactor);
%% Compute MAX1 maps and track maps
disp(['start maxing image ' num2str(ii) ' at Gabor length ' num2str(2*halfFilterSize+1) ' at all resolutions']); tic
CgetMAX1track(numResolution, allSizex, allSizey, numOrient, locationShiftLimit, orientShiftLimit, subsample, ...
              SUM1map, MAX1map, trackMap); 
disp(['maxing time: ' num2str(toc) ' seconds']);
%% Save the maps and spaces
mapName = ['working/SUMMAXmap' 'image' num2str(ii) 'scale' num2str(s)];   
save(mapName, 'SUM1map', 'MAX1map', 'trackMap', 'averageMap', 'SUM2map', 'translatedTemplate', 'MAX2score', 'Fx', 'Fy', 'allSizex', 'allSizey'); 
end
end