Fixed a lot of bugs and some cleanups