Fixing and refactoring following Daniel's comments