some database function fixes and refactoring
database now fixed (hopefully) and more refactoring