move flatten function into util file