Fixed some bugs, simplified some code.