Major refactoring to eliminate nested looping.