Refactoring: code greatly simplified and improved