Further code from Junjie, in addition to minor bug fixes and
improvements.