database fix and refactoring code