added replace function for m > 1