code cleanup and a couple bug fixes