Add naïve cycle detection to flatten function