refactored replace and insert