Miscellaneous changes and improvements

A variety of changes to improve efficiency, readability, type safety and const correctness.