function[output] = skewtemplates(bw,theta,direction);
% This function is to perform rotation of the inputs. 
% bw = image to be rotatio. (has to be treshold)
% theta = degree of rotation
% direction = direction of rotation (1 = clockwise, -1 = anticlockwise)

[row col] = size(bw);

% Trying to pinpoint the exact center of the image
row1 = round(row/2);
col1 = round(col/2);

% Creating aritifical coordinates and shifting it to (0,0)
for i = 1:row
    ycord(i,:) = row1 - ones(1,col)*i;
end

for i = 1:col
    xcord(:,i) = col1 - ones(row,1)*i;
end


% Calculating the coordinates after a shift. Note that the shifted position
% of the coordinates are not intergers, but intergers for coordinates are
% used. Therefore there is a rounding function for the x and y coordinates
% which will impose imperfections on the rotated image. The direction of
% rotation can also be specified. "-1" for counter-clock wise and "1" for
% clockwise

 theta = (theta/180)*pi;
 if direction == 1
 for i = 1:row
     for j = 1:col
        xcord1(i,j) = floor(xcord(i,j)*cos(theta) + ycord(i,j)*sin(theta));
        ycord1(i,j) = floor(-xcord(i,j)*sin(theta) + ycord(i,j)*cos(theta));
    end
end
elseif direction == -1
for i = 1:row
     for j = 1:col
        xcord1(i,j) = floor(xcord(i,j)*cos(theta) - ycord(i,j)*sin(theta));
        ycord1(i,j) = floor(xcord(i,j)*sin(theta) + ycord(i,j)*cos(theta));
    end
end
else
    disp('Please input the right direction');
end

% Offsetting the image again because we cannot use negative coordinates.
% The method used is to find the max negative value for both coordinates
% and shift it by that amount +1
minx = min(min(xcord1));
miny = min(min(ycord1));


if minx <= 0
    xcord1 = xcord1 - (minx -1);
end

if miny <= 0
    ycord1 = ycord1 - (miny -1);
end

% Correlation the rotated coordinates to the original image to be rotated

 for i = 1:row
     for j = 1:col
         output(ycord1(i,j),xcord1(i,j)) = bw((row-i+1),(col-j+1));
     end
 end


 % Because of the imperfections imposed from rotating, a simple method is
 % used to counter the imperfections. All it does is to check 3 bits in a
 % row. If it detects a "1", "0", "1", then most likely an error has
 % occoured. Therefore we replace the "0" with a "1"
 [row col] = size(output);
 for i = 1:row
     for j = 1:col-3
         temp = output(i,j);
         temp1 = output(i,j+1);
         temp2 = output(i,j+2);
         if (temp == 1) & (temp1 == 0) & (temp2 == 1)
             output(i,j+1) = 1;
         else
             output(i,j+1) = temp1;
         end
     end
 end



 for i = 1:row
     output1 = nnz(output(i,:));
     if output1 >= 1
         temp = i;
         break
     end
 end
output = output(i:end,1:512);
[row col] = size(output); 
for i = 1:row
     output1 = nnz(output(i,:));
     if output1 <= 0
         temp = i;
         break
     end
 end
 output = output(1:i,:);

% figure;
% imshow(output);
