Fixed flatten function