More complete solution to part 2

Needs proper testing