Fixed a lot of bugs, cleaned up code