Some refactoring of complicated code into helper functions