Fixed some bugs and undefined variables in the new code.