Fixed flatten funciton