function [S2T] = transformTemplate(sx, sy, rotateShiftLimit, numOrient, template, nScaleGabor)



selectedFilter = template.selectedFilter;
selectedRow = template.selectedRow - round(sx/2) +1;  % index starts from 1
selectedCol = template.selectedCol - round(sy/2) +1;  % index starts from 1
selectedlambda = template.selectedLambdas;  



allSelectedRow = []; % cell(numPart, numPartRotate); 
allSelectedCol = []; %cell(numPart, numPartRotate);
allSelectedFilter = []; %cell(numPart, numPartRotate);

   
 numElement=template.numSelected; 
 
 for (rot = -rotateShiftLimit : rotateShiftLimit)  
  
    theta = -pi*rot/numOrient;
    sintheta = sin(theta);
    costheta = cos(theta);    
     
    r = rot+rotateShiftLimit+1;
   
    if (rot == 0)
       for (i=1: numElement)
           allSelectedRow(r,i) = selectedRow(i);
           allSelectedCol(r,i) = selectedCol(i);
           allSelectedFilter(r,i) = selectedFilter(i); 
       end
                      
    else
       for (i=1: numElement)
           allSelectedRow(r,i) = selectedRow(i)*costheta + selectedCol(i)*sintheta;
           allSelectedCol(r,i) = -selectedRow(i)*sintheta + selectedCol(i)*costheta;
                
           if  selectedFilter(i)> nScaleGabor * numOrient *2  % DoG
                   allSelectedFilter(r,i) = selectedFilter(i);
                
           else   % Gabor
                   iScale=floor((selectedFilter(i)-1)/numOrient); % index of iScale starts from 0;
                   iOri= mod(selectedFilter(i)-1,numOrient);  % index of iOri starts from 0;
                   newOri = iOri + rot;
                   if (newOri>=numOrient)
                       newOri = newOri - numOrient;
                   end
                   if (newOri<0)
                       newOri = newOri + numOrient;
                   end
                   allSelectedFilter(r,i) = iScale*numOrient + newOri+1; % index of filter starts from 1;  
          end
       end
    end    
 end



numRotate = 2*rotateShiftLimit+1; 
% organize the S2 part template
S2T = cell( numRotate, 1 );
for r = 1:numRotate
      S2T{r} = struct( 'selectedRow',single( round(allSelectedRow(r,:))),...
            'selectedCol', single( round(allSelectedCol(r,:))),...
            'selectedFilter', single(allSelectedFilter(r,:)),...           
            'selectedLambdas', single(selectedlambda),...
            'numSelected', single(length(allSelectedRow(r,:))) );
end



