Algorithm overhaul.

This solution is much cleaner than the brute force method of the first.