some code cleanup and some bug fixes