move flatten function