Enhanced performance of the flattening
Moved flatten to a function off the List.