refactor to reduce memory usage, isolate concerns better