Code cleanup, and fix a minor bug