add code refactoring and some fixes