Refactored insertion code