code cleanup and fixed some bugs