Various cleanups

Not really a theme here, just things that caught my eye. Most of it is for readability or minor performance gains, but the last two commits contain bug fixes.