Major refactoring and bug fixes