some refactoring; fixed bug that could crash the db