a bit of refactoring and commenting to clarify