Database fixes for #7.

Only includes Kashif's database fixes (plus a few of my own) and should be less problematic than merging all of Kashif's changes.
I've tested it as much as I can, but someone else should have a glance over the changes before merging it.