Overall refactoring and bug fixes