
%% this function takes the number coordinate and does a simplified version of the modulus function
%% it takes a number which is either 0 or L+1 and maps it to L and 1 respectively

function [neighbourindex]=toroid(loc,L)

% L is the size of the side of the square lattice
% loc is the linear index we want to find the neigbours of in toroidal
% co-ords
% movex, movey are values which can be 1,0,-1.
% neigbourindex returns the vector of linear ordered index of the neigbours in toroidal boundary
% conditions


sizer=[L,L];

for i=1:4
    if i==1
        movex=1;
        movey=0;
    elseif i==2
        movex=0;
        movey=1;
    elseif i==3
        movex=-1;
        movey=0;
    elseif i==4
        movex=0;
        movey=-1;
    end
[I,J] =ind2sub(L,loc); %finds the matrix entry from its linear index
I=I+movex;
J=J+movey;

if I==L+1
I=1;
elseif I==0
    I=L  ;
end

if J==L+1
J=1;
elseif J==0
    J=L  ;
end

if i==1
neighbourindex=sub2ind(sizer,I,J);
else
neighbourindex=[neighbourindex sub2ind(sizer,I,J)];
end

end
