Bunch of minor unrelated fixes

most of these changes are pure coding style fixes, but some are fixes to handle very very unlikely error cases more gracefully