Major clean-up and refactoring