Optimizations to various code

courtesy of @AgentREV