added recursion and a bit of sorting