Complete and refactored, runs in 0.35s