Refactor nested merge function

An attempt to make it a bit clearer what's happening.