Refactoring to use pattern matching more, and fix a logic bug in the sm2 algorithm