Patern matching with some performance fixes