flatten: improve flattening order