Refactoring the code to make it easier to reason about

This is a first step to make it easier to read the code and reason about what it does.