More refactoring and debugging