Fix token replacement code and add result logging