Refactor a rather complex function.