Optimized some of the code, and fixed some bugs.