Refactored first run and upgrade code
Closes #131
Moved database stuff to its own package