Reworked to use heap rather than a giant stack.