fix replace function and some small refactoring