Working version after refactoring