Added database support and cleaned up the code/structure a bit.