%% Initialize learning from the starting image 
numImage0 = 1; locationShiftLimit0 = 0; orientShiftLimit0 = 0; 

learnedTemplateName = ['working/learnedTemplate' '_' num2str(startx) '_' num2str(starty)];
load(learnedTemplateName);
storeExponentialModelName = ['storedExponentialModel']; 
load(storeExponentialModelName); 
SUM1MAX1mapName = ['working/SUM1MAX1map' 'image' num2str(starting)];   
load(SUM1MAX1mapName);
SUM1mapLearn0 = cell(1, numOrient);

for orient = 1 : numOrient
   SUM1mapLearn0{1, orient} = single(zeros(sizeTemplatex, sizeTemplatey));    
end

% crop S1 patches for part learning
destWidth = partSize; destHeight = partSize;
reflection = 1; % 1 means no reflection, -1 means reflected
% -- the following code create a transformed lattice
denseX = -floor(partSize/2) + (1:partSize);
denseY = denseX;
count = 0;
inRow = zeros(length(denseX)*length(denseY),1,'single');
inCol = zeros(length(denseX)*length(denseY),1,'single');
for y = denseY
    for x = denseX
        count = count+1;
        inRow(count) = x;
        inCol(count) = y;
    end
end
tScale = 0; rScale = 1; cScale = 1; inO = zeros(numel(inRow),1,'single'); inS = zeros(numel(inRow),1,'single');
rotation = 0;
[outRow, outCol] = ...
    mexc_TemplateAffineTransform(tScale,rScale,cScale,rotation,inRow,inCol,inO,inS,numOrient);

SUM1mapLearn0 = mexc_CropInstance( SUM1map,...
            floor(-1+startx+partSize/2),...
            floor(-1+starty+partSize/2),...
            rotation,tScale,reflection,outRow,outCol,numOrient,numScale, destWidth, destHeight );
                

subsampleM1 = 1;
[MAX1mapLearn0 ARGMAX1mapLearn0 M1RowShift M1ColShift M1OriShifted] = ...
	mexc_ComputeMAX1( SUM1mapLearn0, locationShiftLimit0,...
        orientShiftLimit0, subsample );

commonTemplate0 = single(zeros(sizeTemplatex, sizeTemplatey));               
deformedTemplate0{1} = single(zeros(sizeTemplatex, sizeTemplatey));
mexc_SharedSketch(numOrient, locationShiftLimit0, orientShiftLimit0, subsample, ... % about active basis  
	numElement1, numImage0, sizeTemplatex, sizeTemplatey, ...
	SUM1mapLearn0, MAX1mapLearn0, ARGMAX1mapLearn0, ... % about training images 
	halfFilterSize, Correlation, allSymbol(1, :), ... % about filters
	numStoredPoint, storedlambda, storedExpectation, storedLogZ, ... % about exponential model 
	selectedOrient, selectedx, selectedy, selectedlambda, selectedLogZ, ... % learned parameters
	commonTemplate0, deformedTemplate0,... % learned templates 
	M1RowShift, M1ColShift, M1OriShifted); % stored local shifts

% remove the low-scored Gabor elements and re-draw the template:
ind = selectedlambda >= LambdaThreshold;
selectedOrient = selectedOrient(ind); selectedx = selectedx(ind); selectedy = selectedy(ind); selectedLogZ = selectedLogZ(ind); selectedlambda = selectedlambda(ind);
commonTemplate0 = displayMatchedTemplate([partSize partSize], selectedx,selectedy,selectedOrient,zeros(length(ind),1),selectedlambda,allSymbol,numOrient);

towrite = -double(commonTemplate0);
towrite = uint8(255 * (towrite-min(towrite(:)))/(max(towrite(:))-min(towrite(:))));
imwrite(towrite,[category '_part_template' num2str(startx) '_' num2str(starty) '.png']);

save(learnedTemplateName, 'selectedOrient', 'selectedx', 'selectedy', 'selectedlambda', 'selectedLogZ','starting'); 
 
 %% illustration
 if GraphicsIsOn
     clf('reset');
     subplot(2,3,1:3);
     text0 = sprintf('Iter 0. #Start learning the next part-model#from a single image patch in the #seed image:%d th part out of %d',...
         count_PartLoc,length(PartLocX)*length(PartLocY));
     imshow(text2im(text0,700,80,[1 1 1]));
     pause(0.5);
     subplot(2,3,4:5); % indicates what seed patch is used
     tmp = inscribe(templateSize,J0,0);
     tmp(startx:startx+partSize-1,[starty+(0:2) starty+partSize-1+(-2:0)]) = 255;
     tmp([startx+(0:2) startx+partSize-1+(-2:0)],starty:starty+partSize-1) = 255;
     imshow(tmp,[]);
     title(sprintf('subwindow at %d %d',startx,starty));
     pause(0.5);
     subplot(2,3,6); % the learned initial template
     imshow(-commonTemplate0,[]);
     title('initially template');
     pause(0.5);
 end


