Got working logic for pattern matching