Database bugfixing and refactoring