implement replace option, refactor a bit