improved algorithm to iterate the db, but bugs