This whole block is now very nested, which makes it complicated to understand and error prone. Wonder if there's an easy way to flatten it