Simplified the code to flatten