better implementation of flatten