Correcting recursion algorithm