Lots of refactoring to save memory