De-duplicate and clean some code (mostly math).