Lots of bug fixes and minor tweaks