Refactored some insert and update code