Fixed bugs, and optimized code a bit.