refactored code to have separate insert function