added replace function, refactored to remove some bugs.