Database bugfixing and refactoring
Database closing added
Konrad's changes