code refactoring and various bug fixes