Refactor a rather complex function.
Merge pull request #16 from mcmtroffaes/feature/refactor

Refactor a rather complex function.