Further refactoring: added comments and separation of duties.