made good improvements to flatten