Working version with some refactoring already done.