Somehow managed to generalize the adjacent() function. I think it works for all cases but it needs to be tested a lot more.