Fixed some bugs; code cleanup