fixed a number of bugs and optimized a lot of the code