Code cleanup and a few bugs fixed.