Bug fixes and improvements

@sunglim See comments in the code comparison.