code cleanup and bug-fixes