refactoring and some error fixes