Refactor the insert function into sub-functions