refactor bug that has undefined variable