Re-wrote most of the DB class and added some tests etc.