Finally got it working. Passes many, but not all, tests.