Fixed some bugs in the token replacement code