code cleanup and minor bug fixes