Better pattern matching (removed duplication)