%Copyright 2006, Adarsh Krishnamurthy (me.berkeley.edu/~adarsh) and Athulan Vijayaraghavan (me.berkeley.edu/~athulan)

function neigh_cells = neighbors3d(cell, n)

face = cell(1);
x = cell(2);
y = cell(3);

switch face
    case 1         
        if y == n
            N = [4 x 1];
        else
            N = [1 x y+1];
        end
        
        if y == 1
            S = [2 x n];
        else
            S = [1 x y-1];
        end
        
        if x == 1
            W = [5 n y];
        else
            W = [1 x-1 y];
        end
        
        if x == n
            E = [6 1 y];
        else
            E = [1 x+1 y];
        end
        
    case 2
        if y == n
            N = [1 x 1];
        else
            N = [2 x y+1];
        end
        
        if y == 1
            S = [3 x n];
        else
            S = [2 x y-1];
        end
        
        if x == 1
            W = [5 y 1];
        else
            W = [2 x-1 y];
        end
        
        if x == n
            E = [6 n-y+1 1];
        else
            E = [2 x+1 y];
        end
        
    case 3
        if y == n
            N = [2 x 1];
        else
            N = [3 x y+1];
        end
        
        if y == 1
            S = [4 x n];
        else
            S = [3 x y-1];
        end
        
        if x == 1
            W = [5 1 n-y+1];
        else
            W = [3 x-1 y];
        end
        
        if x == n
            E = [6 n n-y+1];
        else
            E = [3 x+1 y];
        end
        
        
    case 4
        if y == n
            N = [3 x 1];
        else
            N = [4 x y+1];
        end
        
        if y == 1
            S = [1 x n];
        else
            S = [4 x y-1];
        end
        
        if x == 1
            W = [5 n-y+1 n];
        else
            W = [4 x-1 y];
        end
        
        if x == n
            E = [6 y n];
        else
            E = [4 x+1 y];
        end
        
    case 5
        if y == n
            N = [4 1 n-x+1];
        else
            N = [5 x y+1];
        end
        
        if y == 1
            S = [2 1 x];
        else
            S = [5 x y-1];
        end
        
        if x == 1
            W = [3 1 n-y+1];
        else
            W = [5 x-1 y];
        end
        
        if x == n
            E = [1 1 y];
        else
            E = [5 x+1 y];
        end
        
    case 6
        if y == n
            N = [4 n x];
        else
            N = [6 x y+1];
        end
        
        if y == 1
            S = [2 n n-x+1];
        else
            S = [6 x y-1];
        end
        
        if x == 1
            W = [1 n y];
        else
            W = [6 x-1 y];
        end
        
        if x == n
            E = [3 n n-y+1];
        else
            E = [6 x+1 y];
        end
        
end

neigh_cells = [N; S; E; W];
