Spent way too much time on this problem, but it was fast enough to put me in 16th place for speed.