Improvements to make the script work in practice.

Better handling of timeouts, fix database close, etc.