Refactored flatten function
Rewritten the merge function