Reduce commits to db (big improvement on Rpi)

Reorganize slightly so that there is only one commit to db for the entire loop.