More refactoring to reduce memory usage