Refactor flatten middleware and add tests.