more refactoring and bug fixing