Some more refactoring and debugging