flatten function fixed