more refactoring (mostly db), and a logic error in the main file