Rewritten the flatten function