Finished, finally

It's dog slow on the large input, but it cranks it out under the limit
and gives correct outputs, so I shouldn't complain. Thanks go to
StackOverflow user choc13 for the heuristic insight.