Several minor improvements

I have used these patches on my server (app engine) for several months without any issues so the code is hopefully stable enough.