Major refactoring and code clean-up