more refactoring and debugging