refactored to build intermediate data structures
refactored