Optimize/fix recursive algorithm.