Bug fixes and improvements

@sunglim See comments in the code comparison. Also note that I've just quickly fixed the apparent bugs I noticed; I didn't run tests or anything like that.