Refactoring merge patch. Removing duplicated logic with recursion.

Some logic were duplicated. I had done a baby step refactoring to notice it. Maybe I should commit on each step?

I don't know if is there any concern about efficiency.