Fix undefined behavior and minor annoyances