fix undefined variable, and some code cleanup