Added comments and a bit of refactoring