clear
close all

%% mex-C compilation
mex mexc_ComputeMAX1.cpp	% compute MAX1 maps
mex mexc_ComputeMAX2.cpp	% compute MAX2 maps
mex mexc_ComputeSUM2.cpp	% compute SUM2 maps
mex mexc_ComputeSUM3.cpp	% compute SUM3 maps
mex mexc_CropInstance.cpp	% crop image/map patch (according to the detected localization of template)
mex mexc_Histogram.cpp	% pool histogram from negative images
mex mexc_LocalNormalize.cpp		% local normalization
mex mexc_LocalNormalizeDouble.cpp	% local normalization of type double
mex mexc_SharedSketch.cpp	% learning by shared sketch algorithm
mex mexc_Sigmoid.cpp	% sigmoid transformation
mex mexc_TemplateAffineTransform.cpp	% affine transform of the template
mex mexc_FindS3.cpp			% find an S3 template on the image by inferring its hierarchical deformation


%% preparation
GraphicsIsOn = false; % set this to 0 if you want to turn off animation
ParameterCodeImage;
ExponentialModel; close all
SUM1MAX1;

if GraphicsIsOn
    initFigureFrame;
end

%% begin learning active basis templates inside sub-windows, with unknown local translation/rotation 
count_PartLoc = 1;
PartList = [];
for ix = 1:length(PartLocX)
    for iy = 1:length(PartLocY)
        
        startx = PartLocX(ix);
        endx = PartLocX(ix) + partSize -1;
        starty = PartLocY(iy);
        endy = PartLocY(iy) + partSize -1;
        PartList = [ PartList, [startx;starty;count_PartLoc] ];
        
        if count_PartLoc < 1 % change this to control where to start from
            count_PartLoc = count_PartLoc + 1;
            continue;
        end

        disp(sprintf('=========== Learning part at (%d %d)', startx, starty));
        
        LearnPart;
        Learn0;
        for it = 1:numIt
            SUM2MAX2;
            Learn1;
        end
        
        
        
        count_PartLoc = count_PartLoc + 1;
    end
end

%% organize the S2 dictionary: index them
numCandPart = length(PartLocX) * length(PartLocY);
S2DictPaths = cell(numCandPart,1); % It is a cell array of paths
for j = 1:numCandPart
    S2DictPaths{j} = { 'working', sprintf( 'LearnedPart_%d_%d.mat',PartList(1,j), PartList(2,j) ) };
end


% canonicalIS2IndByLoc is the list of S2 ID's for canonical templates (without rotation) per local window  
[S2Dict S2TNeighbors canonicalS2IndByLoc] = organizeS2Dictionary(S2DictPaths);
save('working/S2Dict.mat','S2Dict','S2TNeighbors','canonicalS2IndByLoc', 'S2DictPaths', 'numCandPart', 'PartList');


%% Learn an S3 template
% No learning. Use all parts
partOnOff = ones(1,numCandPart);

testFindS3;

