Fixed a lot of bugs in the code

Lots and lots of bug fixes