fixed a huge number of bugs and cleaned the code a bit