Fixed a bunch of bugs

Fixed a bunch of bugs and refined a bit