code cleanup and bug fix