fixed a bunch of bugs and optimized some other stuff