Lots of bug fixes, some code cleanup