Lots of refactoring and debugging