Replaced recursion with reduce + cosmetics.