%%% Learning from the cropped images 
close all; 
 
learnedTemplateName = ['working/learnedTemplate_' num2str(startx) '_' num2str(starty)]; 
load(learnedTemplateName);
storeExponentialModelName = ['storedExponentialModel']; 
load(storeExponentialModelName); 
SUM1MAX1mapName = ['working/SUM1MAX1map' 'image' num2str(starting)];  
load(SUM1MAX1mapName);
sizex = templateSize(1); sizey = templateSize(2);
sizexSubsample = floor(sizex/subsample); sizeySubsample = floor(sizey/subsample); 
MAX1mapLearn = cell(size(SUM1mapLearn));
ARGMAX1mapLearn = cell(size(SUM1mapLearn));
for ii = 1:size(MAX1mapLearn,1)
  [MAX1mapLearn(ii,:) ARGMAX1mapLearn(ii,:) M1RowShift M1ColShift M1OriShifted] = ...
        mexc_ComputeMAX1( SUM1mapLearn(ii,:), locationShiftLimit,...
        orientShiftLimit, subsample );
end

selectedOrient = zeros(1, numElement1);  % orientation and location of selected Gabors
selectedx = zeros(1, numElement1); 
selectedy = zeros(1, numElement1);
selectedlambda = zeros(1, numElement1); % weighting parameter for scoring template matching
selectedLogZ = zeros(1, numElement1); % normalizing constant
commonTemplate = single(zeros(sizeTemplatex, sizeTemplatey)); % template of active basis 
mexc_SharedSketch(numOrient, locationShiftLimit, orientShiftLimit, subsample, ... % about active basis  
   numElement1, numImage, sizeTemplatex, sizeTemplatey, ...
   SUM1mapLearn, MAX1mapLearn, ARGMAX1mapLearn, ... % about training images 
   halfFilterSize, Correlation, allSymbol(1, :), ... % about filters
   numStoredPoint, storedlambda, storedExpectation, storedLogZ, ... % about exponential model 
   selectedOrient, selectedx, selectedy, selectedlambda, selectedLogZ, ... % learned parameters
   commonTemplate, deformedTemplate,... % learned templates 
   M1RowShift, M1ColShift, M1OriShifted); % stored local shifts
   
% remove the low-scored Gabor elements and re-draw the template:
ind = selectedlambda >= LambdaThreshold; 
if isempty(ind)
    disp('empty!');
    pause;
end
selectedOrient = selectedOrient(ind); selectedx = selectedx(ind); selectedy = selectedy(ind); selectedLogZ = selectedLogZ(ind); selectedlambda = selectedlambda(ind);
commonTemplate = displayMatchedTemplate([partSize partSize], selectedx,selectedy,selectedOrient,zeros(length(ind),1),selectedlambda,allSymbol,numOrient);

towrite = -double(commonTemplate);
towrite = uint8(255 * (towrite-min(towrite(:)))/(max(towrite(:))-min(towrite(:))));
imwrite(towrite,['template_iter' num2str(it) '_part' num2str(startx) '_' num2str(starty) '.png']);

save(learnedTemplateName, 'numElement', 'selectedOrient', 'selectedx', 'selectedy', 'selectedlambda', 'selectedLogZ');

% load the seed image
multipleResolutionImageName = ['working/multipleResolutionImage' num2str(starting)];
load(multipleResolutionImageName);
tmp = cropped{starting} + deformedTemplate{starting}*100;

%% illustration
if GraphicsIsOn
    clf('reset');
    subplot(2,3,1:3);
    text0 = sprintf('Iter %d. #M step. Re-learn template from #cropped image patches in E step.',it);
    imshow(text2im(text0,700,80,[1 1 1]));
    subplot(2,3,4);  % new template
    imshow(-commonTemplate,[]);
    title('new template');
    pause(0.5);
    subplot(2,3,5:6);  % template matching overlay for new template
    imshow(tmp,[]);
    title('its matching');
    pause(0.5);
end


