Refactor

I've added a few helper functions to simplify preexisting code. I guess the should be moved to a more general location later on.

I've also added some tests. More details in the commit message.