function saveSynImages(currSample, sizeTemplatex, sizeTemplatey, nTileCol, nTileRow, Corr, template, halfFilterSize, filters, savingFolder)


%%%% save the synthesized results
%%%% save each chain of synthesized images respectively in the last iteration
EachChainSynFolder=[savingFolder 'EachChainSyn/'];
if exist(EachChainSynFolder)
    rmdir(EachChainSynFolder,'s'); 
    mkdir(EachChainSynFolder);
else
    mkdir(EachChainSynFolder);
end

%%%% reconstruct each chain of synthesized images respectively in the last iteration
EachChainReconstructionFolder=[savingFolder 'EachChainReconSyn/'];
if exist(EachChainReconstructionFolder)
    rmdir(EachChainReconstructionFolder,'s'); 
    mkdir(EachChainReconstructionFolder);
else
    mkdir(EachChainReconstructionFolder);
end

curr_projected=zeros(nTileRow*sizeTemplatex,nTileCol*sizeTemplatey);
currSample2=zeros(nTileRow*sizeTemplatex,nTileCol*sizeTemplatey);

index=0;
for j=1:nTileCol
   for i=1:nTileRow
        
     index=index+1;
     crop=currSample(1+(i-1)*sizeTemplatex:sizeTemplatex+(i-1)*sizeTemplatex, 1+(j-1)*sizeTemplatey:sizeTemplatey+(j-1)*sizeTemplatey);
     gLow = min(crop(:));
     gHigh = max(crop(:));
     img = (crop-gLow)/(gHigh-gLow);
     imwrite(img,[EachChainSynFolder 'chain-' num2str(index,'%04d') '.png']);
     currSample2(1+(i-1)*sizeTemplatex:sizeTemplatex+(i-1)*sizeTemplatex, 1+(j-1)*sizeTemplatey:sizeTemplatey+(j-1)*sizeTemplatey)=img;
     
     %% project the synthesized images onto the domain specified by the selected basis
     %img_projected = reshape(R*crop(:),sx,sy);  % R = B*(inv(B'*B)*(B'));
     [~, ~, ~, img_projected]=ComputeProjectionV2(Corr,template,single(halfFilterSize),filters,crop);
     curr_projected(1+(i-1)*sizeTemplatex:sizeTemplatex+(i-1)*sizeTemplatex, 1+(j-1)*sizeTemplatey:sizeTemplatey+(j-1)*sizeTemplatey)=img_projected;
     gLow = min(img_projected(:));
     gHigh = max(img_projected(:));
     img_projected = (img_projected-gLow)/(gHigh-gLow);       
     imwrite(img_projected,[EachChainReconstructionFolder 'reconstruct_chain-' num2str(index,'%04d') '.png']);
     curr_projected(1+(i-1)*sizeTemplatex:sizeTemplatex+(i-1)*sizeTemplatex, 1+(j-1)*sizeTemplatey:sizeTemplatey+(j-1)*sizeTemplatey)=img_projected;
   end
end
imwrite(currSample2,[EachChainSynFolder 'raw.png']);
imwrite(curr_projected,[EachChainReconstructionFolder 'reconstruct.png']);