De-duplicate and clean some code (mostly math).
Merge branch 'master' into better-find-text