Refactoring to make everything work