Working recursive algorithm.