Major refactoring and code improvements.