Refactoring and insert function