Some code refactoring and bug fixing