Holy Moley!

It's not a different function for every direction - it's one loop, with one turn, when you can't go straight in the direction you are traveling now, and loop.