Replaced flatten with pattern matching.